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 { SectorList, SectorPageFilterParams } from '@/shared/types/infrastructure';
import { useInfrastructureStore } from '@/shared/api/stores/admin-service/infrastructureStore';
import { useSnackbar } from 'notistack';

export const DEFAULT_TABLE_HEAD: TableColumn[] = [
    { id: 'id', label: 'N°', type: 'text' },
    { id: 'name', label: 'Nom', type: 'text' },
    { id: 'address', label: 'Adresse', type: 'text' },
    { id: 'createdAt', label: 'Date de création', type: 'date' },
    { id: '', label: 'Action' },
];

const sectorConfig: TableConfig<SectorList> = {
    initialData: [],
    defaultTableHead: DEFAULT_TABLE_HEAD,
};

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

    const { 
        sectorPage, 
        sectorPageTotalElements, 
        loading,
        error,
        clearError,
        fetchSectorPage, 
        startExportInfrastructureDataInExcel, 
        exportInfrastructureDataInPdf 
    } = useInfrastructureStore();

	const { enqueueSnackbar } = useSnackbar();

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

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

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

        return (sectorPage || []).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);
                }
            });
        });
    }, [sectorPage, 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 baseParams: SectorPageFilterParams = {
            page: 0,
            size: tableManager.table.rowsPerPage || 20,
            sortBy: tableManager.table.orderBy || 'id',
            sortDirection: (tableManager.table.order || 'desc').toLowerCase() as 'asc' | 'desc'
        };

        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: SectorPageFilterParams = {
            ...baseParams,
            ...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 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 handleStartExportInExcel = async () => {
		await startExportInfrastructureDataInExcel(params);
		const { error: exportError } = useInfrastructureStore.getState();
		if (!exportError) {
			enqueueSnackbar('Export Excel lancé avec succès.', { variant: 'success' });
		} else {
			enqueueSnackbar("Échec de l'export Excel.", { variant: 'error' });
		}
	};

	const handleExportInPdf = async () => {
		await exportInfrastructureDataInPdf(params);
		const { error: exportError } = useInfrastructureStore.getState();
		if (!exportError) {
			enqueueSnackbar('Export PDF lancé avec succès.', { variant: 'success' });
		} else {
			enqueueSnackbar("Échec de l'export PDF.", { variant: 'error' });
		}
	};

    return {
        ...tableManager,
        loading,
        error,
        clearError,
        totalSectors: sectorPageTotalElements || 0,
        onPageChange: handlePageChange,
        page: params.page,
        onRowsPerPageChange: handleRowsPerPageChange,
        rowsPerPage: params.size,
        sortBy: params.sortBy || 'id',
        sortDirection: params.sortDirection || 'desc',
        filteredData: filteredSectorPage,
        handleStartExportInExcel,
        handleExportInPdf,
        onResetFilters
    };
}