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';
import { getAllJadwalShift, deleteJadwalShift } from '../../../api/jadwal-shift';

const columns = (showPreviewModal, showEditModal, showDeleteDialog) => [
    {
        title: 'Tanggal Jadwal',
        dataIndex: 'schedule_date',
        key: 'schedule_date',
        render: (date) => date ? new Date(date).toLocaleDateString('id-ID') : '-',
    },
    {
        title: 'Nama Shift',
        dataIndex: 'shift_name',
        key: 'shift_name',
        render: (text) => text || '-',
    },
    {
        title: 'Jam Masuk',
        dataIndex: 'start_time',
        key: 'start_time',
        render: (time) => time || '-',
    },
    {
        title: 'Jam Pulang',
        dataIndex: 'end_time',
        key: 'end_time',
        render: (time) => time || '-',
    },
    {
        title: 'Status',
        dataIndex: 'is_active',
        key: 'is_active',
        render: (isActive) => (
            <Tag color={isActive ? 'green' : 'red'}>
                {isActive ? 'Aktif' : 'Tidak Aktif'}
            </Tag>
        ),
    },
    {
        title: 'Aksi',
        key: 'aksi',
        align: 'center',
        render: (_, record) => (
            <Space>
                <Button
                    type="text"
                    icon={<EyeOutlined style={{ color: '#1890ff' }} />}
                    onClick={() => showPreviewModal(record)}
                />
                <Button
                    type="text"
                    icon={<EditOutlined style={{ color: '#faad14' }} />}
                    onClick={() => showEditModal(record)}
                />
                <Button
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    onClick={() => showDeleteDialog(record)}
                />
            </Space>
        ),
    },
];

const ListJadwalShift = memo(function ListJadwalShift(props) {
    const [trigerFilter, setTrigerFilter] = useState(false);
    const defaultFilter = { criteria: '' };
    const [formDataFilter, setFormDataFilter] = useState(defaultFilter);
    const [searchValue, setSearchValue] = useState('');
    const navigate = useNavigate();

    const getData = async (queryParams) => {
        try {
            const params = new URLSearchParams({
                page: queryParams.page || 1,
                limit: queryParams.limit || 10,
                criteria: queryParams.criteria || ''
            });

            const response = await getAllJadwalShift(params);
            return response;
        } catch (error) {
            console.error('Error fetching jadwal shift:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: 'Gagal mengambil data jadwal shift.',
            });
            return {
                status: 500,
                data: {
                    data: [],
                    paging: {
                        page: 1,
                        limit: 10,
                        total: 0,
                        page_total: 0
                    }
                }
            };
        }
    };

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

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

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

    const handleSearchClear = () => {
        setSearchValue('');
        setFormDataFilter({ criteria: '' });
        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) => {
        const dateStr = param.schedule_date ? new Date(param.schedule_date).toLocaleDateString('id-ID') : 'tanggal tidak diketahui';
        NotifConfirmDialog({
            icon: 'question',
            title: 'Konfirmasi Hapus',
            message: `Jadwal shift tanggal ${dateStr} akan dihapus?`,
            onConfirm: () => handleDelete(param.schedule_id),
            onCancel: () => props.setSelectedData(null),
        });
    };

    const handleDelete = async (id) => {
        try {
            const response = await deleteJadwalShift(id);
            if (response.statusCode === 200) {
                NotifAlert({
                    icon: 'success',
                    title: 'Berhasil',
                    message: 'Data Jadwal Shift berhasil dihapus.',
                });
                doFilter();
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Error',
                    message: response.message || 'Gagal menghapus data jadwal shift.',
                });
            }
        } catch (error) {
            console.error('Error deleting jadwal shift:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: 'Terjadi kesalahan saat menghapus data.',
            });
        }
    };

    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="Cari jadwal shift..."
                                    value={searchValue}
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setSearchValue(value);
                                        if (value === '') {
                                            handleSearchClear();
                                        }
                                    }}
                                    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={{
                                            components: {
                                                Button: {
                                                    defaultBg: 'white',
                                                    defaultColor: '#23A55A',
                                                    defaultBorderColor: '#23A55A',
                                                },
                                            },
                                        }}
                                    >
                                        <Button
                                            icon={<PlusOutlined />}
                                            onClick={() => showAddModal()}
                                            size="large"
                                        >
                                            Tambah Data
                                        </Button>
                                    </ConfigProvider>
                                </Space>
                            </Col>
                        </Row>
                    </Col>
                    <Col xs={24} style={{ marginTop: '16px' }}>
                        <TableList
                            mobile
                            cardColor={'#42AAFF'}
                            header={'schedule_date'}
                            showPreviewModal={showPreviewModal}
                            showEditModal={showEditModal}
                            showDeleteDialog={showDeleteDialog}
                            getData={getData}
                            queryParams={formDataFilter}
                            columns={columns(showPreviewModal, showEditModal, showDeleteDialog)}
                            triger={trigerFilter}
                        />
                    </Col>
                </Row>
            </Card>
        </React.Fragment>
    );
});

export default ListJadwalShift;