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

const DEFAULT_ESTABLISHMENT_TABLE_HEAD: TableColumn[] = [
    { id: "id", label: "N° établissement", type: "text" },
    { id: "establishmentName", label: "Nom établissement", type: "text" },
    { id: "address", label: "Adresse", type: "text" },
    { id: "establishmentSector", label: "Regime", type: "status" },
    { id: "uaiCode", label: "Code UAI", type: "text" },
    { id: "horaire", label: "Horaire", type: "text", align: 'center' },
    { id: "phoneNumber", label: "Téléphone", type: "text" },
    { id: "establishmentType", label: "Type", type: "text" },
    { id: 'departmentName', label: 'Département', type: 'text', align: 'center' },
    { id: "", label: "Action" },
]

const establishmentConfig: TableConfig<EstablishmentTableItem> = {
    initialData: [],
    defaultTableHead: DEFAULT_ESTABLISHMENT_TABLE_HEAD,
};

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

    const { loading, error, fetchEstablishmentsPage, establishments, totalElements } = useEstablishmentStore();

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

    const tableManager = useTableManager<any>({
        ...establishmentConfig,
        initialData: establishments || [],
    });

    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: ContractPageFilterParams = {
            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 === 'id' && isValidFilterValue(value)) {
                filterParams[key] = Number(value);
            } else if (isValidFilterValue(value)) {
                filterParams[key] = value;
            }
        });

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