import React, { memo, useState, useEffect } from 'react';
import { Space, Tag, ConfigProvider, Button, Row, Col, Card, Input } from 'antd';
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    EyeOutlined,
    SearchOutlined,
} from '@ant-design/icons';
import { NotifAlert, NotifConfirmDialog } from '../../../../components/Global/ToastNotif';
import { useNavigate } from 'react-router-dom';
import TableList from '../../../../components/Global/TableList';

// Dummy data
const initialTagsData = [
    {
        tag_id: 1,
        tag_code: 'J06-OPEN',
        tag_name: 'tag 1',
        tag_value: 'On',
        tag_type: 'alarm',
        tag_description: 'test1',
    },
    {
        tag_id: 2,
        tag_code: 'J06-CLS',
        tag_name: 'tag 2',
        tag_value: 'Off',
        tag_type: 'alarm',
        tag_description: 'tes2',
    },
    {
        tag_id: 3,
        tag_code: 'J06-VRS',
        tag_name: 'tag 3',
        tag_value: 'Critical',
        tag_type: 'measurement',
        tag_description: 'test3',
    },
    {
        tag_id: 4,
        tag_code: 'J07-IR',
        tag_name: 'tag 4 R',
        tag_value: 'On',
        tag_type: 'measurement',
        tag_description: 'test 4',
    },
    {
        tag_id: 5,
        tag_code: 'K01-CLS',
        tag_name: 'tag 5',
        tag_value: 'Off',
        tag_type: 'alarm',
        tag_description: 'tes5',
    },
    {
        tag_id: 6,
        tag_code: 'J07-IS',
        tag_name: 'tag6',
        tag_value: 'On',
        tag_type: 'measurement',
        tag_description: 'tes6',
    },
    {
        tag_id: 7,
        tag_code: 'J07-IT',
        tag_name: 'tag7',
        tag_value: 'Critical',
        tag_type: 'measurement',
        tag_description: 'tes7',
    },
    {
        tag_id: 8,
        tag_code: 'J06-VST',
        tag_name: 'tag8',
        tag_value: 'On',
        tag_type: 'measurement',
        tag_description: 'tes8',
    },
    {
        tag_id: 9,
        tag_code: 'J06-VTR',
        tag_name: 'tag9',
        tag_value: 'On',
        tag_type: 'measurement',
        tag_description: 'tes9',
    },
    {
        tag_id: 10,
        tag_code: 'K02-OPEN',
        tag_name: 'tag10',
        tag_value: 'On',
        tag_type: 'alarm',
        tag_description: 'tes10',
    },
    {
        tag_id: 11,
        tag_code: 'K02-CLS',
        tag_name: 'Kontaktor K02 Close',
        tag_value: 'Off',
        tag_type: 'alarm',
        tag_description: 'Kontaktor K02 dalam kondisi tertutup',
    },
    {
        tag_id: 12,
        tag_code: 'J08-FREQ',
        tag_name: 'Frequency',
        tag_value: 'On',
        tag_type: 'measurement',
        tag_description: 'Frekuensi sistem normal (50Hz)',
    },
    {
        tag_id: 13,
        tag_code: 'J08-PF',
        tag_name: 'Power Factor',
        tag_value: 'Critical',
        tag_type: 'measurement',
        tag_description: 'Power factor rendah, perlu perbaikan',
    },
    {
        tag_id: 14,
        tag_code: 'TR01-TEMP',
        tag_name: 'Transformer Temperature',
        tag_value: 'Critical',
        tag_type: 'alarm',
        tag_description: 'Suhu trafo melebihi batas aman',
    },
    {
        tag_id: 15,
        tag_code: 'TR01-OIL',
        tag_name: 'Transformer Oil Level',
        tag_value: 'On',
        tag_type: 'alarm',
        tag_description: 'Level oli trafo normal',
    },
    {
        tag_id: 16,
        tag_code: 'GEN01-RUN',
        tag_name: 'Generator Running',
        tag_value: 'Off',
        tag_type: 'alarm',
        tag_description: 'Generator dalam kondisi mati',
    },
    {
        tag_id: 17,
        tag_code: 'GEN01-FUEL',
        tag_name: 'Generator Fuel Level',
        tag_value: 'On',
        tag_type: 'measurement',
        tag_description: 'Level bahan bakar generator mencukupi',
    },
    {
        tag_id: 18,
        tag_code: 'UPS01-BAT',
        tag_name: 'UPS Battery Status',
        tag_value: 'On',
        tag_type: 'alarm',
        tag_description: 'Status battery UPS normal',
    },
    {
        tag_id: 19,
        tag_code: 'UPS01-LOAD',
        tag_name: 'UPS Load',
        tag_value: 'Critical',
        tag_type: 'measurement',
        tag_description: 'Beban UPS mendekati kapasitas maksimal',
    },
    {
        tag_id: 20,
        tag_code: 'PANEL-DOOR',
        tag_name: 'Panel Door Status',
        tag_value: 'Off',
        tag_type: 'alarm',
        tag_description: 'Pintu panel tertutup',
    },
];

const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
    {
        title: 'ID',
        dataIndex: 'tag_id',
        key: 'tag_id',
        width: '5%',
        hidden: 'true',
    },
    {
        title: 'Tag Code',
        dataIndex: 'tag_code',
        key: 'tag_code',
        width: '10%',
    },
    {
        title: 'Tag Name',
        dataIndex: 'tag_name',
        key: 'tag_name',
        width: '20%',
    },
    {
        title: 'Value',
        dataIndex: 'tag_value',
        key: 'tag_value',
        width: '10%',
        align: 'center',
        render: (_, { tag_value }) => {
            let color = 'default';
            if (tag_value.toLowerCase() === 'on') color = 'green';
            else if (tag_value.toLowerCase() === 'off') color = 'gray';
            else if (tag_value.toLowerCase() === 'critical') color = 'red';
            return (
                <Tag color={color} key={'value'}>
                    {tag_value}
                </Tag>
            );
        },
    },
    {
        title: 'Type',
        dataIndex: 'tag_type',
        key: 'tag_type',
        width: '10%',
    },
    {
        title: 'Description',
        dataIndex: 'tag_description',
        key: 'tag_description',
        width: '25%',
    },
    {
        title: 'Aksi',
        key: 'aksi',
        align: 'center',
        width: '15%',
        render: (_, record) => (
            <Space>
                <Button
                    type="text"
                    icon={<EyeOutlined />}
                    onClick={() => showPreviewModal(record)}
                    style={{
                        color: '#1890ff',
                        borderColor: '#1890ff',
                    }}
                />
                <Button
                    type="text"
                    icon={<EditOutlined />}
                    onClick={() => showEditModal(record)}
                    style={{
                        color: '#faad14',
                        borderColor: '#faad14',
                    }}
                />
                <Button
                    danger
                    type="text"
                    icon={<DeleteOutlined />}
                    onClick={() => showDeleteDialog(record)}
                    style={{
                        borderColor: '#ff4d4f',
                    }}
                />
            </Space>
        ),
    },
];

const ListTag = memo(function ListTag(props) {
    const [showFilter, setShowFilter] = useState(false);
    const [trigerFilter, setTrigerFilter] = useState(false);
    const [tagsData, setTagsData] = useState(initialTagsData);

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

    const navigate = useNavigate();

    // Dummy data function to simulate API call - now uses state
    const getAllTag = async (params) => {
        // Simulate API delay
        await new Promise((resolve) => setTimeout(resolve, 300));

        // Extract URLSearchParams - TableList sends URLSearchParams object
        const searchParam = params.get('search') || '';
        const page = parseInt(params.get('page')) || 1;
        const limit = parseInt(params.get('limit')) || 10;

        console.log('getAllTag called with:', { searchParam, page, limit });

        // Filter by search
        let filteredTags = tagsData;
        if (searchParam) {
            const searchLower = searchParam.toLowerCase();
            filteredTags = tagsData.filter(
                (tag) =>
                    tag.tag_code.toLowerCase().includes(searchLower) ||
                    tag.tag_name.toLowerCase().includes(searchLower) ||
                    tag.tag_type.toLowerCase().includes(searchLower) ||
                    tag.tag_description.toLowerCase().includes(searchLower)
            );
        }

        // Pagination logic
        const totalData = filteredTags.length;
        const totalPages = Math.ceil(totalData / limit);
        const startIndex = (page - 1) * limit;
        const endIndex = startIndex + limit;
        const paginatedData = filteredTags.slice(startIndex, endIndex);

        // Return structure that matches TableList expectation
        // Based on TableList code:
        // - resData.data.data = array of items
        // - resData.data.total = total count
        // - resData.data.paging.page = current page
        // - resData.data.paging.limit = items per page
        // - resData.data.paging.total = total items
        // - resData.data.paging.page_total = total pages
        return {
            status: 200,
            statusCode: 200,
            data: {
                data: paginatedData,
                total: totalData,
                paging: {
                    page: page,
                    limit: limit,
                    total: totalData,
                    page_total: totalPages,
                },
            },
        };
    };

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

    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.tag_name + '" ?',
            onConfirm: () => handleDelete(param.tag_id),
            onCancel: () => props.setSelectedData(null),
        });
    };

    const handleDelete = async (tag_id) => {
        // Find tag name before deleting
        const tagToDelete = tagsData.find((tag) => tag.tag_id === tag_id);

        // Simulate delete API call
        await new Promise((resolve) => setTimeout(resolve, 300));

        // Remove from state
        const updatedTags = tagsData.filter((tag) => tag.tag_id !== tag_id);
        setTagsData(updatedTags);

        NotifAlert({
            icon: 'success',
            title: 'Berhasil',
            message: `Data Tag "${tagToDelete?.tag_name || ''}" berhasil dihapus.`,
        });
    };

    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 tag by code, name, or type..."
                                    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={getAllTag}
                            queryParams={formDataFilter}
                            columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
                            triger={trigerFilter}
                        />
                    </Col>
                </Row>
            </Card>
        </React.Fragment>
    );
});

export default ListTag;