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, EstablishmentSector, EstablishmentType } 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: "text" },
    { 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, startExportFiltredEstablishments } = 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 (key === 'establishmentSector' && isValidFilterValue(value)) {
                let sector: EstablishmentSector;
                switch (value.toLowerCase()) {
                    case 'privé':
                        sector = EstablishmentSector.PRIVATE;
                        break;
                    case 'public':
                        sector = EstablishmentSector.PUBLIC;
                        break;
                    default:
                        sector = EstablishmentSector.PRIVATE;
                }
                filterParams[key] = sector;
            } else if (key === 'establishmentType' && isValidFilterValue(value)) {
                let type: EstablishmentType;
                switch (value.toLowerCase()) {
                    case 'primaire':
                        type = EstablishmentType.PRIMARY_SCHOOL;
                        break;
                    case 'collège':
                        type = EstablishmentType.MIDDLE_SCHOOL;
                        break;
                    case 'lycée':
                        type = EstablishmentType.HIGH_SCHOOL;
                        break;
                    default:
                        type = EstablishmentType.PRIMARY_SCHOOL;
                }
                filterParams[key] = type;
            } 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
            }));
        }
    };

    const handleStartExportEstablishments = () => {
        startExportFiltredEstablishments(params);
    };

    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,
        handleStartExportEstablishments: handleStartExportEstablishments
    };
}