import { useEffect, useState } from 'react';
import { Modal, Select, Divider, Typography, Button, ConfigProvider } from 'antd';
import { NotifAlert, NotifOk } from '../../../components/Global/ToastNotif';
import { createJadwalShift, updateJadwalShift } from '../../../api/jadwal-shift';
import { getAllShift } from '../../../api/master-shift';
import { getAllUser } from '../../../api/user';

const { Text } = Typography;
const { Option } = Select;

const DetailJadwalShift = (props) => {
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [shifts, setShifts] = useState([]);
    const [users, setUsers] = useState([]);

    const defaultData = {
        id: '',
        id_shift: null,
        id_user: null,
    };

    const [FormData, setFormData] = useState(defaultData);

    const fetchShifts = async () => {
        const response = await getAllShift(new URLSearchParams());
        setShifts(response.data.data);
    };

    const fetchUsers = async () => {
        const response = await getAllUser(new URLSearchParams("limit=1000")); // Fetch all users
        setUsers(response.data.data);
    };

    useEffect(() => {
        fetchShifts();
        fetchUsers();
    }, []);

    const handleCancel = () => {
        props.setSelectedData(null);
        props.setActionMode('list');
    };

    const handleSave = async () => {
        setConfirmLoading(true);

        if (!FormData.id_shift) {
            NotifOk({
                icon: 'warning',
                title: 'Peringatan',
                message: 'Kolom Shift Tidak Boleh Kosong',
            });
            setConfirmLoading(false);
            return;
        }

        if (!FormData.id_user) {
            NotifOk({
                icon: 'warning',
                title: 'Peringatan',
                message: 'Kolom User Tidak Boleh Kosong',
            });
            setConfirmLoading(false);
            return;
        }

        const payload = {
            id_shift: FormData.id_shift,
            id_user: FormData.id_user,
        };

        try {
            const response = FormData.id
                ? await updateJadwalShift(FormData.id, payload)
                : await createJadwalShift(payload);

            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `Data Jadwal Shift berhasil ${FormData.id ? 'diubah' : 'ditambahkan'}.`,
                });

                props.setActionMode('list');
            } else {
                NotifAlert({
                    icon: 'error',
                    title: 'Gagal',
                    message: response?.message || 'Terjadi kesalahan saat menyimpan data.',
                });
            }
        } catch (error) {
            console.error('Save Jadwal Shift Error:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: error.message || 'Terjadi kesalahan pada server. Coba lagi nanti.',
            });
        }

        setConfirmLoading(false);
    };

    const handleSelectChange = (name, value) => {
        setFormData({
            ...FormData,
            [name]: value,
        });
    };

    useEffect(() => {
        if (props.selectedData) {
            setFormData(props.selectedData);
        } else {
            setFormData(defaultData);
        }
    }, [props.actionMode, props.selectedData]);

    return (
        <Modal
            title={`${
                props.actionMode === 'add'
                    ? 'Tambah'
                    : 'Edit'
            } Jadwal Shift`}
            open={props.actionMode !== 'list'}
            onCancel={handleCancel}
            footer={[
                <>
                    <ConfigProvider
                        theme={{
                            token: { colorBgContainer: '#E9F6EF' },
                            components: {
                                Button: {
                                    defaultBg: 'white',
                                    defaultColor: '#23A55A',
                                    defaultBorderColor: '#23A55A',
                                    defaultHoverColor: '#23A55A',
                                    defaultHoverBorderColor: '#23A55A',
                                },
                            },
                        }}
                    >
                        <Button onClick={handleCancel}>Batal</Button>
                    </ConfigProvider>
                    <ConfigProvider
                        theme={{
                            token: {
                                colorBgContainer: '#209652',
                            },
                            components: {
                                Button: {
                                    defaultBg: '#23a55a',
                                    defaultColor: '#FFFFFF',
                                    defaultBorderColor: '#23a55a',
                                    defaultHoverColor: '#FFFFFF',
                                    defaultHoverBorderColor: '#23a55a',
                                },
                            },
                        }}
                    >
                        <Button loading={confirmLoading} onClick={handleSave}>
                            Simpan
                        </Button>
                    </ConfigProvider>
                </>,
            ]}
        >
            {FormData && (
                <div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Shift</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Select
                            style={{ width: '100%' }}
                            placeholder="Pilih Shift"
                            onChange={(value) => handleSelectChange('id_shift', value)}
                            value={FormData.id_shift}
                        >
                            {shifts.map(shift => (
                                <Option key={shift.id} value={shift.id}>{shift.nama_shift} ({shift.jam_shift})</Option>
                            ))}
                        </Select>
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>User</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Select
                            style={{ width: '100%' }}
                            placeholder="Pilih User"
                            onChange={(value) => handleSelectChange('id_user', value)}
                            value={FormData.id_user}
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {users.map(user => (
                                <Option key={user.id} value={user.id}>{user.username} ({user.nama_employee})</Option>
                            ))}
                        </Select>
                    </div>
                </div>
            )}
        </Modal>
    );
};

export default DetailJadwalShift;
