import { useEffect, useState } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableColumn } from '@/shared/types/common';
import { IHolidayImport, IHolidayImportFilterParams } from '@/shared/types/establishment';
import { useEstablishmentStore } from '@/shared/api/stores/admin-service/establishmentStore';

export const _holidayImportHeaders: TableColumn[] = [
    { id: "id", label: "N°", type: "text", align: "left" },
    { id: "holidayImportName", label: "Nom", type: "text" },
    { id: "createdAt", label: "Date d'importation", type: "date" },
    { id: "importedByName", label: "Par", type: "text", align: "left" },
    { id: "", label: "Action" }
]

const holidayImportConfig: TableConfig<IHolidayImport> = {
    initialData: [],
    defaultTableHead: _holidayImportHeaders,
}

export function useHolidayImportTable() {
    const [params, setParams] = useState<IHolidayImportFilterParams>({
        page: 0,
        size: 20,
        sortBy: "id",
        sortDirection: "desc",
        holidayImportName: "",
        createdAt: "",
        importedByName: "",
    });

    const { getHolidayImportPage, holidayImportPage, totalElementsHolidayImport, loading, error } = useEstablishmentStore();

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

    const tableManager = useTableManager<IHolidayImport>({
        ...holidayImportConfig,
        initialData: holidayImportPage,
    });

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

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

    const isValidFilterValue = (value: any): boolean => {
        return value !== null && value !== undefined && value !== '';
    };

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

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

        Object.entries(tableManager.filters).forEach(([key, { value }]) => {
            if (key === 'holidayImportName' && isValidFilterValue(value)) {
                filterParams[key] = value;
            } else if (key === 'createdAt' && isValidFilterValue(value)) {
                filterParams[key] = value;
            } else if (key === 'importedByName' && isValidFilterValue(value)) {
                filterParams[key] = value;
            }
        });

        const newParams: IHolidayImportFilterParams = {
            ...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,
        totalEstablishments: totalElementsHolidayImport || 0,
        onPageChange: handlePageChange,
        page: params.page || 0,
        onRowsPerPageChange: handleRowsPerPageChange,
        rowsPerPage: params.size || 20,
        sortBy: params.sortBy || 'id',
        sortDirection: params.sortDirection || 'desc',
        filteredData: holidayImportPage,
        onResetFilters: onResetFilters
    };
}