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

const { Text } = Typography;

const IndexNotification = memo(function IndexNotification() {
    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);

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

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

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

    return (
        <React.Fragment>
            <ListNotification
                actionMode={actionMode}
                setActionMode={setActionMode}
                selectedData={selectedData}
                setSelectedData={setSelectedData}
            />
            <DetailNotification
                visible={isModalVisible}
                onCancel={handleCancel}
                form={form}
                selectedData={selectedData}
            />
        </React.Fragment>
    );
});

export default IndexNotification;
