import { useState, useEffect, useRef, useCallback } 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: 'id', label: 'N°', type: 'text' },
    { 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: 'id',
        sortDirection: 'desc'
    });
    
    const isResettingPage = useRef(false);

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

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

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

    const filteredLotPage = React.useMemo(() => {
        if (!tableManager.filters || Object.keys(tableManager.filters).length === 0) {
            return lotPage || [];
        }

        return (lotPage || []).filter((item: any) => {
            return Object.entries(tableManager.filters).every(([key, { value, condition }]) => {
                if (!value) return true;
                
                const itemValue = item[key];
                if (!itemValue) return false;

                const stringValue = String(itemValue).toLowerCase();
                const filterValue = String(value).toLowerCase();

                switch (condition) {
                    case 'equals':
                        return stringValue === filterValue;
                    case 'startsWith':
                        return stringValue.startsWith(filterValue);
                    case 'endsWith':
                        return stringValue.endsWith(filterValue);
                    case 'contains':
                    default:
                        return stringValue.includes(filterValue);
                }
            });
        });
    }, [lotPage, tableManager.filters]);

    const onResetFilters = () => {
        tableManager.handleResetFilters();
        setParams({
            page: 0,
            size: 20,
            sortBy: 'id',
            sortDirection: 'desc'
        });
    };

    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 filterParams: Record<string, string | number> = {};

        Object.entries(tableManager.filters).forEach(([key, { value, condition }]) => {
            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)) {
                const filterKey = condition ? `${key}_${condition}` : key;
                filterParams[filterKey] = value;
            }
        });

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

        const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
        
        if (paramsChanged) {
            setParams(newParams);
        }
    }, [tableManager.filters, tableManager.table.orderBy, tableManager.table.order, tableManager.table.rowsPerPage, params]);
    
    const handlePageChangeCustom = useCallback((event: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => {
        tableManager.table.onChangePage(event, newPage);
        setParams(prev => ({ ...prev, page: newPage }));
    }, [tableManager.table]);
    
    const handleRowsPerPageChangeCustom = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
        const newSize = parseInt(event.target.value, 10);
        tableManager.table.onChangeRowsPerPage(event);
        setParams(prev => ({ ...prev, size: newSize, page: 0 }));
    }, [tableManager.table]);
    
    useEffect(() => {
        const pageSize = params.size || 20;
        const currentPage = params.page || 0;
        
        if (lotPageTotalElements > 0 && pageSize > 0) {
            const totalPages = Math.ceil(lotPageTotalElements / pageSize);
            
            const needsReset = (currentPage >= totalPages || tableManager.table.page >= totalPages) && 
                              totalPages > 0 && 
                              !isResettingPage.current;
            
            if (needsReset) {
                isResettingPage.current = true;
                
                tableManager.table.onChangePage(null as any, 0);
                
                setTimeout(() => {
                    setParams(prev => ({ ...prev, page: 0 }));
                    isResettingPage.current = false;
                }, 0);
            }
        }
    }, [lotPageTotalElements]);

    return {
        ...tableManager,
        loading,
        error,
        clearError,
        totalLots: lotPageTotalElements || 0,
        onPageChange: handlePageChangeCustom,
        page: params.page || 0,
        onRowsPerPageChange: handleRowsPerPageChangeCustom,
        rowsPerPage: params.size || 20,
        sortBy: params.sortBy || 'id',
        sortDirection: params.sortDirection || 'desc',
        filteredData: filteredLotPage,
        onResetFilters: onResetFilters
    };
    
}