import { useState, useCallback, useMemo, useEffect } from 'react';
import { IFormulaire, FormulaireTab } from '@/shared/types/formulaire';
import useTable from '@/shared/components/table/use-tablets';
import { _formulaires, updateFormulaire, deleteFormulaire } from '@/shared/_mock/_formulaire';
import { DEFAULT_FORMULAIRE_TABLE_HEAD } from '@/shared/_mock/_formulaire';
import { nanoid } from 'nanoid';
import { useGetAllForms } from '@/shared/api/stores/hr-service/forms-recruitment';

export function useFormulaireTable(activeTab: FormulaireTab) {
  const table = useTable();
  const [filters, setFilters] = useState<Record<string, { value: string; condition: string }>>({});
  const { forms } = useGetAllForms();
  const [formulaires, setFormulaires] = useState<IFormulaire[]>([]);  

  const filteredData = useMemo(() => {
    // Apply filters
    return formulaires.filter((formulaire) => {
      return Object.entries(filters).every(([fieldName, filter]) => {
        if (!filter.value) return true;
        
        const fieldValue = String(formulaire[fieldName as keyof IFormulaire] || '').toLowerCase();
        const searchValue = filter.value.toLowerCase();
        
        if (filter.condition === 'contains') {
          return fieldValue.includes(searchValue);
        }
        if (filter.condition === 'equals') {
          return fieldValue === searchValue;
        }
        if (filter.condition === 'startsWith') {
          return fieldValue.startsWith(searchValue);
        }
        if (filter.condition === 'endsWith') {
          return fieldValue.endsWith(searchValue);
        }
        
        return true;
      });
    });
  }, [formulaires, filters]);

  const handleFilterChange = useCallback(
    (key: string, value: string, condition: string) => {
      setFilters((prev) => ({
        ...prev,
        [key]: { value, condition },
      }));
    },
    []
  );

  const handleResetFilters = useCallback(() => {
    setFilters({});
  }, []);

  const notFound = !filteredData.length;

  const handleSave = useCallback((formulaire: IFormulaire) => {
    const savedFormulaire = updateFormulaire(formulaire);
    return savedFormulaire;
  }, []);

  const handleDelete = useCallback((id: string) => {
    // In a real application, this would call an API to delete the item
    console.log('Deleting formulaire with ID:', id);
    
    // Use the deleteFormulaire function to delete the form from our mock data
    const deleted = deleteFormulaire(id);
    
    if (deleted) {
      // Update the local state with the current _formulaires      
      // Deselect the deleted item if it was selected
      if (table.selected.includes(id)) {
        table.onSelectRow(id);
      }
    }
    
    return deleted;
  }, [table]);

  const handleResetColumns = useCallback(() => {
    // No need to set columns as it's handled by the TableControlBar component
    return;
  }, []);

  const handleColumnsChange = useCallback(
    (columns: typeof DEFAULT_FORMULAIRE_TABLE_HEAD) => {
      // No need to set columns as it's handled by the TableControlBar component
      return;
    },
    []
  );

  useEffect(() => {
    if (forms) {
      setFormulaires(forms);
    }
  }, [forms]);

  return {
    table,
    filteredData,
    filters,
    tableHead: DEFAULT_FORMULAIRE_TABLE_HEAD,
    notFound,
    handleFilterChange,
    handleResetFilters,
    handleResetColumns,
    handleColumnsChange,
    handleSave,
    handleDelete,
  };
} 