import { useState, useEffect } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableColumn } from '@/shared/types/common';
import React from 'react';
import type { LotList, LotPageFilterParams } from '@/shared/types/infrastructure';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';

export const DEFAULT_TABLE_HEAD: TableColumn[] = [
    { id: "number", label: "Numéro", type: "text" },
    { id: "description", label: "Description", type: "text" },
    { id: "createdAt", label: "Date de création", type: "date" },
    { id: "", label: "Action" },
];

const lotConfig: TableConfig<LotList> = {
    initialData: [],
    defaultTableHead: DEFAULT_TABLE_HEAD,
};

export function useLotTable() {
    const [params, setParams] = useState<LotPageFilterParams>({
        page: 0,
        size: 20,
        sortBy: 'number',
        sortDirection: 'desc'
    });

    const { lotPage, lotPageTotalElements, loading, error, fetchLotPage } = useInfrastructureStore();

    useEffect(() => {
        fetchLotPage(params);
    }, [params]);

    const tableManager = useTableManager<LotList>({
        ...lotConfig,
        initialData: lotPage || [],
    });

    useEffect(() => {
        if (tableManager.table.rowsPerPage > 0) {
            setParams(prev => ({
                ...prev,
                page: tableManager.table.page,
                size: tableManager.table.rowsPerPage,
            }));
        }
    }, [tableManager.table.page, tableManager.table.rowsPerPage]);

    const isValidDateInput = (value: any): boolean => {
        if (!value || typeof value !== 'string') return false;
        const date = new Date(value);
        return date instanceof Date && !isNaN(date.getTime());
    };
    
    const isValidFilterValue = (value: any): boolean => {
        return value !== null && value !== undefined && value !== '';
    };

    useEffect(() => {
        const baseParams: LotPageFilterParams = {
            page: tableManager.table.page || 0,
            size: tableManager.table.rowsPerPage || 20,
            sortBy: tableManager.table.orderBy || 'number',
            sortDirection: tableManager.table.order.toLowerCase() as 'asc' | 'desc'
        };

        const filterParams: Record<string, string | number> = {};

        Object.entries(tableManager.filters).forEach(([key, { value }]) => {
            if (key === 'createdAt' && isValidDateInput(value)) {
                const date = new Date(value);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                filterParams[key] = `${year}-${month}-${day}T00:00:00`;
            } else if (isValidFilterValue(value)) {
                filterParams[key] = value;
            }
        });

        const newParams: LotPageFilterParams = {
            ...baseParams,
            ...filterParams
        };

        const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
        if (paramsChanged) {
            setParams(newParams);
        }
    }, [tableManager.filters, tableManager.table.orderBy, tableManager.table.order]);

    const handlePageChange = (event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
        setParams(prev => ({
            ...prev,
            page: newPage
        }));
    };

    const handleRowsPerPageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const size = parseInt(event.target.value, 10);
        if (!isNaN(size) && size > 0) {
            setParams(prev => ({
                ...prev,
                size,
                page: 0
            }));
        }
    };

    return {
        ...tableManager,
        loading,
        error,
        totalLots: lotPageTotalElements || 0,
        onPageChange: handlePageChange,
        page: params.page,
        onRowsPerPageChange: handleRowsPerPageChange,
        rowsPerPage: params.size,
        sortBy: params.sortBy || 'number',
        sortDirection: params.sortDirection || 'desc',
        filteredData: lotPage
    };
}
