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

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

const { Text } = Typography;

// Mock Data
const initialData = [
    {
        key: '3',
        statusCode: 3,
        statusName: 'Done',
        description: 'Indicates that the process is complete.',
    },
    {
        key: '1',
        statusCode: 1,
        statusName: 'Warning',
        description: 'Indicates a warning condition.',
    },
    {
        key: '2',
        statusCode: 2,
        statusName: 'Alarm',
        description: 'Indicates an alarm condition.',
    },
    {
        key: '4',
        statusCode: 4,
        statusName: 'Critical',
        description: 'Indicates a critical condition.',
    },
];

const IndexStatus = memo(function IndexStatus() {
    const navigate = useNavigate();
    const { setBreadcrumbItems } = useBreadcrumb();

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

    // Mock API function
    const getAllStatus = async (params) => {
        const { page = 1, limit = 10, search = '' } = Object.fromEntries(params.entries());
        
        let filteredData = data;
        if (search) {
            filteredData = data.filter(item => 
                item.statusName.toLowerCase().includes(search.toLowerCase())
            );
        }

        const start = (page - 1) * limit;
        const end = start + limit;
        const paginatedData = filteredData.slice(start, end);

        return new Promise(resolve => {
            setTimeout(() => {
                resolve({
                    status: 200,
                    data: {
                        data: paginatedData,
                        total: filteredData.length,
                        paging: {
                            page: parseInt(page),
                            limit: parseInt(limit),
                            total: filteredData.length,
                        },
                    },
                });
            }, 500);
        });
    };

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

    useEffect(() => {
        if (actionMode === 'add' || actionMode === 'edit' || actionMode === 'preview') {
            setIsModalVisible(true);
            setReadOnly(actionMode === 'preview');
        } else {
            setIsModalVisible(false);
        }
    }, [actionMode]);

    const handleDataSaved = (values) => {
        let newData = [...data];
        if (values.key) { // Editing
            const index = newData.findIndex((item) => values.key === item.key);
            if (index > -1) {
                newData.splice(index, 1, values);
            }
        } else { // Adding
            const newKey = (Math.max(...data.map(item => parseInt(item.key))) + 1).toString();
            newData = [{ key: newKey, ...values }, ...newData];
        }
        setData(newData);
    };

    const handleEdit = (record) => {
        setSelectedData(record);
        setActionMode('edit');
    };

    const handlePreview = (record) => {
        setSelectedData(record);
        setActionMode('preview');
    };

    const handleDelete = (record) => {
        NotifConfirmDialog({
            icon: 'question',
            title: 'Konfirmasi',
            message: `Apakah anda yakin ingin menghapus status "${record.statusName}"?`,
            onConfirm: () => {
                const newData = data.filter((item) => item.key !== record.key);
                setData(newData);
                NotifAlert({
                    icon: 'success',
                    title: 'Berhasil',
                    message: `Status "${record.statusName}" berhasil dihapus.`,
                });
            },
        });
    };

    return (
        <React.Fragment>
            <ListStatus
                setActionMode={setActionMode}
                handleEdit={handleEdit}
                handleDelete={handleDelete}
                handlePreview={handlePreview}
                getAllStatus={getAllStatus}
                data={data}
            />
            <DetailStatus
                showModal={isModalVisible}
                setActionMode={setActionMode}
                selectedData={selectedData}
                readOnly={readOnly}
                onDataSaved={handleDataSaved}
                setSelectedData={setSelectedData}
            />
        </React.Fragment>
    );
});

export default IndexStatus;