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

const { Text } = Typography;

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

    const defaultData = {
        id_apd: '',
        nama_apd: '',
        type_input: 1,
        is_active: true,
        jenis_permit_default: [],
    };

    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 handleSave = async () => {
        setConfirmLoading(true);

        if (!FormData.nama_apd) {
            NotifOk({
                icon: 'warning',
                title: 'Peringatan',
                message: 'Kolom Nama APD Tidak Boleh Kosong',
            });

            setConfirmLoading(false);
            return;
        }

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

            setConfirmLoading(false);
            return;
        }

        const payload = {
            nama_apd: FormData.nama_apd,
            is_active: FormData.is_active,
            type_input: FormData.type_input,
            jenis_permit_default: checkedList,
        };

        if (props.permitDefault) {
            try {
                let response;
                if (!FormData.id_apd) {
                    response = await createApd(payload);
                } else {
                    response = await updateApd(FormData.id_apd, payload);
                }

                if (response.statusCode === 200) {
                    NotifOk({
                        icon: 'success',
                        title: 'Berhasil',
                        message: `Data "${response.data.nama_apd}" berhasil ${
                            FormData.id_apd ? 'diubah' : 'ditambahkan'
                        }.`,
                    });

                    props.setActionMode('list');
                } else {
                    NotifAlert({
                        icon: 'error',
                        title: 'Gagal',
                        message: response.message || 'Terjadi kesalahan saat menyimpan data.',
                    });
                }
            } catch (error) {
                NotifAlert({
                    icon: 'error',
                    title: 'Error',
                    message: 'Terjadi kesalahan pada server. Coba lagi nanti.',
                });
            }
        } else {
            props.setData((prevData) => [
                ...prevData,
                { nama_apd: payload.nama_apd, type_input: payload.type_input },
            ]);

            props.setActionMode('list');
        }

        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) {
            getDataJenisPermit();
            if (props.selectedData != null) {
                setFormData(props.selectedData);
                setCheckedList(props.selectedData.jenis_permit_default_arr);
            } else {
                setFormData(defaultData);
            }
        } else {
            navigate('/signin');
        }
    }, [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>
                    {props.permitDefault && (
                        <>
                            <div>
                                <div>
                                    <Text strong>Aktif</Text>
                                </div>
                                <div
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        marginTop: '8px',
                                    }}
                                >
                                    <div style={{ marginRight: '8px' }}>
                                        <Switch
                                            disabled={props.readOnly}
                                            style={{
                                                backgroundColor:
                                                    FormData.is_active == 1 ? '#23A55A' : '#bfbfbf',
                                            }}
                                            checked={FormData.is_active == 1 ? true : false}
                                            onChange={handleStatusToggle}
                                        />
                                    </div>
                                    <div>
                                        <Text>
                                            {FormData.is_active == 1 ? 'Aktif' : 'Non Aktif'}
                                        </Text>
                                    </div>
                                </div>
                            </div>
                            <Divider style={{ margin: '5px 0' }} />
                        </>
                    )}
                    <div hidden>
                        <Text strong>Device ID</Text>
                        <Input
                            name="id_apd"
                            value={FormData.id_apd}
                            onChange={handleInputChange}
                            disabled
                        />
                    </div>
                    <div>
                        <Text strong>Device Name</Text>
                        <Text style={{ color: 'red' }}> *</Text>
                        <Input
                            name="nama_apd"
                            value={FormData.nama_apd}
                            onChange={handleInputChange}
                            readOnly={props.readOnly}
                        />
                    </div>
                    <div style={{ marginTop: 4, marginBottom: 4 }}>
                        <Text strong>Tipe Input</Text>
                        <Text style={{ color: 'red', marginLeft: 4 }}>*</Text>
                        <div>
                            <Radio.Group
                                value={FormData.type_input}
                                options={[
                                    { value: 1, label: 'Check' },
                                    { value: 2, label: 'Text' },
                                    { value: 3, label: 'Number' },
                                ]}
                                onChange={onChangeRadio}
                                disabled={props.readOnly}
                            />
                        </div>
                    </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;