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 DetailBrandDevice = (props) => {
    const [confirmLoading, setConfirmLoading] = useState(false);

    const defaultData = {
        brand_id: '',
        brandName: '',
        brandType: '',
        manufacturer: '',
        model: '',
        status: 'Active',
    };

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

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

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

        // Validasi required fields
        if (!FormData.brandName) {
            NotifOk({
                icon: 'warning',
                title: 'Peringatan',
                message: 'Kolom Brand Name Tidak Boleh Kosong',
            });
            setConfirmLoading(false);
            return;
        }

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

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

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

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

        const payload = {
            brandName: FormData.brandName,
            brandType: FormData.brandType,
            manufacturer: FormData.manufacturer,
            model: FormData.model,
            status: FormData.status,
        };

        try {
            // Simulate API call
            await new Promise((resolve) => setTimeout(resolve, 500));

            const response = {
                statusCode: FormData.brand_id ? 200 : 201,
                data: {
                    brandName: FormData.brandName,
                },
            };

            console.log('Save Brand Device Response:', response);

            // Check if response is successful
            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `Data Brand Device "${
                        response.data?.brandName || FormData.brandName
                    }" berhasil ${FormData.brand_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 Brand Device 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 handleSelectChange = (name, value) => {
        setFormData({
            ...FormData,
            [name]: value,
        });
    };

    const handleStatusToggle = (event) => {
        const isChecked = event;
        setFormData({
            ...FormData,
            status: isChecked ? true : false,
        });
    };

    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'
            } Brand Device`}
            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}>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>
                        <div>
                            <Text strong>Status</Text>
                        </div>
                        <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={handleStatusToggle}
                                />
                            </div>
                            <div>
                                <Text>{FormData.status === true ? 'Active' : 'Inactive'}</Text>
                            </div>
                        </div>
                    </div>
                    <Divider style={{ margin: '12px 0' }} />
                    <div hidden>
                        <Text strong>Brand ID</Text>
                        <Input
                            name="brand_id"
                            value={FormData.brand_id}
                            onChange={handleInputChange}
                            disabled
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Brand Name</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="brandName"
                            value={FormData.brandName}
                            onChange={handleInputChange}
                            placeholder="Enter Brand Name"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Type</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="brandType"
                            value={FormData.brandType}
                            onChange={handleInputChange}
                            placeholder="Enter Type (e.g., PLC)"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Manufacturer</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="manufacturer"
                            value={FormData.manufacturer}
                            onChange={handleInputChange}
                            placeholder="Enter Manufacturer"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Model</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="model"
                            value={FormData.model}
                            onChange={handleInputChange}
                            placeholder="Enter Model"
                            readOnly={props.readOnly}
                        />
                    </div>
                </div>
            )}
        </Modal>
    );
};

export default DetailBrandDevice;
