import React, { memo, useState, useEffect } from 'react';
import {
    Space,
    Tag,
    ConfigProvider,
    Button,
    Row,
    Col,
    Card,
    Divider,
    Form,
    Input,
    Dropdown,
} from 'antd';
import {
    PlusOutlined,
    FilterOutlined,
    EditOutlined,
    DeleteOutlined,
    EyeOutlined,
    SearchOutlined,
    FilePdfOutlined,
    FileExcelOutlined,
    EllipsisOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifOk, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import { deleteApd, getAllApd } from '../../../../api/master-apd';
import { deleteDevice, getAllDevice } from '../../../../api/master-device';
import TableList from '../../../../components/Global/TableList';
import { getFilterData } from '../../../../components/Global/DataFilter';
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
import logoPiEnergi from '../../../../assets/images/logo/pi-energi.png';

const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
    {
        title: 'ID',
        dataIndex: 'device_id',
        key: 'device_id',
        width: '5%',
        hidden: 'true',
    },
    {
        title: 'Device Code',
        dataIndex: 'device_code',
        key: 'device_code',
        width: '10%',
    },
    {
        title: 'Device Name',
        dataIndex: 'device_name',
        key: 'device_name',
        width: '20%',
    },
    {
        title: 'Location',
        dataIndex: 'device_location',
        key: 'device_location',
        width: '10%',
    },
    {
        title: 'IP Address',
        dataIndex: 'ip_address',
        key: 'ip_address',
        width: '10%',
    },
    {
        title: 'Status',
        dataIndex: 'device_status',
        key: 'device_status',
        width: '10%',
        align: 'center',
        render: (_, { device_status }) => (
            <>
                {device_status === true ? (
                    <Tag color={'green'} key={'status'}>
                        Running
                    </Tag>
                ) : (
                    <Tag color={'red'} key={'status'}>
                        Offline
                    </Tag>
                )}
            </>
        ),
    },
    {
        title: 'Aksi',
        key: 'aksi',
        align: 'center',
        width: '15%',
        render: (_, record) => (
            <Space>
                <Button
                    type="text"
                    style={{ borderColor: '#1890ff' }}
                    icon={<EyeOutlined style={{ color: '#1890ff' }} />}
                    onClick={() => showPreviewModal(record)}
                />
                <Button
                    type="text"
                    style={{ borderColor: '#faad14' }}
                    icon={<EditOutlined style={{ color: '#faad14' }} />}
                    onClick={() => showEditModal(record)}
                />
                <Button
                    type="text"
                    danger
                    style={{ borderColor: 'red' }}
                    icon={<DeleteOutlined />}
                    onClick={() => showDeleteDialog(record)}
                />
            </Space>
        ),
    },
];

const ListDevice = memo(function ListDevice(props) {
    const [showFilter, setShowFilter] = useState(false);
    const [trigerFilter, setTrigerFilter] = useState(false);

    const defaultFilter = { search: '' };
    const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
    const [searchValue, setSearchValue] = useState('');

    const navigate = useNavigate();

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            if (props.actionMode == 'list') {
                setFormDataFilter(defaultFilter);
                doFilter();
            }
        } else {
            navigate('/signin');
        }
    }, [props.actionMode]);

    const toggleFilter = () => {
        setFormDataFilter(defaultFilter);
        setShowFilter((prev) => !prev);
    };

    const doFilter = () => {
        setTrigerFilter((prev) => !prev);
    };

    const handleSearch = () => {
        setFormDataFilter({ search: searchValue });
        setTrigerFilter((prev) => !prev);
    };

    const handleSearchClear = () => {
        setSearchValue('');
        setFormDataFilter({ search: '' });
        setTrigerFilter((prev) => !prev);
    };

    const showPreviewModal = (param) => {
        props.setSelectedData(param);
        props.setActionMode('preview');
    };

    const showEditModal = (param = null) => {
        props.setSelectedData(param);
        props.setActionMode('edit');
    };

    const showAddModal = (param = null) => {
        props.setSelectedData(param);
        props.setActionMode('add');
    };

    const showDeleteDialog = (param) => {
        NotifConfirmDialog({
            icon: 'question',
            title: 'Konfirmasi',
            message: 'Apakah anda yakin hapus data "' + param.device_name + '" ?',
            onConfirm: () => handleDelete(param.device_id),
            onCancel: () => props.setSelectedData(null),
        });
    };

    const handleDelete = async (device_id) => {
        const response = await deleteDevice(device_id);

        if (response.statusCode == 200) {
            NotifAlert({
                icon: 'success',
                title: 'Berhasil',
                message: 'Data Device "' + response.data.device_name + '" berhasil dihapus.',
            });
            doFilter();
        } else {
            NotifOk({
                icon: 'error',
                title: 'Gagal',
                message: 'Gagal Menghapus Data Device',
            });
        }
    };

    const generatePdf = () => {
        props.setActionMode('generatepdf');
    };

    const exportExcel = async () => {
        const data = getFilterData();

        const workbook = new ExcelJS.Workbook();
        const sheet = workbook.addWorksheet('Data APD');
        let rowCursor = 1;
        // Kop Logo PIE
        if (logoPiEnergi) {
            const response = await fetch(logoPiEnergi);
            const blob = await response.blob();
            const buffer = await blob.arrayBuffer();

            const imageId = workbook.addImage({
                buffer,
                extension: 'png',
            });

            // Tempatkan gambar di pojok atas
            sheet.addImage(imageId, {
                tl: { col: 0.2, row: 0.8 },
                ext: { width: 163, height: 80 },
            });

            sheet.getRow(5).height = 15; // biar ada jarak ke tabel
            rowCursor = 3;
        }

        // Tambah Judul
        const titleCell = sheet.getCell(`C${rowCursor}`);
        titleCell.value = 'Data APD';
        titleCell.font = { size: 20, bold: true, color: { argb: 'FF00AEEF' } };
        titleCell.alignment = { vertical: 'middle', horizontal: 'center' };
        sheet.mergeCells(`C${rowCursor}:F${rowCursor}`);

        // Header tabel
        const headers = [
            'ID APD',
            'Nama APD',
            'Deskripsi',
            'Jenis Permit Default',
            'Aktif',
            'Dibuat',
            'Diubah',
        ];
        sheet.addRow(headers);
        const headerRow = sheet.getRow(6);
        headerRow.font = { bold: true, size: 12 };
        headerRow.eachCell((cell) => {
            cell.alignment = {
                horizontal: 'center', // rata tengah kiri-kanan
                vertical: 'middle', // rata tengah atas-bawah
            };
        });

        // Tambahkan data
        data.forEach((item) => {
            sheet.addRow([
                item.id_apd,
                item.nama_apd,
                item.deskripsi_apd ?? '',
                item.jenis_permit_default ?? '',
                item.is_active ? 'Ya' : 'Tidak',
                new Date(item.created_at).toLocaleString(),
                new Date(item.updated_at).toLocaleString(),
            ]);
        });

        // Auto width
        sheet.columns.forEach((col) => {
            let maxLength = 10;
            col.eachCell({ includeEmpty: true }, (cell) => {
                const len = cell.value?.toString().length || 0;
                if (len > maxLength) maxLength = len;
            });
            col.width = maxLength + 2;
        });

        // Export
        const buffer = await workbook.xlsx.writeBuffer();
        saveAs(new Blob([buffer]), 'Data_APD.xlsx');
    };

    return (
        <React.Fragment>
            <Card>
                <Row>
                    <Col xs={24}>
                        <Row justify="space-between" align="middle" gutter={[8, 8]}>
                            <Col xs={24} sm={24} md={12} lg={12}>
                                <Input.Search
                                    placeholder="Search device by name, code, or location..."
                                    value={searchValue}
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setSearchValue(value);
                                        // Auto search when clearing by backspace/delete
                                        if (value === '') {
                                            setFormDataFilter({ search: '' });
                                            setTrigerFilter((prev) => !prev);
                                        }
                                    }}
                                    onSearch={handleSearch}
                                    allowClear={{
                                        clearIcon: <span onClick={handleSearchClear}>✕</span>,
                                    }}
                                    enterButton={
                                        <Button
                                            type="primary"
                                            icon={<SearchOutlined />}
                                            style={{
                                                backgroundColor: '#23A55A',
                                                borderColor: '#23A55A',
                                            }}
                                        >
                                            Search
                                        </Button>
                                    }
                                    size="large"
                                />
                            </Col>
                            <Col>
                                <Space wrap size="small">
                                    <ConfigProvider
                                        theme={{
                                            token: { colorBgContainer: '#E9F6EF' },
                                            components: {
                                                Button: {
                                                    defaultBg: 'white',
                                                    defaultColor: '#23A55A',
                                                    defaultBorderColor: '#23A55A',
                                                    defaultHoverColor: '#23A55A',
                                                    defaultHoverBorderColor: '#23A55A',
                                                },
                                            },
                                        }}
                                    >
                                        <Button
                                            icon={<PlusOutlined />}
                                            onClick={() => showAddModal()}
                                            size="large"
                                        >
                                            Tambah Data
                                        </Button>
                                    </ConfigProvider>
                                </Space>
                            </Col>
                        </Row>
                    </Col>
                    <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginTop: '16px' }}>
                        <TableList
                            getData={getAllDevice}
                            queryParams={formDataFilter}
                            columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
                            triger={trigerFilter}
                        />
                    </Col>
                </Row>
            </Card>
        </React.Fragment>
    );
});

export default ListDevice;
