/* eslint-disable @typescript-eslint/no-explicit-any */
import { Box, Text, Title } from '@mantine/core';
import { useEffect, useRef, useState } from 'react';
import io from 'socket.io-client';
import { WorkingPage } from '../components/dashboard';
import { IBid, IWebBid } from '../system/type';
import { checkStatus } from '../apis/auth';

const socket = io(`${import.meta.env.VITE_SOCKET_URL}/admin-bid-ws`, {
    autoConnect: true,
    transports: ['websocket'],
});

export default function DashBoard() {
    const [workingData, setWorkingData] = useState<(IWebBid & { type: string })[] | (IBid & { type: string })[]>([]);

    const RETRY_CONNECT = useRef(2);

    useEffect(() => {
        socket.connect();

        socket.on('connect', () => {
            socket.emit('getBidsData');
        });

        socket.on('disconnect', async () => {
            if (RETRY_CONNECT.current > 0) {
                await checkStatus();

                socket.connect();

                RETRY_CONNECT.current--;
                return;
            }
        });

        socket.on('adminBidsUpdated', (data: IWebBid[]) => {
            const array = data.reduce((prev, cur) => {
                if (cur.children?.length > 0) {
                    prev = [...prev, ...cur.children];
                }
                prev.push(cur);
                return prev;
            }, [] as any[]);

            const newData = array.map((item) => {
                if (item.children) {
                    return {
                        ...item,
                        type: 'API_BID',
                    };
                }

                return {
                    ...item,
                    type: 'PRODUCT_TAB',
                };
            });
            setWorkingData(newData);
        });

        return () => {
            console.log('🔌 Cleanup WebSocket listeners...');
            socket.off('adminBidsUpdated');
            socket.off('working');
            socket.off('connect');
            socket.off('disconnect');
            socket.disconnect();
        };
    }, []);

    return (
        <Box>
            <Title order={2} mb="md">
                Admin Dashboard
            </Title>

            <Box className="grid grid-cols-4 gap-4">
                {workingData.length > 0 && workingData.map((item, index) => <WorkingPage socket={socket} data={item} key={item.id + index} />)}

                {workingData.length <= 0 && (
                    <Box className="flex items-center justify-center col-span-4">
                        <Text>No Pages</Text>
                    </Box>
                )}
            </Box>
        </Box>
    );
}
