import React, { useEffect, useState } from 'react';
import {
    Modal,
    Typography,
    Button,
    ConfigProvider,
    Form,
    Select,
    Spin,
    Input
} from 'antd';
import { NotifOk, NotifAlert } from '../../../components/Global/ToastNotif';
import { updateJadwalShift, createJadwalShift } from '../../../api/jadwal-shift.jsx';

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

const DetailJadwalShift = (props) => {
    const [form] = Form.useForm();
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [employees, setEmployees] = useState([]);
    const [loadingEmployees, setLoadingEmployees] = useState(false);

    const isReadOnly = props.actionMode === 'preview';

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

    const fetchEmployees = async () => {
        setLoadingEmployees(true);
        try {
            // Data dummy untuk dropdown karyawan
            const dummyEmployees = [
                { employee_id: '101', nama_employee: 'Andi Pratama' },
                { employee_id: '102', nama_employee: 'Budi Santoso' },
                { employee_id: '103', nama_employee: 'Citra Lestari' },
                { employee_id: '104', nama_employee: 'Dewi Anggraini' },
                { employee_id: '105', nama_employee: 'Eko Wahyudi' },
                { employee_id: '106', nama_employee: 'Fitriani' },
            ];
            setEmployees(dummyEmployees);
        } catch (error) {
            NotifAlert({ icon: 'error', title: 'Gagal', message: 'Gagal memuat daftar karyawan.' });
        } finally {
            setLoadingEmployees(false);
        }
    };

    const handleSave = async () => {
        try {
            const values = await form.validateFields();
            let payload;
            let responseMessage;

            setConfirmLoading(true);
            if (props.actionMode === 'edit') {
                payload = { ...props.selectedData, ...values };
                // await updateJadwalShift(payload.schedule_id, payload);
                console.log("Updating schedule with payload:", payload);
                responseMessage = 'Jadwal berhasil diperbarui.';
            } else { // 'add' mode
                payload = {
                    employee_id: values.employee_id,
                    shift_name: props.selectedData.shift_name,
                    schedule_date: new Date().toISOString().split('T')[0], // Example date
                };
                // await createJadwalShift(payload);
                console.log("Creating schedule with payload:", payload);
                responseMessage = 'User berhasil ditambahkan ke jadwal.';
            }
            await new Promise(resolve => setTimeout(resolve, 500)); // Simulasi API call

            NotifOk({ icon: 'success', title: 'Berhasil', message: responseMessage });
            props.setActionMode('list'); // Menutup modal dan memicu refresh di parent
        } catch (error) {
            const message = error.response?.data?.message || 'Gagal memperbarui jadwal.';
            NotifAlert({ icon: 'error', title: 'Gagal', message });
        } finally {
            setConfirmLoading(false);
        }
    };

    useEffect(() => {
        // Hanya jalankan jika modal untuk 'edit' atau 'preview' terbuka
        if (props.showModal) {
            fetchEmployees();
            if (props.actionMode === 'edit' || props.actionMode === 'preview') {
                form.setFieldsValue({
                    employee_id: props.selectedData.employee_id,
                    shift_name: props.selectedData.shift_name,
                });
            } else if (props.actionMode === 'add') {
                form.setFieldsValue({
                    shift_name: props.selectedData.shift_name,
                    employee_id: null, // Reset employee selection
                });
            }
        }
    }, [props.actionMode, props.showModal, props.selectedData, form]);

    return (
        <Modal
            title={isReadOnly ? 'Preview Jadwal' : (props.actionMode === 'edit' ? 'Edit Jadwal' : 'Tambah User')}
            open={props.showModal}
            onCancel={handleCancel}
            width={600}
            footer={[
                <React.Fragment key="modal-footer">
                    <Button key="back" onClick={handleCancel}>
                        {isReadOnly ? 'Tutup' : 'Batal'}
                    </Button>
                    {!isReadOnly && (
                        <Button key="submit" type="primary" loading={confirmLoading} onClick={handleSave} style={{ backgroundColor: '#23A55A' }}>
                            Simpan
                        </Button>
                    )}
                </React.Fragment>,
            ]}
        >
            <Spin spinning={loadingEmployees} tip="Memuat data...">
                <Form form={form} layout="vertical" name="shift_form">
                    {props.actionMode === 'add' ? (
                        <>
                            <Form.Item
                                name="shift_name"
                                label="Shift"
                            >
                                <Input disabled />
                            </Form.Item>
                            <Form.Item
                                name="employee_id"
                                label="Nama Karyawan"
                                rules={[{ required: true, message: 'Nama karyawan wajib dipilih!' }]}
                            >
                                <Select
                                    placeholder="Pilih karyawan"
                                    showSearch
                                    optionFilterProp="children"
                                >
                                    {employees.map(emp => (
                                        <Option key={emp.employee_id} value={emp.employee_id}>{emp.nama_employee}</Option>
                                    ))}
                                </Select>
                            </Form.Item>
                        </>
                    ) : (
                        <>
                            <Form.Item
                                name="employee_id"
                                label="Nama Karyawan"
                                rules={[{ required: true, message: 'Nama karyawan wajib dipilih!' }]}
                            >
                                <Select placeholder="Pilih karyawan" disabled={isReadOnly} showSearch optionFilterProp="children">
                                    {employees.map(emp => (
                                        <Option key={emp.employee_id} value={emp.employee_id}>{emp.nama_employee}</Option>
                                    ))}
                                </Select>
                            </Form.Item>
                            <Form.Item name="shift_name" label="Shift" rules={[{ required: true, message: 'Shift wajib dipilih!' }]}>
                                <Select placeholder="Pilih shift" disabled={isReadOnly}>
                                    <Option value="PAGI">PAGI</Option>
                                    <Option value="SIANG">SIANG</Option>
                                    <Option value="MALAM">MALAM</Option>
                                </Select>
                            </Form.Item>
                        </>
                    )}
                </Form>
            </Spin>
        </Modal>
    );
};

export default DetailJadwalShift;
