import { useEffect, useState } from 'react';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider, Select } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';

const { Text } = Typography;

const DetailPlantSection = (props) => {
    const [confirmLoading, setConfirmLoading] = useState(false);

    const defaultData = {
        plant_section_id: '',
        plantName: '',
        sectionName: '',
        status: true,
    };

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

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

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

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

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

        const payload = {
            plantName: FormData.plantName,
            sectionName: FormData.sectionName,
            status: FormData.status,
        };

        try {
            await new Promise((resolve) => setTimeout(resolve, 500));

            const response = {
                statusCode: FormData.plant_section_id ? 200 : 201,
                data: {
                    plantName: FormData.plantName,
                    sectionName: FormData.sectionName,
                },
            };

            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `Data Plant Section "${
                        response.data?.plantName || FormData.plantName
                    } - ${response.data?.sectionName || FormData.sectionName}" berhasil ${FormData.plant_section_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 Plant Section 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 handleStatusChange = (value) => {
        setFormData({
            ...FormData,
            status: value,
        });
    };

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            if (props.selectedData != null) {
                setFormData(props.selectedData);
            } else {
                setFormData(defaultData);
            }
        } else {
            // navigate('/signin'); // Uncomment if useNavigate is imported
        }
    }, [props.showModal]);

    return (
        <Modal
            title={`${
                props.actionMode === 'add'
                    ? 'Tambah'
                    : props.actionMode === 'preview'
                    ? 'Preview'
                    : 'Edit'
            } Plant Section`}
            open={props.showModal}
            onCancel={handleCancel}
            footer={[
                <>
                    <ConfigProvider
                        theme={{
                            token: { colorBgContainer: '#E9F6EF' },
                            components: {
                                Button: {
                                    defaultBg: 'white',
                                    defaultColor: '#23A55A',
                                    defaultBorderColor: '#23A55A',
                                    defaultHoverColor: '#23A55A',
                                    defaultHoverBorderColor: '#23A55A',
                                },
                            },
                        }}
                    >
                        <Button onClick={handleCancel}>
                            {props.actionMode === 'preview' ? 'Tutup' : 'Batal'}
                        </Button>
                    </ConfigProvider>
                    <ConfigProvider
                        theme={{
                            token: {
                                colorBgContainer: '#209652',
                            },
                            components: {
                                Button: {
                                    defaultBg: '#23a55a',
                                    defaultColor: '#FFFFFF',
                                    defaultBorderColor: '#23a55a',
                                    defaultHoverColor: '#FFFFFF',
                                    defaultHoverBorderColor: '#23a55a',
                                },
                            },
                        }}
                    >
                        {!props.readOnly && (
                            <Button loading={confirmLoading} onClick={handleSave}>
                                Simpan
                            </Button>
                        )}
                    </ConfigProvider>
                </>,
            ]}
        >
            {FormData && (
                <div>
                    <div hidden>
                        <Text strong>Plant Section ID</Text>
                        <Input
                            name="plant_section_id"
                            value={FormData.plant_section_id}
                            onChange={handleInputChange}
                            disabled
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Status</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <div
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                marginTop: '8px',
                            }}
                        >
                            <div style={{ marginRight: '8px' }}>
                                <Switch
                                    disabled={props.readOnly}
                                    style={{
                                        backgroundColor:
                                            FormData.status === true ? '#23A55A' : '#bfbfbf',
                                    }}
                                    checked={FormData.status === true}
                                    onChange={handleStatusChange}
                                />
                            </div>
                            <div>
                                <Text>{FormData.status === true ? 'Active' : 'Inactive'}</Text>
                            </div>
                        </div>
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Plant Name</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="plantName"
                            value={FormData.plantName}
                            onChange={handleInputChange}
                            placeholder="Enter Plant Name"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Section Name</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="sectionName"
                            value={FormData.sectionName}
                            onChange={handleInputChange}
                            placeholder="Enter Section Name"
                            readOnly={props.readOnly}
                        />
                    </div>
                </div>
            )}
        </Modal>
    );
};

export default DetailPlantSection;
