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

const { Text } = Typography;
const { TextArea } = Input;

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

    const defaultData = {
        tag_id: '',
        tag_code: '',
        tag_name: '',
        tag_value: 'Off',
        tag_type: 'alarm',
        tag_description: '',
    };

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

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

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

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

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

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

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

        const payload = {
            tag_code: FormData.tag_code,
            tag_name: FormData.tag_name,
            tag_value: FormData.tag_value,
            tag_type: FormData.tag_type,
            tag_description: FormData.tag_description,
        };

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

            const response = {
                statusCode: FormData.tag_id ? 200 : 201,
                data: {
                    tag_name: FormData.tag_name,
                },
            };

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

            // Check if response is successful
            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `Data Tag "${response.data?.tag_name || FormData.tag_name}" berhasil ${
                        FormData.tag_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 Tag 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,
        });
    };

    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'
            } Tag`}
            open={props.showModal}
            onCancel={handleCancel}
            footer={[
                <>
                    <ConfigProvider
                        theme={{
                            token: { colorBgContainer: '#E9F6EF' },
                            components: {
                                Button: {
                                    defaultBg: 'white',
                                    defaultColor: '#23A55A',
                                    defaultBorderColor: '#23A55A',
                                    defaultHoverColor: '#23A55A',
                                    defaultHoverBorderColor: '#23A55A',
                                    defaultHoverColor: '#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 hidden>
                        <Text strong>Tag ID</Text>
                        <Input
                            name="tag_id"
                            value={FormData.tag_id}
                            onChange={handleInputChange}
                            disabled
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Tag Code</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="tag_code"
                            value={FormData.tag_code}
                            onChange={handleInputChange}
                            placeholder="Enter Tag Code"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Tag Name</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="tag_name"
                            value={FormData.tag_name}
                            onChange={handleInputChange}
                            placeholder="Enter Tag Name"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Tag Value</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Select
                            value={FormData.tag_value}
                            onChange={(value) => handleSelectChange('tag_value', value)}
                            disabled={props.readOnly}
                            style={{ width: '100%' }}
                            placeholder="Select Value"
                            options={[
                                { value: 'On', label: 'On' },
                                { value: 'Off', label: 'Off' },
                                { value: 'Critical', label: 'Critical' },
                            ]}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Tag Type</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Select
                            value={FormData.tag_type}
                            onChange={(value) => handleSelectChange('tag_type', value)}
                            disabled={props.readOnly}
                            style={{ width: '100%' }}
                            placeholder="Select Type"
                            options={[
                                { value: 'alarm', label: 'Alarm' },
                                { value: 'measurement', label: 'Measurement' },
                            ]}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Tag Description</Text>
                        <TextArea
                            name="tag_description"
                            value={FormData.tag_description}
                            onChange={handleInputChange}
                            placeholder="Enter Tag Description (Optional)"
                            readOnly={props.readOnly}
                            rows={4}
                        />
                    </div>
                </div>
            )}
        </Modal>
    );
};

export default DetailTag;
