import { useMemo, useCallback, useEffect } from 'react';
import { useFormsStore } from '@/shared/api/stores/hr-service/formsStore';
import { FormDTO } from '@/shared/api/endpoints/hr/forms';
import { TableColumn, TableType } from '@/shared/types/common';

const convertBackendToFrontend = (form: FormDTO): any => ({
  id: form.id,
  nom: form.title,
  description: form.description,
  lien: '',
  dateCreation: form.createdDate,
  dateModification: form.lastModifiedDate,
});

export function useFormulaireTableBackend() {
  const {
    forms,
    loading,
    creating,
    updating,
    deleting,
    totalElements,
    totalPages,
    currentPage,
    pageSize,
    fetchForms,
    createForm,
    updateForm,
    deleteForm,
    setPage,
  } = useFormsStore();

  const tableHead: TableColumn[] = useMemo(
    () => [
      { id: 'nom', label: 'Nom', type: 'text' },
      { id: 'description', label: 'Description', type: 'text' },
      { id: 'lien', label: 'Lien', type: 'text' },
    ],
    []
  );

  useEffect(() => {
    fetchForms();
  }, []);

  const filteredData = useMemo(() => {
    if (!forms || !Array.isArray(forms)) {
      return [];
    }
    return forms.map(convertBackendToFrontend);
  }, [forms]);

  const handleSave = useCallback(
    async (formData: any) => {
      try {
        if (formData.id) {
          const backendData: Partial<FormDTO> = {
            title: formData.nom,
            description: formData.description,
          };
          await updateForm(formData.id, backendData);
        } else {
          const backendData = {
            title: formData.nom,
            description: formData.description,
          };
          await createForm(backendData);
        }
      } catch (error) {
        console.error('Error saving form:', error);
        throw error;
      }
    },
    [createForm, updateForm]
  );

  const handleDelete = useCallback(
    async (formId: string) => {
      try {
        await deleteForm(formId);
      } catch (error) {
        console.error('Error deleting form:', error);
        throw error;
      }
    },
    [deleteForm]
  );

  const mockTable = {
    dense: false,
    selected: [],
    onSelectRow: () => {},
    onSelectAllRows: () => {},
    onResetPage: () => setPage(0),
    page: currentPage,
    rowsPerPage: pageSize,
    totalRows: totalElements,
    orderBy: 'nom',
    order: 'asc' as const,
    onSort: () => {},
    onChangePage: () => {},
    onChangeRowsPerPage: () => {},
    onChangeDense: () => {},
  };

  return {
    table: mockTable,
    filteredData,
    tableHead,
    notFound: !loading && filteredData.length === 0,
    filters: {},
    handleFilterChange: () => {},
    handleResetFilters: () => {},
    handleResetColumns: () => {},
    handleColumnsChange: () => {},
    dataToExport: filteredData,
    handleSave,
    handleDelete,
    loading,
    creating,
    updating,
    deleting,
  };
}
