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

export const DEFAULT_HOLIDAYS_TABLE_HEAD: TableColumn[] = [
    { id: "id", label: "N°", type: "text" },
    { id: "name", label: "Nom", type: "text" },
    { id: "startDate", label: "Date de début", type: "date" },
    { id: "endDate", label: "Date de fin", type: "date" },
    { id: "population", label: "Population", type: "text" },
    { id: "academy", label: "Académie", type: "text" },
    { id: "zoneName", label: 'Zone', type: 'text' },
    { id: "type", label: "Type", type: "text" },
    { id: "isActive", label: "Active", type: "boolean" },
    { id: "", label: "Action" }
]

const defaultHolidaysConfig: TableConfig<IHolidayGeneral> = {
    initialData: [],
    defaultTableHead: DEFAULT_HOLIDAYS_TABLE_HEAD,
}

export function useCalendarHolidays(selectedDate: Date, timeUnit: TimeUnit) {
    const [params, setParams] = useState<IHolidayCalendarFilterParams>({
        year: selectedDate.getFullYear(),
        month: selectedDate.getMonth()
    });

    const userId = localStorage.getItem("userId");

    useEffect(() => {
        if (userId) {
            setParams({ ...params, userId: userId });
        }
    }, [userId]);

    const [holidays, setHolidays] = useState<IHolidayGeneral[]>([]);

    useEffect(() => {
        if (timeUnit === "year") {
            setParams({ year: selectedDate.getFullYear(), month: undefined });
        } else {
            setParams({ year: selectedDate.getFullYear(), month: selectedDate.getMonth() });
        }
    }, [selectedDate, timeUnit]);

    const { 
        holidaysListByYear,
        holidaysListByYearAndMonth,
        getHolidaysListByYear,
        getHolidaysListByYearAndMonth,
        startCsvExportHolidays 
    } = useEstablishmentStore();

    useEffect(() => {
        if (params.month && params.year) {
            getHolidaysListByYearAndMonth(params.year, params.month);
        } else if (params.year) {
            getHolidaysListByYear(params.year);
        }
    }, [params]);

    useEffect(() => {
        setHolidays(holidaysListByYear);
    }, [holidaysListByYear]);

    useEffect(() => {
        setHolidays(holidaysListByYearAndMonth);
    }, [holidaysListByYearAndMonth]);

    const handleCsvExportHolidays = () => {
        startCsvExportHolidays(params);
    }

    const tableManager = useTableManager<IHolidayGeneral>({
        ...defaultHolidaysConfig,
        initialData: holidays || [],
    });

    return {
        ...tableManager,
        filteredData: holidays,
        handleCsvExportHolidays
    };
}