import { useCallback, useEffect, useMemo } from 'react';
import { useEmployeesStore } from '@/shared/api/stores/hr-service/employeesStore';
import type { IEmployee, EmployeeFilters } from '@/shared/types/employee';
import type { Candidat } from '@/shared/types/candidat';
import { useSnackbar } from 'notistack';

const transformEmployeeToCandidat = (employee: IEmployee): Candidat => {
  return {
    id: employee.id.toString(),
    numeroSalarié: employee.employeeNumber,
    civilite: (employee.civility === 'Mr'
      ? 'M'
      : employee.civility === 'Mrs'
        ? 'Mme'
        : employee.civility === 'Miss'
          ? 'Mlle'
          : employee.civility) as 'M' | 'Mme' | 'Mlle',
    nom: employee.lastName,
    nomFamille: employee.lastName,
    prenom: employee.firstName,
    villeNaissance: employee.birthCity || '',
    dateNaissance: employee.birthDate,
    nationalite: employee.nationality,
    email: employee.email,
    telephone: employee.phone,
    adresse: {
      address: employee.address,
      lat: 0,
      lng: 0,
    },
    codePostal: employee.postalCode,
    ville: employee.city,
    dureePermis: employee.licenseDuration || '',
    numeroPermis: employee.licenseNumber || '',
    numeroSS: employee.socialSecurityNumber || '',
    dateDebutContrat: employee.contractStartDate || '',
    dateSignatureContrat: employee.contractSignatureDate || '',
    dateInscription: employee.createdDate,
    status:
      employee.status === 'EMPLOYEE'
        ? 'Salarié'
        : employee.status === 'SORTI'
          ? 'Sorti'
          : 'Archivé',
    tauxHoraire: parseFloat(employee.hourlyRate || '0') || 0,
    cni: null,
    permisConduire: null,
    carteVitale: null,
    rib: null,
    type: employee.type === 'DRIVER' ? 'chauffeur' : 'sedentaire',
    workingHours: [],
    departement: employee.department,
    fuelCard: employee.fuelType ? [employee.fuelType] : [],

    licensePath: employee.licensePath || '',
    idCardPath: employee.idCardPath || '',
    healthCardPath: employee.healthCardPath || '',
    bankDetailsPath: employee.bankDetailsPath || '',
    profilePicturePath: employee.profilePicturePath || '',
    licenseUrl: employee.licenseUrl || '',
    idCardUrl: employee.idCardUrl || '',
    healthCardUrl: employee.healthCardUrl || '',
    bankDetailsUrl: employee.bankDetailsUrl || '',
    profilePictureUrl: employee.profilePictureUrl || employee.profilePicturePath || '',
    fullName: employee.fullName || `${employee.firstName} ${employee.lastName}`,
  };
};

const transformCandidatToEmployeeData = (candidat: Candidat, isUpdate: boolean = false): any => {
  const baseData = {
    civility:
      candidat.civilite === 'M'
        ? 'Mr'
        : candidat.civilite === 'Mme'
          ? 'Mrs'
          : candidat.civilite === 'Mlle'
            ? 'Miss'
            : candidat.civilite,
    lastName: candidat.nom,
    firstName: candidat.prenom,
    birthDate: candidat.dateNaissance ? new Date(candidat.dateNaissance) : new Date(),
    birthCity: candidat.villeNaissance || '',
    nationality: candidat.nationalite || 'Française',
    email: candidat.email,
    phone: candidat.telephone,
    address: typeof candidat.adresse === 'object' ? candidat.adresse.address : candidat.adresse,
    postalCode: candidat.codePostal,
    city: candidat.ville,
    licenseDuration: candidat.dureePermis || '',
    licenseNumber: candidat.numeroPermis || '',
    socialSecurityNumber: candidat.numeroSS || '',
    contractStartDate: candidat.dateDebutContrat ? new Date(candidat.dateDebutContrat) : undefined,
    contractSignatureDate: candidat.dateSignatureContrat
      ? new Date(candidat.dateSignatureContrat)
      : undefined,
    hourlyRate: candidat.tauxHoraire ? candidat.tauxHoraire.toString() : '',
    department: candidat.departement || '',
    fuelType: candidat.fuelCard && candidat.fuelCard.length > 0 ? candidat.fuelCard[0] : '',
    type: candidat.type === 'chauffeur' ? 'DRIVER' : 'SEDENTARY',
    status:
      candidat.status === 'Salarié'
        ? 'EMPLOYEE'
        : candidat.status === 'Sorti'
          ? 'SORTI'
          : 'ARCHIVE',
  };

  if (isUpdate) {
    return {
      ...baseData,

      existingProfilePicturePath: candidat.profilePicturePath || '',
      existingHealthCardPath: candidat.healthCardPath || '',
      existingBankDetailsPath: candidat.bankDetailsPath || '',
      existingLicensePath: candidat.licensePath || '',
      existingIdCardPath: candidat.idCardPath || '',

      profilePictureFile: candidat.profilePictureFile || undefined,
      healthCardFile: candidat.carteVitale || undefined,
      bankDetailsFile: candidat.rib || undefined,
      licenseFile: candidat.permisConduire || undefined,
      idCardFile: candidat.cni || undefined,
    };
  }

  return {
    ...baseData,

    profilePictureFile: candidat.profilePictureFile || undefined,
    healthCardFile: candidat.carteVitale || undefined,
    bankDetailsFile: candidat.rib || undefined,
    licenseFile: candidat.permisConduire || undefined,
    idCardFile: candidat.cni || undefined,
  };
};

export const useSalarieBackend = () => {
  const { enqueueSnackbar } = useSnackbar();

  const {
    employees,
    currentEmployee,
    totalEmployees,
    loading,
    creating,
    updating,
    deleting,
    copying,
    error,
    filters,
    searchTerm,
    page,
    size,
    sortBy,
    sortDirection,

    // Actions
    setLoading,
    setError,
    setFilters,
    setSearchTerm,
    setPagination,
    setSorting,
    fetchEmployees,
    fetchEmployeeById,
    createEmployee,
    updateEmployee,
    deleteEmployee,
    changeEmployeeStatus,
    copyEmployee,
    resetFilters,
    clearCurrentEmployee,
  } = useEmployeesStore();

  const salaries = useMemo(() => {
    return employees.map(transformEmployeeToCandidat);
  }, [employees]);

  useEffect(() => {
    if (employees.length === 0 && !loading) {
      fetchEmployees();
    }
  }, []);

  const handleSave = useCallback(
    async (salarieData: Candidat) => {
      try {
        const isUpdate = Boolean(salarieData.id && salarieData.id !== 'new');

        const employeeData = transformCandidatToEmployeeData(salarieData, isUpdate);

        let result;
        if (isUpdate) {
          // Update existing employee
          result = await updateEmployee(salarieData.id, employeeData);
          enqueueSnackbar('Salarié mis à jour avec succès', { variant: 'success' });

          await fetchEmployees();

          if (currentEmployee && currentEmployee.id === salarieData.id) {
            await fetchEmployeeById(salarieData.id);
          }
        } else {
          result = await createEmployee(employeeData);
          enqueueSnackbar('Salarié créé avec succès', { variant: 'success' });

          await fetchEmployees();
        }

        // Return the result with the employee ID for working hours creation
        return result;
      } catch (error: any) {
        console.error('❌ Error saving employee:', error);
        enqueueSnackbar(error.message || 'Erreur lors de la sauvegarde du salarié', {
          variant: 'error',
        });
        throw error;
      }
    },
    [
      updateEmployee,
      createEmployee,
      enqueueSnackbar,
      fetchEmployees,
      fetchEmployeeById,
      currentEmployee,
    ]
  );

  const handleStatusChange = useCallback(
    async (employeeId: string, newStatus: string) => {
      try {
        const result = await changeEmployeeStatus(employeeId, newStatus);

        enqueueSnackbar('Statut mis à jour avec succès', { variant: 'success' });
        return result;
      } catch (error: any) {
        console.error('❌ Error updating employee status:', error);
        enqueueSnackbar(error.message || 'Erreur lors de la mise à jour du statut', {
          variant: 'error',
        });
        throw error;
      }
    },
    [changeEmployeeStatus, enqueueSnackbar]
  );

  const handleDelete = useCallback(
    async (employeeId: string) => {
      try {
        const success = await deleteEmployee(employeeId);
        if (success) {
          enqueueSnackbar('Salarié supprimé avec succès', { variant: 'success' });
          return true;
        }
        return false;
      } catch (error: any) {
        console.error('Error deleting employee:', error);
        enqueueSnackbar(error.message || 'Erreur lors de la suppression du salarié', {
          variant: 'error',
        });
        throw error;
      }
    },
    [deleteEmployee, enqueueSnackbar]
  );

  const handleFilterChange = useCallback(
    (newFilters: Partial<EmployeeFilters>) => {
      setFilters(newFilters);

      setTimeout(() => {
        const state = useEmployeesStore.getState();
        state.fetchEmployees();
      }, 100);
    },
    [setFilters]
  );

  const handleSearch = useCallback(
    (term: string) => {
      setSearchTerm(term);

      setTimeout(() => {
        const state = useEmployeesStore.getState();
        state.fetchEmployees();
      }, 300);
    },
    [setSearchTerm]
  );

  const handlePaginationChange = useCallback(
    (newPage: number, newSize: number) => {
      setPagination(newPage, newSize);
      setTimeout(() => {
        const state = useEmployeesStore.getState();
        state.fetchEmployees();
      }, 100);
    },
    [setPagination]
  );

  const handleSortingChange = useCallback(
    (newSortBy: string, newSortDirection: 'asc' | 'desc') => {
      setSorting(newSortBy, newSortDirection);
      setTimeout(() => {
        const state = useEmployeesStore.getState();
        state.fetchEmployees();
      }, 100);
    },
    [setSorting]
  );

  const handleCopyEmployee = useCallback(
    async (employeeId: string) => {
      try {
        const copiedEmployee = await copyEmployee(employeeId);
        if (copiedEmployee) {
          enqueueSnackbar('Employé copié avec succès', { variant: 'success' });
          return copiedEmployee;
        }
      } catch (error: any) {
        console.error('Error copying employee:', error);
        enqueueSnackbar("Erreur lors de la copie de l'employé", { variant: 'error' });
        throw error;
      }
    },
    [copyEmployee, enqueueSnackbar]
  );

  useEffect(() => {
    if (error) {
      enqueueSnackbar(error, { variant: 'error' });
      setError(null);
    }
  }, [error, enqueueSnackbar, setError]);

  return {
    salaries,
    employees,
    currentEmployee,
    totalEmployees,

    loading: loading || creating || updating || deleting || copying,
    creating,
    updating,
    deleting,
    copying,

    error,

    filters,
    searchTerm,
    page,
    size,
    sortBy,
    sortDirection,
    totalPages: Math.ceil(totalEmployees / size),

    handleSave,
    handleStatusChange,
    handleDelete,
    handleCopyEmployee,
    handleFilterChange,
    handleSearch,
    handlePaginationChange,
    handleSortingChange,
    resetFilters,
    clearCurrentEmployee,

    fetchEmployees,
    fetchEmployeeById,
  };
};

export { transformEmployeeToCandidat };
