import { IAbsence } from '@/shared/types/absence';
import { enqueueSnackbar } from 'notistack';

export function sortAbsences(data: IAbsence[], orderBy: string, order: string) {
  if (!orderBy) return data;
  return [...data].sort((a, b) => {
    let aValue = a[orderBy as keyof IAbsence];
    let bValue = b[orderBy as keyof IAbsence];

    if (orderBy === 'usager') {
      aValue = typeof aValue === 'object' && aValue !== null && 'label' in aValue ? (aValue.label as string).toLowerCase() : '';
      bValue = typeof bValue === 'object' && bValue !== null && 'label' in bValue ? (bValue.label as string).toLowerCase() : '';
    }
    if (orderBy === 'dateDebut' || orderBy === 'dateFin' || orderBy === 'previentLe') {
      aValue = aValue ? new Date(aValue as string | Date) : new Date(0);
      bValue = bValue ? new Date(bValue as string | Date) : new Date(0);
    }
    if (aValue && bValue && aValue < bValue) return order === 'asc' ? -1 : 1;
    if (aValue && bValue && aValue > bValue) return order === 'asc' ? 1 : -1;
    return 0;
  });
}

export function mapStateToEtat(apiState: string): string {
  switch (apiState) {
    case 'In_progress':
      return 'En cours';
    case 'Unprocessed':
      return 'Non traité';
    case 'Cancelled':
      return 'Annulé';
    case 'Processed':
      return 'Traité';
    default:
      return 'Non traité';
  }
}
export function mapEtatToState(frontState: string): string {
    switch (frontState) {
      case 'En cours':
        return 'In_progress';
      case 'Non traité':
        return 'Unprocessed';
      case 'Annulé':
        return 'Cancelled';
      case 'Traité':
        return 'Processed';
      default:
        return 'Unprocessed';
    }
}
export function transformApiResponseToIAbsence(apiResponse: any[]): IAbsence[] {
  if (!Array.isArray(apiResponse)) {
    console.error("Invalid API response:", apiResponse);
    return [];
  }
  return apiResponse.map(item => {
    const sensAR = item.concernedTrip.map((trip: string) =>
      trip === 'Outbound' ? 'aller' : 'retour'
    );
    return {
      id: item.id.toString(),
      usager: {
        id: item?.passenger?.id,
        value: item.passenger.id.toString(),
        label: `${item.passenger.firstName} ${item.passenger.lastName}`,
        establishmentName: item.passenger.establishmentName,
        departmentName: item.passenger.departmentName,
        firstName: item.passenger.firstName,
        lastName: item.passenger.lastName
      },
      etat: [mapStateToEtat(item.state)],
      etablissement: item.passenger.establishmentName,
      dateDebut: item.startDate,
      dateFin: item.endDate,
      sensAR,
      observation: item.observations,
      modeReception: item.receivingMethod,
      previentLe: item.forecastDate || '',
      departement: item.passenger.departmentName,
      comment: item.comment,
      par: item.reportedBy || ''
    };
  });
}



export async function handleStatusChange(
  updatedAbsence: IAbsence,
  updateAbsence: (id: number, data: any) => Promise<any>,
  fetchUnprocessedAbsences: () => Promise<any>,
  fetchProcessedAbsences: () => Promise<any>
) {
  try {
    await updateAbsence(parseInt(updatedAbsence.id), updatedAbsence);
    await Promise.all([
      fetchUnprocessedAbsences(),
      fetchProcessedAbsences()
    ]);
    enqueueSnackbar('Statut mis à jour avec succès', { variant: 'success' });
  } catch (error) {
    console.error('Failed to update absence status:', error);
    enqueueSnackbar('Erreur lors de la mise à jour du statut', { variant: 'error' });
  }
}

export async function handleConcernedTripChange(
  row: IAbsence,
  newValues: string[],
  updateAbsence: (id: number, data: any) => Promise<any>,
  fetchUnprocessedAbsences: () => Promise<any>,
  fetchProcessedAbsences: () => Promise<any>,
  mapStateToEtat: (etat: string) => string
) {
  try {
    const payload = {
        id: row.id,
      startDate: row.dateDebut,
      endDate: row.dateFin,
      state: mapEtatToState(row.etat[0]),
      observations: row.observation,
      receivingMethod: row.modeReception,
      forecastDate: row.previentLe,
      comment: row.comment,
      reportedBy: row.par,
      concernedTrip: newValues.map(v => v === 'aller' ? 'Outbound' : 'Return'),
      passengerId: typeof row.usager === 'object' ? row.usager.id : row.usager
    };

    await updateAbsence(parseInt(row.id), payload);
    await Promise.all([fetchUnprocessedAbsences(), fetchProcessedAbsences()]);
  } catch (error) {
    console.error('Failed to update concerned trip:', error);
  }
}

export function exportOptions(handleStartExportAbsences: () => Promise<any>) {
  return [
    {
      label: "Exporter en CSV",
      action: () => handleStartExportAbsences()
    }
  ];
}

export function handleExportError(error: Error) {
  enqueueSnackbar("Erreur lors de l'export:", { variant: "error" });
}

export async function handleSave(
  updatedAbsence: IAbsence,
  updateAbsence: (id: number, data: any) => Promise<any>,
  fetchUnprocessedAbsences: () => Promise<any>,
  fetchProcessedAbsences: () => Promise<any>,
  handleCancel: (tabId: string, isSaved: boolean) => void,
  activeTab: string
) {
    try {
      if (updatedAbsence.id) {
        await updateAbsence(parseInt(updatedAbsence.id), updatedAbsence);
      }
      await Promise.all([
        fetchUnprocessedAbsences(),
        fetchProcessedAbsences()
      ]);
      handleCancel(activeTab, true);
      enqueueSnackbar('Absence enregistrée avec succès', { variant: 'success' });
    } catch (error) {
      console.error('Failed to save absence:', error);
      enqueueSnackbar("Erreur lors de l'enregistrement de l'absence", { variant: 'error' });
    }
  }