import React, { memo, useState, useEffect } from 'react';
import { Button, Row, Col, Card, Input, DatePicker, Select, Typography } from 'antd';
import TableList from '../../../../components/Global/TableList';
import dayjs from 'dayjs';
import { FileTextOutlined } from '@ant-design/icons';
import {
    getAllHistoryValueReport,
    getAllHistoryValueReportPivot,
} from '../../../../api/history-value';
import { getAllPlantSection } from '../../../../api/master-plant-section';

const { Text } = Typography;

const ListReport = memo(function ListReport(props) {
    const columns = [
        {
            title: 'No',
            key: 'no',
            width: '5%',
            align: 'center',
            render: (_, __, index) => index + 1,
        },
        {
            title: 'Datetime',
            dataIndex: 'datetime',
            key: 'datetime',
            width: '15%',
        },
        {
            title: 'Tag Name',
            dataIndex: 'tag_name',
            key: 'tag_name',
            width: '70%',
        },
        // {
        //     title: 'Value',
        //     dataIndex: 'val',
        //     key: 'val',
        //     width: '10%',
        //     render: (_, record) => Number(record.val).toFixed(4),
        // },
        // {
        //     title: 'Stat',
        //     dataIndex: 'status',
        //     key: 'status',
        //     width: '10%',
        // },
    ];

    const dateNow = dayjs();
    const dateNowFormated = dateNow.format('YYYY-MM-DD');

    const [trigerFilter, setTrigerFilter] = useState(false);

    const [plantSubSection, setPlantSubSection] = useState(0);
    const [plantSubSectionList, setPlantSubSectionList] = useState([]);
    const [startDate, setStartDate] = useState(dateNow);
    const [endDate, setEndDate] = useState(dateNow);
    const [periode, setPeriode] = useState(10);

    const defaultFilter = {
        criteria: '',
        plant_sub_section_id: 0,
        from: dateNowFormated,
        to: dateNowFormated,
        interval: periode,
    };
    const [formDataFilter, setFormDataFilter] = useState(defaultFilter);

    const handleSearch = () => {
        const formattedDateStart = startDate.format('YYYY-MM-DD');
        const formattedDateEnd = endDate.format('YYYY-MM-DD');

        setFormDataFilter({
            criteria: '',
            plant_sub_section_id: plantSubSection,
            from: formattedDateStart,
            to: formattedDateEnd,
            interval: periode,
        });
        setTrigerFilter((prev) => !prev);
    };

    const handleReset = () => {
        setPlantSubSection(0);
        setStartDate(dateNow);
        setEndDate(dateNow);
        setPeriode(5);
    };

    const getPlantSubSection = async () => {
        const params = new URLSearchParams({ page: 1 });
        const response = await getAllPlantSection(params);

        if (response && response.data) {
            const activePlantSubSections = response.data.filter(
                (section) => section.is_active === true
            );
            setPlantSubSectionList(activePlantSubSections);
        }
    };

    useEffect(() => {
        getPlantSubSection();
    }, []);

    return (
        <React.Fragment>
            <Card>
                <Row>
                    <Col xs={24}>
                        <Row gutter={16} style={{ marginTop: '16px' }}>
                            <Col xs={24} sm={12} md={6}>
                                <div className="filter-item">
                                    <Text style={{ fontSize: '12px', color: '#666' }}>
                                        Plant Sub Section
                                    </Text>
                                    <Select
                                        value={plantSubSection}
                                        onChange={(value) => setPlantSubSection(value)}
                                        style={{ width: '100%', marginTop: '4px' }}
                                    >
                                        <Select.Option key={0} value={0}>
                                            Pilih Plant Sub Section
                                        </Select.Option>
                                        {plantSubSectionList.map((item) => (
                                            <Select.Option
                                                key={item.plant_sub_section_id}
                                                value={item.plant_sub_section_id}
                                            >
                                                {item.plant_sub_section_name}
                                            </Select.Option>
                                        ))}
                                    </Select>
                                </div>
                            </Col>
                            <Col xs={24} sm={12} md={6}>
                                <div className="filter-item">
                                    <Text style={{ fontSize: '12px', color: '#666' }}>
                                        Tanggal Mulai
                                    </Text>
                                    <DatePicker
                                        value={startDate}
                                        onChange={setStartDate}
                                        format="DD-MM-YYYY"
                                        style={{ width: '100%', marginTop: '4px' }}
                                    />
                                </div>
                            </Col>
                            <Col xs={24} sm={12} md={6}>
                                <div className="filter-item">
                                    <Text style={{ fontSize: '12px', color: '#666' }}>
                                        Tanggal Akhir
                                    </Text>
                                    <DatePicker
                                        value={endDate}
                                        onChange={setEndDate}
                                        format="DD-MM-YYYY"
                                        style={{ width: '100%', marginTop: '4px' }}
                                    />
                                </div>
                            </Col>
                            <Col xs={24} sm={12} md={6}>
                                <div className="filter-item">
                                    <Text style={{ fontSize: '12px', color: '#666' }}>Periode</Text>
                                    <Select
                                        value={periode}
                                        onChange={setPeriode}
                                        style={{ width: '100%', marginTop: '4px' }}
                                        options={[
                                            { value: 5, label: '5 Minute' },
                                            { value: 10, label: '10 Minute' },
                                            { value: 30, label: '30 Minute' },
                                            { value: 60, label: '1 Hour' },
                                            { value: 120, label: '2 Hour' },
                                        ]}
                                    ></Select>
                                </div>
                            </Col>
                        </Row>
                        <Row gutter={8} style={{ marginTop: '16px' }}>
                            <Col>
                                <Button
                                    type="primary"
                                    danger
                                    icon={<FileTextOutlined />}
                                    onClick={handleSearch}
                                >
                                    Show
                                </Button>
                            </Col>
                            <Col>
                                <Button
                                    onClick={handleReset}
                                    style={{ backgroundColor: '#6c757d', color: 'white' }}
                                >
                                    Reset
                                </Button>
                            </Col>
                        </Row>
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
                        <TableList
                            firstLoad={false}
                            mobile
                            cardColor={'#d38943ff'}
                            header={'datetime'}
                            getData={getAllHistoryValueReportPivot}
                            queryParams={formDataFilter}
                            columns={columns}
                            columnDynamic={'columns'}
                            triger={trigerFilter}
                        />
                    </Col>
                </Row>
            </Card>
        </React.Fragment>
    );
});

export default ListReport;
