import { format, addMinutes } from 'date-fns';
import { fr } from 'date-fns/locale';
import { PlanningEvent, EVENT_COLORS } from '@/shared/_mock/_planningEvents';
import { STATUS_COLORS } from '../constants/planning-constants';
import { TimeSlot, Vehicle } from '../types/planning-types';

export const getHourIntervals = (selectedDate: Date) => {
  const intervals = [];
  let currentTime = new Date(selectedDate);
  currentTime.setHours(0, 0, 0);

  for (let i = 0; i < 24; i++) {
    intervals.push({
      hour: format(currentTime, 'HH'),
      startCell: i * 4,
      endCell: (i + 1) * 4 - 1,
    });
    currentTime = addMinutes(currentTime, 60);
  }
  return intervals;
};

export const getMinuteIntervals = () => {
  return ['00', '15', '30', '45'];
};

export const isTimeSlotInCell = (slot: TimeSlot, cellHour: string, cellMinute: string) => {
  return slot.startHeure === cellHour && slot.startMinute === cellMinute;
};

export const calculateTimeSlotWidth = (
  startHour: string,
  startMinute: string,
  endHour: string,
  endMinute: string,
  intervalMinutes: number,
  cellWidth: number
) => {
  const start = parseInt(startHour) * 60 + parseInt(startMinute);
  const end = parseInt(endHour) * 60 + parseInt(endMinute);
  const duration = end - start;
  const intervals = duration / intervalMinutes;
  return intervals * cellWidth - 5;
};

export const groupOverlappingSlots = (slots: TimeSlot[]) => {
  if (slots.length === 0) return [];

  // Sort slots by start time
  const sortedSlots = [...slots].sort((a, b) => {
    const aStart = parseInt(a.startHeure) * 60 + parseInt(a.startMinute);
    const bStart = parseInt(b.startHeure) * 60 + parseInt(b.startMinute);
    return aStart - bStart;
  });

  const groups: TimeSlot[][] = [];
  let currentGroup = [sortedSlots[0]];
  let currentEnd = parseInt(sortedSlots[0].endHeure) * 60 + parseInt(sortedSlots[0].endMinute);

  for (let i = 1; i < sortedSlots.length; i++) {
    const slot = sortedSlots[i];
    const slotStart = parseInt(slot.startHeure) * 60 + parseInt(slot.startMinute);
    const slotEnd = parseInt(slot.endHeure) * 60 + parseInt(slot.endMinute);

    if (slotStart < currentEnd) {
      // This slot overlaps with the current group
      currentGroup.push(slot);
      currentEnd = Math.max(currentEnd, slotEnd);
    } else {
      // No overlap, start a new group
      groups.push(currentGroup);
      currentGroup = [slot];
      currentEnd = slotEnd;
    }
  }

  // Don't forget to add the last group
  groups.push(currentGroup);
  return groups;
};

export const findSlotIndexInGroup = (slot: TimeSlot, groups: TimeSlot[][]) => {
  for (const group of groups) {
    const index = group.findIndex(s => s.id === slot.id);
    if (index !== -1) {
      return index;
    }
  }
  return 0;
};

// Convert planning events to time slots
export const convertEventsToTimeSlots = (events: PlanningEvent[]): TimeSlot[] => {
  return events.map(event => {
    const startDate = new Date(event.start);
    const endDate = new Date(event.end);
    
    // Transform vehicle data to match the interface
    const vehicle: Vehicle = {
      id: event.vehicle.immatriculation,
      name: `${event.vehicle.marque} ${event.vehicle.modele}`,
      type: event.vehicle.modele,
      registration: event.vehicle.immatriculation,
      driver: event.vehicle.chauffeur || '',
      immatriculation: event.vehicle.immatriculation,
      marque: event.vehicle.marque,
      modele: event.vehicle.modele,
      chauffeur: event.vehicle.chauffeur
    };
    
    return {
      id: event.id,
      vehicleId: event.vehicle.immatriculation,
      start: event.start,
      startHeure: startDate.getHours().toString().padStart(2, '0'),
      startMinute: startDate.getMinutes().toString().padStart(2, '0'),
      endHeure: endDate.getHours().toString().padStart(2, '0'),
      endMinute: endDate.getMinutes().toString().padStart(2, '0'),
      color: EVENT_COLORS[event.type][event.status],
      driverId: event.vehicle.immatriculation,
      title: event.title,
      type: event.type,
      status: event.status,
      interventionDetails: event.interventionDetails,
      technician: event.technician,
      vehicle: vehicle,  // Use the transformed vehicle
      estimatedDuration: event.estimatedDuration
    };
  });
};

export const extractUniqueVehicles = (events: PlanningEvent[]): Vehicle[] => {
  return [...events.reduce((acc: Vehicle[], event) => {
    if (!acc.some(v => v.immatriculation === event.vehicle.immatriculation)) {
      acc.push({
        id: event.vehicle.immatriculation,
        name: `${event.vehicle.marque} ${event.vehicle.modele}`,
        type: event.vehicle.modele,
        registration: event.vehicle.immatriculation,
        driver: event.vehicle.chauffeur || '',
        immatriculation: event.vehicle.immatriculation,
        modele: event.vehicle.modele,
        marque: event.vehicle.marque,
        chauffeur: event.vehicle.chauffeur
      });
    }
    return acc;
  }, [])];
}; 