import { useEffect, useState } from 'react';
import { Modal, Input, Typography, Switch, Button, ConfigProvider, Divider } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createShift, updateShift } from '../../../../api/master-shift';

const { Text } = Typography;

const DetailShift = (props) => {
    const [confirmLoading, setConfirmLoading] = useState(false);
    const readOnly = props.actionMode === 'preview';

    const defaultData = {
        id: '',
        nama_shift: '',
        jam_shift: '',
        status: true, // default to active
    };

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

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

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

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

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

        const payload = {
            nama_shift: FormData.nama_shift,
            jam_shift: FormData.jam_shift,
            status: FormData.status,
        };

        try {
            if (FormData.id) {
                props.onUpdate(payload);
            } else {
                props.onAdd(payload);
            }
            NotifOk({
                icon: 'success',
                title: 'Berhasil',
                message: `Data Shift "${payload.nama_shift}" berhasil ${FormData.id ? 'diubah' : 'ditambahkan'}.`,
            });
        } catch (error) {
            console.error('Save Shift Error:', error);
            NotifAlert({
                icon: 'error',
                title: 'Error',
                message: error.message || 'Terjadi kesalahan pada server. Coba lagi nanti.',
            });
        }

        setConfirmLoading(false);
    };

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

    const handleStatusToggle = (checked) => {
        setFormData({ ...FormData, status: checked });
    };

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

    return (
        <Modal
            title={`${props.actionMode === 'add' ? 'Tambah' : props.actionMode === 'preview' ? 'Preview' : 'Edit'} 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',
                                },
                            },
                        }}
                    >
                        {!readOnly && (
                            <Button loading={confirmLoading} onClick={handleSave}>
                                Simpan
                            </Button>
                        )}
                    </ConfigProvider>
                </>,
            ]}
        >
            {FormData && (
                <div>
                    <div>
                        <div>
                            <Text strong>Status</Text>
                        </div>
                        <div
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                marginTop: '8px',
                            }}
                        >
                            <div style={{ marginRight: '8px' }}>
                                <Switch
                                    disabled={readOnly}
                                    style={{
                                        backgroundColor:
                                            FormData.status === true ? '#23A55A' : '#bfbfbf',
                                    }}
                                    checked={FormData.status === true}
                                    onChange={handleStatusToggle}
                                />
                            </div>
                            <div>
                                <Text>{FormData.status === true ? 'Active' : 'Inactive'}</Text>
                            </div>
                        </div>
                    </div>
                    <Divider style={{ margin: '12px 0' }} />
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Nama Shift</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="nama_shift"
                            value={FormData.nama_shift}
                            onChange={handleInputChange}
                            placeholder="Masukkan Nama Shift"
                            readOnly={readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Jam Shift</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="jam_shift"
                            value={FormData.jam_shift}
                            onChange={handleInputChange}
                            placeholder="Contoh: 08:00 - 17:00"
                            readOnly={readOnly}
                        />
                    </div>
                </div>
            )}
        </Modal>
    );
};

export default DetailShift;