import React, { memo, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBreadcrumb } from '../../../layout/LayoutBreadcrumb';
import { Typography, Table, Card, Select, DatePicker, Button, Row, Col } from 'antd';
import { FileTextOutlined } from '@ant-design/icons';
import { decryptData } from '../../../components/Global/Formatter';
import dayjs from 'dayjs';

const { Text } = Typography;

// New data structure for tag history
const tagHistoryData = [
    {
        tag: 'TEMP_SENSOR_1',
        color: '#FF6B4A',
        history: [
            { timestamp: '2025-10-09 08:00', value: 75 },
            { timestamp: '2025-10-09 08:05', value: 76 },
            { timestamp: '2025-10-09 08:10', value: 75 },
        ],
    },
    {
        tag: 'GAS_LEAK_SENSOR_1',
        color: '#4ECDC4',
        history: [
            { timestamp: '2025-10-09 08:00', value: 10 },
            { timestamp: '2025-10-09 08:05', value: 150 },
            { timestamp: '2025-10-09 08:10', value: 12 },
        ],
    },
    {
        tag: 'PRESSURE_SENSOR_1',
        color: '#FFE66D',
        history: [
            { timestamp: '2025-10-09 08:00', value: 1.2 },
            { timestamp: '2025-10-09 08:05', value: 1.3 },
            { timestamp: '2025-10-09 08:10', value: 1.2 },
        ],
    },
];

const IndexReport = memo(function IndexReport() {
    const navigate = useNavigate();
    const { setBreadcrumbItems } = useBreadcrumb();

    const [plantSubSection, setPlantSubSection] = useState('Semua Plant');
    const [startDate, setStartDate] = useState(dayjs('2025-09-30'));
    const [endDate, setEndDate] = useState(dayjs('2025-10-09'));
    const [periode, setPeriode] = useState('30 Menit');
    const [userRole, setUserRole] = useState(null);
    const [roleLevel, setRoleLevel] = useState(null);

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            // Get user data and role
            let userData = null;
            const sessionData = localStorage.getItem('session');
            if (sessionData) {
                userData = decryptData(sessionData);
            } else {
                const userRaw = localStorage.getItem('user');
                if (userRaw) {
                    try {
                        userData = { user: JSON.parse(userRaw) };
                    } catch (e) {
                        console.error('Error parsing user data:', e);
                    }
                }
            }

            if (userData?.user) {
                setUserRole(userData.user.role_name);
                setRoleLevel(userData.user.role_level);
            }

            setBreadcrumbItems([
                {
                    title: (
                        <Text strong style={{ fontSize: '14px' }}>
                            • History
                        </Text>
                    ),
                },
                {
                    title: (
                        <Text strong style={{ fontSize: '14px' }}>
                            Report
                        </Text>
                    ),
                },
            ]);
        } else {
            navigate('/signin');
        }
    }, []);

    const handleReset = () => {
        setPlantSubSection('Semua Plant');
        setStartDate(dayjs('2025-09-30'));
        setEndDate(dayjs('2025-10-09'));
        setPeriode('30 Menit');
    };

    // Check if user has permission to view data (all except guest)
    const canViewData = userRole && userRole !== 'guest';

    // Convert tag history data to table format
    const convertToTableData = () => {
        const timestamps = {}; // Use an object to collect data per timestamp

        tagHistoryData.forEach((tagData) => {
            tagData.history.forEach((point) => {
                if (!timestamps[point.timestamp]) {
                    timestamps[point.timestamp] = {
                        key: point.timestamp,
                        'Date and Time': point.timestamp,
                    };
                }
                timestamps[point.timestamp][tagData.tag] = point.value;
            });
        });

        // Convert the object to an array
        return Object.values(timestamps);
    };

    const tableData = convertToTableData();

    // Create dynamic columns based on tags
    const tags = tagHistoryData.map((tagData) => tagData.tag);

    const columns = [
        {
            title: 'Date and Time',
            dataIndex: 'Date and Time',
            key: 'Date and Time',
            fixed: 'left',
            width: 180,
            render: (text) => <Text strong>{text}</Text>,
        },
        ...tags.map((tag) => ({
            title: tag,
            dataIndex: tag,
            key: tag,
            align: 'center',
            width: 150,
            render: (value) => <Text>{value !== undefined ? value : '-'}</Text>,
        })),
    ];

    return (
        <React.Fragment>
            <div style={{ minHeight: 360 }}>
                {/* Filter Section */}
                <Card className="filter-card">
                    <div className="filter-header">
                        <Text strong style={{ fontSize: '14px' }}>
                            ☰ Filter Data
                        </Text>
                    </div>
                    <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={setPlantSubSection}
                                    style={{ width: '100%', marginTop: '4px' }}
                                    options={[
                                        { value: 'Semua Plant', label: 'Semua Plant' },
                                        { value: 'Plant 1', label: 'Plant 1' },
                                        { value: 'Plant 2', label: 'Plant 2' },
                                    ]}
                                />
                            </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 Menit', label: '5 Menit' },
                                        { value: '10 Menit', label: '10 Menit' },
                                        { value: '30 Menit', label: '30 Menit' },
                                        { value: '1 Jam', label: '1 Jam' },
                                    ]}
                                />
                            </div>
                        </Col>
                    </Row>
                    <Row gutter={8} style={{ marginTop: '16px' }}>
                        <Col>
                            <Button
                                type="primary"
                                danger
                                icon={<FileTextOutlined />}
                                disabled={!canViewData}
                            >
                                Tampilkan
                            </Button>
                        </Col>
                        <Col>
                            <Button
                                onClick={handleReset}
                                style={{ backgroundColor: '#6c757d', color: 'white' }}
                                disabled={!canViewData}
                            >
                                Reset
                            </Button>
                        </Col>
                    </Row>
                </Card>
                {/* Table Section */}
                {/* {!canViewData ? (
                    <Card style={{ marginTop: '24px', textAlign: 'center', padding: '40px' }}>
                        <Text style={{ fontSize: '16px', color: '#999' }}>
                            Anda tidak memiliki akses untuk melihat data report.
                            <br />
                            Silakan hubungi administrator untuk mendapatkan akses.
                        </Text>
                    </Card>
                ) : ( */}
                <Card style={{ marginTop: '24px' }}>
                    <div style={{ marginBottom: '16px' }}>
                        <Text strong style={{ fontSize: '16px' }}>
                            ☰ History Report
                        </Text>
                    </div>
                    <Table
                        columns={columns}
                        dataSource={tableData}
                        pagination={false}
                        scroll={{ x: 1000 }}
                        size="middle"
                    />
                </Card>
                {/* )} */}
            </div>
        </React.Fragment>
    );
});

export default IndexReport;
