
import { GeolocStatus, IGeolocHistory, IGeolocItem, ITrip, ITripPoint } from "@/shared/types/geoloc";
import { CircuitMap } from '@/shared/types/Maps';
import { StatusColor } from "../sections/chauffeur/planingChauffeur/utils/schedule-utils";
import { TableColumn } from "../types/common";

export const prenomsChauffeur = ['Thomas', 'Léa', 'Martin', 'Sophie', 'Lucas', 'Emma', 'Hugo', 'Clara'];
export const nomsChauffeur = ['Dubois', 'Martin', 'Petit', 'Robert', 'Richard', 'Durand', 'Leroy', 'Moreau'];
export const vehicules = ['Peugeot 5008', 'Renault Trafic', 'Citroën Jumpy', 'Ford Transit', 'Mercedes Sprinter', 'Volkswagen Caravelle', 'Fiat Ducato', 'Toyota Proace'];
export const vehiculeIds = ['VEH-001', 'VEH-002', 'VEH-003', 'VEH-004', 'VEH-005', 'VEH-006', 'VEH-007', 'VEH-008'];
export const routeColors = ['#4285F4', '#EA4335', '#FBBC05', '#34A853', '#8B43EE', '#00ACC1', '#FF6F00', '#C51162'];

export const departements = [
  { code: '13', nom: "Bouches-du-Rhône", center: { lat: 43.2965, lng: 5.3698 } },
  { code: '83', nom: "Var", center: { lat: 43.1257, lng: 5.9304 } },
  { code: '84', nom: "Vaucluse", center: { lat: 43.9493, lng: 4.8055 } },
  { code: '04', nom: "Alpes-de-Haute-Provence", center: { lat: 44.0925, lng: 6.2356 } }
];

export const routesByDepartment: Record<string, CircuitMap[]> = {
  '13': [
    {
      id: "route-13-1",
      name: "Marseille Centre → Vieux Port",
      departement: "13",
      color: StatusColor.PRIMARY,
      status: GeolocStatus.IN_PROGRESS,
      departureDate: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() + 45 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 43.2963, lng: 5.3796 },
        title: "Marseille Centre"
      },
      endPoint: {
        position: { lat: 43.2950, lng: 5.3770 },
        title: "Vieux Port"
      },
      path: [
        { lat: 43.2963, lng: 5.3796 },
        { lat: 43.2965, lng: 5.3780 },
        { lat: 43.2960, lng: 5.3765 },
        { lat: 43.2955, lng: 5.3755 },
        { lat: 43.2950, lng: 5.3770 }
      ],
      users: [
        { position: { lat: 43.2964, lng: 5.3788 }, title: "Anna Leblanc" },
        { position: { lat: 43.29625, lng: 5.37725 }, title: "Marc Dupont" },
        { position: { lat: 43.29575, lng: 5.3760 }, title: "Julie Moreau" },
        { position: { lat: 43.29525, lng: 5.37625 }, title: "Paul Girard" }
      ],
      tolls: [
        { position: { lat: 43.29645, lng: 5.3784 }, title: "Péage Vieux Port" },
        { position: { lat: 43.2956, lng: 5.37575 }, title: "Péage Canebière" }
      ],
      vehicule: "Renault Trafic",
      vehiculeId: "VEH-001",
      prenomChauffeur: "Thomas",
      nomChauffeur: "Dubois",
    },
  ],
  '83': [
    {
      id: "route-83-1",
      name: "Toulon Centre → Port",
      departement: "83",
      color: StatusColor.SUCCESS,
      status: GeolocStatus.IN_PROGRESS,
      departureDate: new Date(Date.now() - 20 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() + 35 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 43.1260, lng: 5.9300 },
        title: "Toulon Centre"
      },
      endPoint: {
        position: { lat: 43.1240, lng: 5.9330 },
        title: "Port de Toulon"
      },
      path: [
        { lat: 43.1260, lng: 5.9300 },
        { lat: 43.1265, lng: 5.9285 },
        { lat: 43.1255, lng: 5.9275 },
        { lat: 43.1245, lng: 5.9290 },
        { lat: 43.1240, lng: 5.9330 }
      ],
      users: [
        { position: { lat: 43.12625, lng: 5.92925 }, title: "Lucas Bernard" },
        { position: { lat: 43.1260, lng: 5.9280 }, title: "Marie Leroy" },
        { position: { lat: 43.12475, lng: 5.92825 }, title: "Antoine Roux" }
      ],
      tolls: [
        { position: { lat: 43.12635, lng: 5.92875 }, title: "Péage Toulon Est" },
        { position: { lat: 43.1250, lng: 5.9282 }, title: "Péage Toulon Ouest" }
      ],
      vehicule: "Ford Transit",
      vehiculeId: "VEH-003",
      prenomChauffeur: "Martin",
      nomChauffeur: "Petit",
    },
    {
      id: "route-83-2",
      name: "Hyères → Îles d'Or",
      departement: "83",
      color: StatusColor.PRIMARY,
      status: GeolocStatus.PLANNED,
      departureDate: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() + 120 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 43.1180, lng: 6.1280 },
        title: "Hyères Centre"
      },
      endPoint: {
        position: { lat: 43.1150, lng: 6.1320 },
        title: "Port d'Hyères"
      },
      path: [
        { lat: 43.1180, lng: 6.1280 },
        { lat: 43.1185, lng: 6.1295 },
        { lat: 43.1175, lng: 6.1310 },
        { lat: 43.1160, lng: 6.1325 },
        { lat: 43.1150, lng: 6.1320 }
      ],
      users: [
        { position: { lat: 43.11825, lng: 6.12875 }, title: "Emma Leroy" },
        { position: { lat: 43.1180, lng: 6.13025 }, title: "Lucas Blanc" },
        { position: { lat: 43.11675, lng: 6.13175 }, title: "Sarah Mercier" }
      ],
      tolls: [],
      vehicule: "Volkswagen Caravelle",
      vehiculeId: "VEH-006",
      prenomChauffeur: "Hugo",
      nomChauffeur: "Leroy",
    }
  ],
  '84': [
    {
      id: "route-84-1",
      name: "Avignon Centre → Palais",
      departement: "84",
      color: StatusColor.PRIMARY,
      status: GeolocStatus.IN_PROGRESS,
      departureDate: new Date(Date.now() - 25 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() + 40 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 43.9490, lng: 4.8050 },
        title: "Avignon Centre"
      },
      endPoint: {
        position: { lat: 43.9510, lng: 4.8080 },
        title: "Palais des Papes"
      },
      path: [
        { lat: 43.9490, lng: 4.8050 },
        { lat: 43.9495, lng: 4.8060 },
        { lat: 43.9500, lng: 4.8070 },
        { lat: 43.9505, lng: 4.8080 },
        { lat: 43.9510, lng: 4.8080 }
      ],
      users: [
        { position: { lat: 43.94925, lng: 4.8055 }, title: "Emma Durand" },
        { position: { lat: 43.94975, lng: 4.8065 }, title: "Lucas Blanc" },
        { position: { lat: 43.95025, lng: 4.8075 }, title: "Sarah Mercier" }
      ],
      tolls: [
        { position: { lat: 43.94935, lng: 4.80575 }, title: "Péage Avignon Centre" },
        { position: { lat: 43.95035, lng: 4.80775 }, title: "Péage Palais" }
      ],
      vehicule: "Mercedes Sprinter",
      vehiculeId: "VEH-004",
      prenomChauffeur: "Sophie",
      nomChauffeur: "Robert",
    },
    {
      id: "route-84-2",
      name: "Orange → Théâtre Antique",
      departement: "84",
      color: StatusColor.WARNING,
      status: GeolocStatus.COMPLETED,
      departureDate: new Date(Date.now() - 120 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() - 60 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 44.1370, lng: 4.8080 },
        title: "Orange Centre"
      },
      endPoint: {
        position: { lat: 44.1350, lng: 4.8100 },
        title: "Théâtre Antique"
      },
      path: [
        { lat: 44.1370, lng: 4.8080 },
        { lat: 44.1375, lng: 4.8070 },
        { lat: 44.1365, lng: 4.8065 },
        { lat: 44.1355, lng: 4.8080 },
        { lat: 44.1350, lng: 4.8100 }
      ],
      users: [
        { position: { lat: 44.13725, lng: 4.8075 }, title: "Clara Moreau" },
        { position: { lat: 44.1370, lng: 4.80675 }, title: "Hugo Lambert" },
        { position: { lat: 44.1360, lng: 4.80725 }, title: "Léa Fournier" }
      ],
      tolls: [],
      vehicule: "Peugeot 5008",
      vehiculeId: "VEH-007",
      prenomChauffeur: "Clara",
      nomChauffeur: "Moreau",
    }
  ],
  '04': [
    {
      id: "route-04-1",
      name: "Digne Centre → Thermes",
      departement: "04",
      color: StatusColor.WARNING,
      status: GeolocStatus.IN_PROGRESS,
      departureDate: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() + 25 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 44.0920, lng: 6.2350 },
        title: "Digne Centre"
      },
      endPoint: {
        position: { lat: 44.0940, lng: 6.2380 },
        title: "Thermes"
      },
      path: [
        { lat: 44.0920, lng: 6.2350 },
        { lat: 44.0925, lng: 6.2360 },
        { lat: 44.0930, lng: 6.2370 },
        { lat: 44.0935, lng: 6.2380 },
        { lat: 44.0940, lng: 6.2380 }
      ],
      users: [
        { position: { lat: 44.09225, lng: 6.2355 }, title: "Hugo Leroy" },
        { position: { lat: 44.09275, lng: 6.2365 }, title: "Chloé Faure" },
        { position: { lat: 44.09325, lng: 6.2375 }, title: "Nathan Rousseau" }
      ],
      tolls: [
        { position: { lat: 44.09235, lng: 6.23575 }, title: "Péage Digne" }
      ],
      vehicule: "Volkswagen Caravelle",
      vehiculeId: "VEH-005",
      prenomChauffeur: "Lucas",
      nomChauffeur: "Richard",
    },
    {
      id: "route-04-2",
      name: "Manosque → Lac",
      departement: "04",
      color: StatusColor.SUCCESS,
      status: GeolocStatus.PLANNED,
      departureDate: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
      arrivalDate: new Date(Date.now() + 90 * 60 * 1000).toISOString(),
      startPoint: {
        position: { lat: 43.8320, lng: 5.7830 },
        title: "Manosque Centre"
      },
      endPoint: {
        position: { lat: 43.8290, lng: 5.7880 },
        title: "Lac de l'Escale"
      },
      path: [
        { lat: 43.8320, lng: 5.7830 },
        { lat: 43.8325, lng: 5.7845 },
        { lat: 43.8315, lng: 5.7860 },
        { lat: 43.8300, lng: 5.7875 },
        { lat: 43.8290, lng: 5.7880 }
      ],
      users: [
        { position: { lat: 43.83225, lng: 5.78375 }, title: "Emma Richard" },
        { position: { lat: 43.8320, lng: 5.78525 }, title: "Maxime Bertrand" },
        { position: { lat: 43.83075, lng: 5.78675 }, title: "Inès Morel" }
      ],
      tolls: [],
      vehicule: "Fiat Ducato",
      vehiculeId: "VEH-008",
      prenomChauffeur: "Emma",
      nomChauffeur: "Durand",
    }
  ]
};

export const _mockGeolocData: IGeolocItem[] = [];

const statusOptions = [GeolocStatus.IN_PROGRESS, GeolocStatus.PLANNED, GeolocStatus.COMPLETED, GeolocStatus.FAILED];

departements.forEach((dept) => {
  const routes = routesByDepartment[dept.code] || [];

  if (routes.length === 0) {
    console.warn(`Aucune route trouvée pour le département ${dept.code}`);
  }

  routes.forEach((route, index) => {
    const vehiculeIndex = index % vehicules.length;
    const chauffeurIndex = index % prenomsChauffeur.length;

    route.vehicule = route.vehicule || vehicules[vehiculeIndex];
    route.vehiculeId = route.vehiculeId || vehiculeIds[vehiculeIndex];
    route.prenomChauffeur = route.prenomChauffeur || prenomsChauffeur[chauffeurIndex];
    route.nomChauffeur = route.nomChauffeur || nomsChauffeur[chauffeurIndex];
    route.departement = route.departement || dept.code;
    route.status = route.status || statusOptions[index % statusOptions.length];
    route.departureDate = route.departureDate || new Date().toISOString();
    route.arrivalDate = route.arrivalDate || new Date(Date.now() + 60 * 60 * 1000).toISOString();

    const geolocItem: IGeolocItem = {
      id: `geo-${dept.code}-${index + 1}`,
      status: route.status,
      nomChauffeur: route.nomChauffeur,
      prenomChauffeur: route.prenomChauffeur,
      vehicule: route.vehicule,
      vehiculeId: route.vehiculeId,
      distance: Math.round((2 + Math.random() * 5) * 10) / 10,
      duree: `0h${25 + index * 5}`,
      vitesseMoyenne: 30 + index * 2,
      consommation: (5 + Math.random() * 3).toFixed(1),
      tolls: route.tolls,
      departureDate: route.departureDate,
      arrivalDate: route.arrivalDate,
      adresseDepart: route.startPoint?.title || `Départ ${dept.nom}`,
      adresseArrivee: route.endPoint?.title || `Arrivée ${dept.nom}`,
      agence: `Agence ${dept.nom}`,
      departement: dept.code,
      secteur: 'Centre-ville',
      dateDepart: route.departureDate,
      dateArrivee: route.arrivalDate,
      routes: [route]
    };

    _mockGeolocData.push(geolocItem);
  });
});

export const DEFAULT_GEOLOC_TABLE_HEAD: TableColumn[] = [
  { id: 'status', label: 'État', type: 'status', width: 100 },
  { id: 'prenomChauffeur', label: 'Prénom', type: 'text', width: 100 },
  { id: 'nomChauffeur', label: 'Nom', type: 'text', width: 100 },
  { id: 'vehicule', label: 'Véhicule', type: 'text', width: 100 },
  { id: 'vehiculeId', label: 'ID Véhicule', type: 'text', width: 100 },
  { id: 'departement', label: 'Département', type: 'text', width: 100 },
  { id: 'distance', label: 'Distance (km)', type: 'text', width: 100 },
  { id: 'duree', label: 'Durée', type: 'text', width: 100 },
  { id: 'vitesseMoyenne', label: 'Vitesse moy.', type: 'text', width: 100 },
  { id: 'dateDepart', label: 'Date de départ', type: 'date', width: 300 },
  { id: 'dateArrivee', label: "Date d'arrivée", type: 'date', width: 300 },
  { id: 'adresseDepart', label: 'Adresse de départ', type: 'text', width: 100 },
  { id: 'adresseArrivee', label: "Adresse d'arrivée", type: 'text', width: 100 },
  { id: '', label: 'Action', width: 120 }
];

interface VehiclePositionPoint {
  position: { lat: number; lng: number };
  timestamp: number;
}

// Dans _geolocData.ts

export const predefinedVehiclePositions: Record<string, VehiclePositionPoint[]> = {
  'route-13-1': [
    { position: { lat: 43.2963, lng: 5.3796 }, timestamp: 0 },
    { position: { lat: 43.2965, lng: 5.3780 }, timestamp: 20000 },    // 20 secondes
    { position: { lat: 43.2960, lng: 5.3765 }, timestamp: 40000 },    // 40 secondes
    { position: { lat: 43.2955, lng: 5.3755 }, timestamp: 60000 },    // 60 secondes
    { position: { lat: 43.2950, lng: 5.3770 }, timestamp: 80000 }     // 80 secondes
  ],
  'route-83-1': [
    { position: { lat: 43.1260, lng: 5.9300 }, timestamp: 0 },
    { position: { lat: 43.1265, lng: 5.9285 }, timestamp: 20000 },
    { position: { lat: 43.1255, lng: 5.9275 }, timestamp: 40000 },
    { position: { lat: 43.1245, lng: 5.9290 }, timestamp: 60000 },
    { position: { lat: 43.1240, lng: 5.9330 }, timestamp: 80000 }
  ],
  'route-84-1': [
    { position: { lat: 43.9490, lng: 4.8050 }, timestamp: 0 },
    { position: { lat: 43.9495, lng: 4.8060 }, timestamp: 20000 },
    { position: { lat: 43.9500, lng: 4.8070 }, timestamp: 40000 },
    { position: { lat: 43.9505, lng: 4.8080 }, timestamp: 60000 },
    { position: { lat: 43.9510, lng: 4.8080 }, timestamp: 80000 }
  ],
  'route-84-2': [
    { position: { lat: 44.1370, lng: 4.8080 }, timestamp: 0 },
    { position: { lat: 44.1375, lng: 4.8070 }, timestamp: 20000 },
    { position: { lat: 44.1365, lng: 4.8065 }, timestamp: 40000 },
    { position: { lat: 44.1355, lng: 4.8080 }, timestamp: 60000 },
    { position: { lat: 44.1350, lng: 4.8100 }, timestamp: 80000 }
  ],
  'route-04-1': [
    { position: { lat: 44.0920, lng: 6.2350 }, timestamp: 0 },
    { position: { lat: 44.0925, lng: 6.2360 }, timestamp: 20000 },
    { position: { lat: 44.0930, lng: 6.2370 }, timestamp: 40000 },
    { position: { lat: 44.0935, lng: 6.2380 }, timestamp: 60000 },
    { position: { lat: 44.0940, lng: 6.2380 }, timestamp: 80000 }
  ],
  'route-04-2': [
    { position: { lat: 43.8320, lng: 5.7830 }, timestamp: 0 },
    { position: { lat: 43.8325, lng: 5.7845 }, timestamp: 20000 },
    { position: { lat: 43.8315, lng: 5.7860 }, timestamp: 40000 },
    { position: { lat: 43.8300, lng: 5.7875 }, timestamp: 60000 },
    { position: { lat: 43.8290, lng: 5.7880 }, timestamp: 80000 }
  ]
};

export const INITIAL_GEOLOC_DATA: IGeolocItem = {
  id: '',
  status: GeolocStatus.PLANNED,
  nomChauffeur: '',
  prenomChauffeur: '',
  vehicule: '',
  vehiculeId: '',
  distance: 0,
  duree: '0h00',
  vitesseMoyenne: 0,
  consommation: '0',
  departureDate: '',
  arrivalDate: '',
  adresseDepart: '',
  adresseArrivee: '',
  agence: '',
  departement: '',
  secteur: '',
  dateDepart: '',
  dateArrivee: '',
  routes: [],
};


export const DEFAULT_GEOLOC_HISTORY_TABLE_HEAD: TableColumn[] = [
  { id: 'driverName', label: 'Nom du chauffeur', type: 'text'},
  { id: 'carRegistration', label: 'Immatriculation', type: 'text' },
   { id: 'tripDate', label: 'Date ', type: 'date' },
  { id: 'agence', label: 'Agence', type: 'text' },
  {id:'departement', label: 'Département', type: 'text'},
  { id: 'secteur', label: 'Secteur', type: 'text' },
  { id: '', label: 'Action'}
];
export const _geolocHistory: IGeolocHistory[] = [...Array(25)].map((_, index) => {
  const date = new Date(2002 + Math.floor(index / 12), index % 12, 15).toISOString().split('T')[0];

  const departementCode = departements[index % departements.length].code;

  const trips: ITrip[] = [...Array(5)].map((__, tripIndex) => {
    const tripId = `route-${departementCode}-${tripIndex + 1}`;

    // Chercher points prédéfinis ou générer 5 points dynamiques si absents
    const predefinedPoints = predefinedVehiclePositions[tripId];
    const points: ITripPoint[] = (predefinedPoints && predefinedPoints.length > 0)
      ? predefinedPoints.map((point, i) => ({
          id: `${tripId}-point-${i}`,
          address: `Adresse ${i + 1}`,
          latitude: point.position.lat,
          longitude: point.position.lng,
        }))
      : [...Array(5)].map((__, i) => ({
          id: `${tripId}-point-${i}`,
          address: `Adresse ${i + 1}`,
          latitude:  43.296 + 0.001 * i ,   
          longitude: 5.3765 + 0.001 * i ,   
        }));

    return {
      id: tripId,
      duration: `00:1${tripIndex + 5}:00`,  
      distance: 15 + tripIndex * 5,           
      endHour: `08:0${tripIndex}`,      
      startHour: `08:2${tripIndex}`,       
      departure_address: points.length > 0 ? points[0].address : '',
      arrival_address: points.length > 0 ? points[points.length - 1].address : '',
      avg_speed: 45 + tripIndex * 5,
      points,
    };
  });

  return {
    id: (index + 1).toString(),
    driverName: `${nomsChauffeur[index % nomsChauffeur.length]} ${prenomsChauffeur[index % prenomsChauffeur.length]}`,
    carRegistration: vehiculeIds[index % vehiculeIds.length],
    tripDate: date,
    agence: `Agence ${departements[index % departements.length].nom}`,
    departement: departements[index % departements.length].code,
    secteur: 'Centre-ville',
    trips,
  };
});



export const INITIAL_GEOLOC_HISTORY_DATA: IGeolocHistory = {
  id: '',
  driverName: '',
  carRegistration: '',
  tripDate: '',
  agence: '',
  departement: '',
  secteur: '',
    trips: [], 
};
