import React, { useEffect, useState } from 'react';
import {
    Modal,
    Input,
    Divider,
    Typography,
    Switch,
    Button,
    ConfigProvider,
    Radio,
    Select,
} from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createApd, getJenisPermit, updateApd } from '../../../../api/master-apd';
import { createDevice, updateDevice } from '../../../../api/master-device';
import { Checkbox } from 'antd';
const CheckboxGroup = Checkbox.Group;

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

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

    const defaultData = {
        device_id: '',
        device_code: '',
        device_name: '',
        is_active: true,
        device_location: 'Building A',
        device_description: '',
        ip_address: '',
    };

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

    const [jenisPermit, setJenisPermit] = useState([]);
    const [checkedList, setCheckedList] = useState([]);

    const onChange = (list) => {
        setCheckedList(list);
    };

    const onChangeRadio = (e) => {
        setFormData({
            ...FormData,
            type_input: e.target.value,
        });
    };

    const getDataJenisPermit = async () => {
        setCheckedList([]);
        const result = await getJenisPermit();
        const data = result.data ?? [];
        const names = data.map((item) => ({
            value: item.id_jenis_permit,
            label: item.nama_jenis_permit,
        }));
        setJenisPermit(names);
    };

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

    const validateIPAddress = (ip) => {
        const ipRegex =
            /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
        return ipRegex.test(ip);
    };

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

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

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

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

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

        // Validasi format IP
        if (!validateIPAddress(FormData.ip_address)) {
            NotifOk({
                icon: 'warning',
                title: 'Peringatan',
                message: 'Format IP Address Tidak Valid',
            });
            setConfirmLoading(false);
            return;
        }

        if (props.permitDefault && checkedList.length === 0) {
            NotifOk({
                icon: 'warning',
                title: 'Peringatan',
                message: 'Kolom Jenis Permit Tidak Boleh Kosong',
            });

            setConfirmLoading(false);
            return;
        }

        // Backend validation schema doesn't include device_code
        const payload = {
            device_name: FormData.device_name,
            is_active: FormData.is_active,
            device_location: FormData.device_location,
            ip_address: FormData.ip_address,
        };

        // For CREATE: device_description is required (cannot be empty)
        // For UPDATE: device_description is optional
        if (!FormData.device_id) {
            // Creating - ensure description is not empty
            payload.device_description = FormData.device_description || '-';
        } else {
            // Updating - include description as-is
            payload.device_description = FormData.device_description;
        }

        console.log('Payload to send:', payload);

        try {
            let response;
            if (!FormData.device_id) {
                response = await createDevice(payload);
            } else {
                response = await updateDevice(FormData.device_id, payload);
            }

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

            // Check if response is successful
            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                // Response.data is now a single object (already extracted from array)
                const deviceName = response.data?.device_name || FormData.device_name;

                NotifOk({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `Data Device "${deviceName}" berhasil ${
                        FormData.device_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 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 handleStatusToggle = (event) => {
        const isChecked = event;
        setFormData({
            ...FormData,
            is_active: isChecked ? true : false,
        });
    };

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            // Only call getDataJenisPermit if permitDefault is enabled
            if (props.permitDefault) {
                getDataJenisPermit();
            }

            if (props.selectedData != null) {
                setFormData(props.selectedData);
                if (props.permitDefault && props.selectedData.jenis_permit_default_arr) {
                    setCheckedList(props.selectedData.jenis_permit_default_arr);
                }
            } else {
                setFormData(defaultData);
            }
        } else {
            // navigate('/signin'); // Uncomment if useNavigate is imported
        }
    }, [props.showModal]);

    return (
        <Modal
            // title={`${FormData.id_apd === '' ? 'Tambah' : 'Edit'} APD`}
            title={`${
                props.actionMode === 'add'
                    ? 'Tambah'
                    : props.actionMode === 'preview'
                    ? 'Preview'
                    : 'Edit'
            } Device`}
            open={props.showModal}
            // open={true}
            onCancel={handleCancel}
            footer={[
                <React.Fragment key="modal-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>
                </React.Fragment>,
            ]}
        >
            {FormData && (
                <div>
                    <div>
                        <div>
                            <Text strong>Device Status</Text>
                        </div>
                        <div
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                marginTop: '8px',
                            }}
                        >
                            <div style={{ marginRight: '8px' }}>
                                <Switch
                                    disabled={props.readOnly}
                                    style={{
                                        backgroundColor:
                                            FormData.is_active === true ? '#23A55A' : '#bfbfbf',
                                    }}
                                    checked={FormData.is_active === true}
                                    onChange={handleStatusToggle}
                                />
                            </div>
                            <div>
                                <Text>{FormData.is_active === true ? 'Running' : 'Offline'}</Text>
                            </div>
                        </div>
                    </div>
                    <Divider style={{ margin: '12px 0' }} />
                    <div hidden>
                        <Text strong>Device ID</Text>
                        <Input
                            name="device_id"
                            value={FormData.device_id}
                            onChange={handleInputChange}
                            disabled
                        />
                    </div>
                    {/* <div style={{ marginBottom: 12 }}>
                        <Text strong>Device Code</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="device_code"
                            value={FormData.device_code}
                            onChange={handleInputChange}
                            placeholder="Enter Device Code"
                            readOnly={props.readOnly}
                        />
                    </div> */}
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Device Name</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="device_name"
                            value={FormData.device_name}
                            onChange={handleInputChange}
                            placeholder="Enter Device Name"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Device Location</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            type="text"
                            name="device_location"
                            value={FormData.device_location}
                            onChange={handleInputChange}
                            placeholder="Enter Device Location"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>IP Address</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="ip_address"
                            value={FormData.ip_address}
                            onChange={handleInputChange}
                            placeholder="e.g. 192.168.1.1"
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Device Description</Text>
                        <TextArea
                            name="device_description"
                            value={FormData.device_description}
                            onChange={handleInputChange}
                            placeholder="Enter Device Description (Optional)"
                            readOnly={props.readOnly}
                            rows={4}
                        />
                    </div>
                    {props.permitDefault && (
                        <div>
                            <Text strong>Jenis Permit</Text>
                            <Text style={{ color: 'red' }}> *</Text>

                            <CheckboxGroup
                                options={jenisPermit}
                                value={checkedList}
                                onChange={onChange}
                                disabled={props.readOnly}
                            />
                        </div>
                    )}
                </div>
            )}
        </Modal>
    );
};

export default DetailDevice;
