import React, { memo, useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useBreadcrumb } from '../../layout/LayoutBreadcrumb';
import { Form, Typography } from 'antd';
import ListRole from './component/ListRole';
import DetailRole from './component/DetailRole';

import { NotifAlert } from '../../components/Global/ToastNotif';

const { Text } = Typography;

const IndexRole = memo(function IndexRole() {
    const navigate = useNavigate();
    const { setBreadcrumbItems } = useBreadcrumb();
    const [form] = Form.useForm();

    const [actionMode, setActionMode] = useState('list');
    const [selectedData, setSelectedData] = useState(null);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [readOnly, setReadOnly] = useState(false);

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            setBreadcrumbItems([
                {
                    title: (
                        <Text strong style={{ fontSize: '14px' }}>
                            • Role
                        </Text>
                    ),
                },
            ]);
        } else {
            navigate('/signin');
        }
    }, [navigate, setBreadcrumbItems]);

    useEffect(() => {
        if (actionMode === 'add' || actionMode === 'edit' || actionMode === 'preview') {
            setIsModalVisible(true);
            setReadOnly(actionMode === 'preview');

            if (actionMode === 'add') {
                form.resetFields();
            } else if (selectedData) {
                form.setFieldsValue(selectedData);
            }
        } else {
            setIsModalVisible(false);
            form.resetFields();
        }
    }, [actionMode, selectedData, form]);

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

    const handleOk = () => {
        if (readOnly) {
            handleCancel();
            return;
        }

        form.validateFields()
            .then((values) => {
                if (actionMode === 'edit') {
                    NotifAlert({
                        icon: 'success',
                        title: 'Berhasil',
                        message: `Data Role "${values.role_name}" berhasil diubah.`,
                    });
                } else if (actionMode === 'add') {
                    NotifAlert({
                        icon: 'success',
                        title: 'Berhasil',
                        message: `Data Role "${values.role_name}" berhasil ditambahkan.`,
                    });
                }
                handleCancel();
            })
            .catch((info) => {
                console.log('Validate Failed:', info);
            });
    };

    return (
        <React.Fragment>
            <ListRole
                actionMode={actionMode}
                setActionMode={setActionMode}
                selectedData={selectedData}
                setSelectedData={setSelectedData}
            />
            <DetailRole
                visible={isModalVisible}
                onCancel={handleCancel}
                onOk={handleOk}
                form={form}
                editingKey={selectedData?.role_id}
                readOnly={readOnly}
            />
        </React.Fragment>
    );
});

export default IndexRole;
