import { Trip, TripStep, Comment, Document, StepValidationStatus } from "../types";
import { sortTripSteps } from "@/services/itineraryGuards";

export function getTrip(trips: Trip[], tripId: string): Trip | null {
  if (!trips) return null;
  return trips.find(trip => trip.id === tripId) || null;
}

export function getUserTrips(trips: Trip[]): Trip[] {
  // Return an empty array if trips is undefined or null
  if (!trips) return [];
  return trips;
}

export function updateTripsAfterCreate(trips: Trip[], newTrip: Trip): Trip[] {
  if (!trips) return [{ ...newTrip, steps: [], documents: [] }];
  return [{ ...newTrip, steps: [], documents: [] }, ...trips];
}

export function updateTripsAfterUpdate(trips: Trip[], tripId: string, updatedTrip: Trip): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId ? {
      ...trip,
      ...updatedTrip,
      steps: updatedTrip.steps.length > 0 ? updatedTrip.steps : trip.steps,
      documents: updatedTrip.documents.length > 0 ? updatedTrip.documents : trip.documents,
    } : trip
  );
}

export function updateTripsAfterDelete(trips: Trip[], tripId: string): Trip[] {
  if (!trips) return [];
  return trips.filter(trip => trip.id !== tripId);
}

export function updateTripsAfterStepAdd(trips: Trip[], tripId: string, newStep: TripStep): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? {
          ...trip,
          steps: sortTripSteps([...(trip.steps || []), {
            ...newStep,
            comments: [],
            // S'assurer que stepType est correctement défini
            stepType: newStep.stepType || 'activity',
          }])
        }
      : trip
  );
}

export function updateTripsAfterStepUpdate(
  trips: Trip[],
  tripId: string,
  stepId: string,
  updatedStep: TripStep
): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? {
          ...trip,
          steps: sortTripSteps((trip.steps || []).map(step =>
            step.id === stepId
              ? {
                  ...step,
                  ...updatedStep,
                  // S'assurer que stepType est correctement défini
                  stepType: updatedStep.stepType || step.stepType || 'activity',
                }
              : step
          )),
        }
      : trip
  );
}

export function updateTripsAfterStepDelete(trips: Trip[], tripId: string, stepId: string): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? { ...trip, steps: (trip.steps || []).filter(step => step.id !== stepId) }
      : trip
  );
}

export function updateTripsAfterStepValidation(
  trips: Trip[],
  tripId: string,
  stepId: string,
  travelerId: string,
  validationStatus: StepValidationStatus
): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? {
          ...trip,
          steps: (trip.steps || []).map(step =>
            step.id === stepId
              ? {
                  ...step,
                  validationStatus,
                  validations: (step.validations || []).some((validation) => validation.travelerId === travelerId)
                    ? (step.validations || []).map((validation) => validation.travelerId === travelerId
                      ? { ...validation, status: validationStatus, updatedAt: new Date().toISOString() }
                      : validation)
                    : [...(step.validations || []), { travelerId, status: validationStatus, updatedAt: new Date().toISOString() }],
                }
              : step
          ),
        }
      : trip
  );
}

export function updateTripsAfterCommentAdd(
  trips: Trip[],
  tripId: string,
  stepId: string,
  newComment: Comment
): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? {
          ...trip,
          steps: (trip.steps || []).map(step =>
            step.id === stepId
              ? { ...step, comments: [...(step.comments || []), newComment] }
              : step
          ),
        }
      : trip
  );
}

export function updateTripsAfterDocumentAdd(trips: Trip[], tripId: string, newDocument: Document): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? { ...trip, documents: [...(trip.documents || []), newDocument] }
      : trip
  );
}

export function updateTripsAfterDocumentDelete(trips: Trip[], tripId: string, documentId: string): Trip[] {
  if (!trips) return [];
  return trips.map(trip =>
    trip.id === tripId
      ? { ...trip, documents: (trip.documents || []).filter(doc => doc.id !== documentId) }
      : trip
  );
}

/**
 * Met à jour le statut de publication d'une étape dans l'état des voyages
 */
export const updateTripsAfterStepPublication = (trips: Trip[], tripId: string, stepId: string, isPublished: boolean) => {
  return trips.map(trip => {
    if (trip.id === tripId) {
      const updatedSteps = trip.steps.map(step => {
        if (step.id === stepId) {
          return { ...step, isPublished };
        }
        return step;
      });
      return { ...trip, steps: updatedSteps };
    }
    return trip;
  });
};
