import { TableColumn } from '@/shared/types/common';
import { IVehicleList } from '@/shared/types/flottes/anomaly-config';
import { Dayjs } from 'dayjs';

export const fuelAnomaliesFields = [
  {
    label: 'Utilisation multiple par jour',
    sub: 'Alerte si un conducteur utilise sa carte plus d’une fois par jour',
    field: 'multipleUsePerDay',
  },
  {
    label: 'Plein hors zone de service',
    sub: 'Si un plein est effectué loin de la zone autorisée',
    field: 'fuelOutsideServiceArea',
  },
  {
    label: 'Plein hors horaires de service',
    sub: 'Si une carte est utilisée en dehors des heures autorisées',
    field: 'fuelOutsideServiceHours',
  },
  {
    label: 'Volume anormalement élevé',
    sub: 'Si le volume dépasse la capacité du réservoir',
    field: 'abnormallyHighVolume',
  },
  {
    label: 'Carte utilisée pendant arrêt',
    sub: 'Si un plein est détecté durant un congé ou absence',
    field: 'cardUsedDuringStop',
  },
  {
    label: 'Utilisation sans trajet prévu',
    sub: 'Si utilisation plusieurs jours d’affilée sans trajet justifié',
    field: 'useWithoutPlannedTrip',
  },
  {
    label: 'Station répétée à court intervalle',
    sub: 'Plusieurs pleins à la même station en peu de temps',
    field: 'repeatedStationShortInterval',
  },
  {
    label: 'Consommation anormale',
    sub: 'Écart inhabituel entre kilométrage et consommation',
    field: 'abnormalConsumption',
  },
  {
    label: 'Utilisation hors trajet',
    sub: 'Carte utilisée dans une ville sans trajet correspondant',
    field: 'useOutsideTrip',
  },
];
export const mileageAnomaliesFields = [
  {
    field: 'abnormalConsumptionDeviation',
    label: 'Écart de consommation anormale',
    sub: 'Si la consommation dépasse la tolérance configurée',
  },
  {
    field: 'averageConsumptionPerKm',
    label: 'Moyenne consommation par km',
    sub: "Vérifier l'écart entre kilométrage et consommation moyenne",
  },
];
const DEPARTMENTS = ['Transport', 'Maintenance', 'Logistique', 'Administration'];
const VEHICLES = ['Peugeot 308', 'Renault Clio', 'Dacia Duster', 'Citroën C3', 'Ford Focus'];
const FIRST_NAMES = [
  'Yassine',
  'Sara',
  'Amine',
  'Leila',
  'Omar',
  'Nadia',
  'Rachid',
  'Khalid',
  'Salma',
  'Imane',
];
const LAST_NAMES = [
  'Chhirou',
  'Bennani',
  'El Fassi',
  'Toumi',
  'Ait Lahcen',
  'Moujahid',
  'Boulahdour',
  'Kabbaj',
  'Tazi',
  'Haddad',
];

const generateEmail = (firstName: string, lastName: string, index: number) =>
  `${firstName.toLowerCase()}.${lastName.toLowerCase()}${index}@example.com`;

export const _vehicleList: IVehicleList[] = [...Array(20)].map((_, index) => {
  const firstName = FIRST_NAMES[index % FIRST_NAMES.length];
  const lastName = LAST_NAMES[index % LAST_NAMES.length];
  const vehicle = VEHICLES[index % VEHICLES.length];
  const department = DEPARTMENTS[index % DEPARTMENTS.length];

  return {
    id: (index + 1).toString(),
    firstName,
    lastName,
    vehicle,
    FuelCardNumber: `CARD-${1000 + index}`,
    phone: `+2126${Math.floor(10000000 + Math.random() * 89999999)}`,
    email: generateEmail(firstName, lastName, index),
    departmentName: department,
  };
});

export const INITIAL_VEHICLE_LIST: IVehicleList = {
  id: '',
  firstName: '',
  lastName: '',
  vehicle: '',
  FuelCardNumber: '',
  phone: '',
  email: '',
  departmentName: '',
};

export const VEHICLE_LIST_TABLE_HEAD: TableColumn[] = [
  { id: 'id', label: 'N°Chauffeur', type: 'text' },
  { id: 'firstName', label: 'Prénom', type: 'text' },
  { id: 'lastName', label: 'Nom', type: 'text' },
  { id: 'vehicle', label: 'Véhicule', type: 'text' },
  { id: 'FuelCardNumber', label: 'Carte carburant', type: 'text' },
  { id: 'phone', label: 'Téléphone', type: 'text' },
  { id: 'email', label: 'Email', type: 'text' },
  { id: 'departmentName', label: 'Département', type: 'text' },
];

export type DayIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;

export interface ScheduleDetails {
  startDate: Dayjs | Date | null;
  endDate: Dayjs | Date | null;
  days: DayIndex[];
  startHour: Dayjs | Date | null;
  endHour: Dayjs | Date | null;
}

export interface ConfigItem<TDetails extends object = ScheduleDetails> {
  enabled: boolean;
  details: TDetails;
}

export interface MultipleUseDetails extends ScheduleDetails {
  limitPerDay: number;
}

export interface FuelOutsideServiceAreaDetails extends ScheduleDetails {
  radiusKm: number;
}

export interface FuelOutsideServiceHoursDetails extends ScheduleDetails {
  /** Plage horaire de service (ex: 08:00–18:00) */
  serviceStartHour: Dayjs | Date | null;
  serviceEndHour: Dayjs | Date | null;
}

export interface AbnormallyHighVolumeDetails extends ScheduleDetails {
  /** Capacité réservoir (L) */
  tankCapacityL: number;
}

export interface AbnormalConsumptionDetails extends ScheduleDetails {
  /** Tolérance consommation (%) */
  tolerancePercent: number;
}

export interface KmDeviationDetails extends ScheduleDetails {
  tolerancePercent: number;
}

export interface VehicleAnomalyConfig {
  multipleUsePerDay: ConfigItem<MultipleUseDetails>;
  fuelOutsideServiceArea: ConfigItem<FuelOutsideServiceAreaDetails>;
  fuelOutsideServiceHours: ConfigItem<FuelOutsideServiceHoursDetails>;
  abnormallyHighVolume: ConfigItem<AbnormallyHighVolumeDetails>;
  cardUsedDuringStop: ConfigItem<ScheduleDetails>;
  useWithoutPlannedTrip: ConfigItem<ScheduleDetails>;
  repeatedStationShortInterval: ConfigItem<ScheduleDetails>;
  abnormalConsumption: ConfigItem<AbnormalConsumptionDetails>;
  useOutsideTrip: ConfigItem<ScheduleDetails>;

  km_deviation?: ConfigItem<KmDeviationDetails>;
  avg_per_km?: ConfigItem<ScheduleDetails>;
}

export type ConfigKey = keyof Required<VehicleAnomalyConfig>;
type VRequired = Required<VehicleAnomalyConfig>;

export const DEFAULT_DAYS: DayIndex[] = [1, 2, 3, 4, 5, 6, 0];

export const defaultSchedule = (overrides?: Partial<ScheduleDetails>): ScheduleDetails => ({
  startDate: new Date(),
  endDate: new Date(Date.now() + 30 * 86400000),
  days: DEFAULT_DAYS,
  startHour: new Date(new Date().setHours(0, 0, 0, 0)),
  endHour: new Date(new Date().setHours(23, 59, 0, 0)),
  ...overrides,
});

export const defaultConfigItem = <T extends object = ScheduleDetails>(
  details: T,
  enabled = false
): ConfigItem<T> => ({ enabled, details });

export const createDefaultVehicleAnomalyConfig = (): VehicleAnomalyConfig => ({
  multipleUsePerDay: defaultConfigItem<MultipleUseDetails>({
    ...defaultSchedule(),
    limitPerDay: 1,
  }),
  fuelOutsideServiceArea: defaultConfigItem<FuelOutsideServiceAreaDetails>({
    ...defaultSchedule(),
    radiusKm: 50,
  }),
  fuelOutsideServiceHours: defaultConfigItem<FuelOutsideServiceHoursDetails>({
    ...defaultSchedule(),
    serviceStartHour: new Date(new Date().setHours(8, 0, 0, 0)),
    serviceEndHour: new Date(new Date().setHours(18, 0, 0, 0)),
  }),
  abnormallyHighVolume: defaultConfigItem<AbnormallyHighVolumeDetails>({
    ...defaultSchedule(),
    tankCapacityL: 60,
  }),
  cardUsedDuringStop: defaultConfigItem<ScheduleDetails>(defaultSchedule()),
  useWithoutPlannedTrip: defaultConfigItem<ScheduleDetails>(defaultSchedule()),
  repeatedStationShortInterval: defaultConfigItem<ScheduleDetails>(defaultSchedule()),
  abnormalConsumption: defaultConfigItem<AbnormalConsumptionDetails>({
    ...defaultSchedule(),
    tolerancePercent: 10,
  }),
  useOutsideTrip: defaultConfigItem<ScheduleDetails>(defaultSchedule()),

  km_deviation: defaultConfigItem<KmDeviationDetails>({
    ...defaultSchedule(),
    tolerancePercent: 10,
  }),
  avg_per_km: defaultConfigItem<ScheduleDetails>(defaultSchedule()),
});

export function setEnabled(
  cfg: VehicleAnomalyConfig,
  key: ConfigKey,
  enabled: boolean
): VehicleAnomalyConfig {
  const item = (cfg as VRequired)[key];
  return {
    ...cfg,
    [key]: { ...item, enabled },
  } as VehicleAnomalyConfig;
}

export function updateDetails<K extends ConfigKey, F extends keyof VRequired[K]['details']>(
  cfg: VehicleAnomalyConfig,
  key: K,
  field: F,
  value: VRequired[K]['details'][F]
): VehicleAnomalyConfig {
  const item = (cfg as VRequired)[key];
  return {
    ...cfg,
    [key]: {
      ...item,
      details: {
        ...item.details,
        [field]: value,
      },
    },
  } as VehicleAnomalyConfig;
}

export function applyDetailsToKeys<K extends ConfigKey>(
  cfg: VehicleAnomalyConfig,
  sourceKey: K,
  targetKeys: ConfigKey[],
  options?: { copyEnabled?: boolean }
): VehicleAnomalyConfig {
  const src = (cfg as VRequired)[sourceKey];
  const next: VehicleAnomalyConfig = { ...cfg };

  for (const k of targetKeys) {
    const t = (next as VRequired)[k];
    (next as any)[k] = {
      ...t,
      details: { ...src.details },
      ...(options?.copyEnabled ? { enabled: src.enabled } : {}),
    };
  }
  return next;
}
