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 { createRole, updateRole } from '../../api/role';
import { NotifAlert, NotifOk } 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(async (values) => {
                try {
                    let response;
                    if (actionMode === 'edit') {
                        response = await updateRole(selectedData.role_id, values);
                        console.log('Update Response:', response);

                        const isSuccess = response.statusCode === 200 || response.statusCode === 201;
                        if (isSuccess) {
                            NotifAlert({
                                icon: 'success',
                                title: 'Berhasil',
                                message: `Data Role "${values.role_name}" berhasil diubah.`,
                            });
                            handleCancel();
                        } else {
                            NotifOk({
                                icon: 'error',
                                title: 'Gagal',
                                message: response.message || 'Gagal mengubah data Role',
                            });
                        }
                    } else if (actionMode === 'add') {
                        response = await createRole(values);
                        console.log('Create Response:', response);

                        const isSuccess = response.statusCode === 200 || response.statusCode === 201;
                        if (isSuccess) {
                            NotifAlert({
                                icon: 'success',
                                title: 'Berhasil',
                                message: `Data Role "${values.role_name}" berhasil ditambahkan.`,
                            });
                            handleCancel();
                        } else {
                            NotifOk({
                                icon: 'error',
                                title: 'Gagal',
                                message: response.message || 'Gagal menambahkan data Role',
                            });
                        }
                    }
                } catch (error) {
                    console.error('Error:', error);
                    NotifOk({
                        icon: 'error',
                        title: 'Error',
                        message: 'Terjadi kesalahan saat menyimpan data',
                    });
                }
            })
            .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;
