import React, { useEffect, useState } from 'react';
import { Modal, Input, Divider, Typography, Switch, Button, ConfigProvider } from 'antd';
import { NotifAlert, NotifOk } from '../../../../components/Global/ToastNotif';
import { createDevice, updateDevice } from '../../../../api/master-device';
import { validateRun } from '../../../../Utils/validate';

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

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

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

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

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

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

        // Daftar aturan validasi
        const validationRules = [
            { field: 'device_name', label: 'Device Name', required: true },
            { field: 'ip_address', label: 'Ip Address', required: true, ip: true },
        ];

        if (
            validateRun(formData, validationRules, (errorMessages) => {
                NotifOk({
                    icon: 'warning',
                    title: 'Peringatan',
                    message: errorMessages,
                });
                setConfirmLoading(false);
            })
        )
            return;

        try {
            const payload = {
                device_name: formData.device_name,
                is_active: formData.is_active,
                device_location: formData.device_location,
                device_description: formData.device_description,
                ip_address: formData.ip_address,
            };

            const response = formData.device_id
                ? await updateDevice(formData.device_id, payload)
                : await createDevice(payload);

            // Check if response is successful
            if (response && (response.statusCode === 200 || response.statusCode === 201)) {
                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(() => {
        if (props.selectedData) {
            setFormData(props.selectedData);
        } else {
            setFormData(defaultData);
        }
    }, [props.showModal, props.selectedData, props.actionMode]);

    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>
                    {/* Device Code - Auto Increment & Read Only */}
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Device Code</Text>
                        <Input
                            name="device_code"
                            value={formData.device_code}
                            placeholder={'Device Code Auto Fill'}
                            disabled
                            style={{
                                backgroundColor: '#f5f5f5',
                                cursor: 'not-allowed',
                                color: formData.device_code ? '#000000' : '#bfbfbf',
                            }}
                        />
                    </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>Brand Device</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="brand_device"
                            value={formData.brand_device}
                            onChange={handleInputChange}
                            placeholder="Enter Brand Device"
                            readOnly={props.readOnly}
                            disabled
                            style={{
                                backgroundColor: '#f5f5f5',
                                cursor: 'not-allowed',
                                color: formData.brand_device ? '#000000' : '#bfbfbf',
                            }}
                        />
                    </div>
                    <div style={{ marginBottom: 12 }}>
                        <Text strong>Device Location</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>
                </div>
            )}
        </Modal>
    );
};

export default DetailDevice;
