import { type IRevision, StatutCT, UserType, IRevisionHistory, RevisionAction } from '@/shared/types/flottes/revision';
import { type TableColumn } from '@/shared/types/common';
import { InterventionType } from '@/shared/types/flottes/vehicule';
import { _interventions } from './_supplier';

// Status color mapping similar to absence system
export const STATUS_COLORS: {
  [key: string]: { color: string; backgroundColor: string };
} = {
  'À faire': {
    color: '#FF3434',
    backgroundColor: '#FFE1E1',
  },
  'En cours': {
    color: '#FF9500', 
    backgroundColor: '#FFF4E6',
  },
  'Terminé': {
    color: '#36B37E',
    backgroundColor: '#E9FBF0',
  },
};

// Function to get status label in French
export const getRevisionStatut = (status: string): string => {
  const statusMap: { [key: string]: string } = {
    'A_FAIRE': 'À faire',
    'EN_COURS': 'En cours', 
    'TERMINE': 'Terminé',
    'À faire': 'À faire',
    'En cours': 'En cours',
    'Terminé': 'Terminé',
  };
  return statusMap[status] || status;
};

// Function to get status color for borders and chips
export const getRevisionStatusColor = (status: string): string => {
  const normalizedStatus = getRevisionStatut(status);
  return STATUS_COLORS[normalizedStatus]?.color || '#757575';
};

// Status options for revision in French
export const REVISION_STATUS_OPTIONS = [
  { 
    value: 'À faire', 
    label: 'À faire',
    statusForChip: 'a_faire'
  },
  { 
    value: 'En cours', 
    label: 'En cours',
    statusForChip: 'en_cours'
  },
  { 
    value: 'Terminé', 
    label: 'Terminé',
    statusForChip: 'termine'
  },
];
export const revisons = _interventions.filter(intervention => intervention.typeIntervention === InterventionType.Entretien)

export const _revisions: IRevision[] = [
  {
    id: '1',
    immatriculation: 'AA-123-BB',
    type: UserType.CHAUFFEUR,
    personne: 'Jean Dupont',
    dateRevision: '2024-02-15',
    garageRevision: 'Garage Central',
    adresse: '123 Rue de la Paix, Paris',
    statutCT: StatutCT.A_FAIRE,
    kilometrage: '98500',
    observation: 'Bruit moteur à vérifier',
    dateCT: '2024-01-15',
    copieCT: '/documents/ct_aa123bb.pdf',
    idfFlotteVehicule: 'VEH001',
    derniereMiseAJour: '2024-01-20',
    isActive: true,
    supplier: '',
    typeIntervention: InterventionType.Entretien,
    intervention: '',
  },
  {
    id: '2',
    immatriculation: 'CC-456-DD',
    type: UserType.SEDENTAIRE,
    personne: 'Marie Martin',
    dateRevision: '2024-02-20',
    garageRevision: 'Auto Service Pro',
    adresse: '456 Avenue du Général, Lyon',
    statutCT: StatutCT.EN_COURS,
    kilometrage: '125000',
    observation: 'Pneus à changer prochainement',
    dateCT: '2024-01-10',
    copieCT: '/documents/ct_cc456dd.pdf',
    idfFlotteVehicule: 'VEH002',
    derniereMiseAJour: '2024-01-25',
    isActive: true,
    supplier: '',
    typeIntervention: InterventionType.Entretien,
    intervention: '',
  },
  {
    id: '3',
    immatriculation: 'EE-789-FF',
    type: UserType.CHAUFFEUR,
    personne: 'Pierre Durand',
    dateRevision: '2024-01-30',
    garageRevision: 'Mécanique Express',
    adresse: '789 Boulevard Saint-Michel, Marseille',
    statutCT: StatutCT.TERMINE,
    kilometrage: '87000',
    observation: 'Véhicule en parfait état',
    dateCT: '2024-01-30',
    copieCT: '/documents/ct_ee789ff.pdf',
    idfFlotteVehicule: 'VEH003',
    derniereMiseAJour: '2024-01-30',
    isActive: true,
    supplier: '',
    typeIntervention: InterventionType.Entretien,
    intervention: '',
  },
  {
    id: '4',
    immatriculation: 'GG-012-HH',
    type: UserType.CHAUFFEUR,
    personne: 'Sophie Lambert',
    dateRevision: '2024-02-25',
    garageRevision: 'Garage Central',
    adresse: '123 Rue de la Paix, Paris',
    statutCT: StatutCT.A_FAIRE,
    kilometrage: '19800',
    observation: 'Plaquettes de frein à surveiller',
    dateCT: '2023-12-15',
    copieCT: '/documents/ct_gg012hh.pdf',
    idfFlotteVehicule: 'VEH004',
    derniereMiseAJour: '2024-01-22',
    isActive: true,
    supplier: '',
    typeIntervention: InterventionType.Entretien,
    intervention: '',
  },
  {
    id: '5',
    immatriculation: 'II-345-JJ',
    type: UserType.SEDENTAIRE,
    personne: 'Luc Bernard',
    dateRevision: '2024-02-10',
    garageRevision: 'Auto Service Pro',
    adresse: '456 Avenue du Général, Lyon',
    statutCT: StatutCT.TERMINE,
    kilometrage: '156000',
    observation: 'Révision effectuée avec succès',
    dateCT: '2024-02-10',
    copieCT: '/documents/ct_ii345jj.pdf',
    idfFlotteVehicule: 'VEH005',
    derniereMiseAJour: '2024-02-10',
    isActive: false, // This one is archived
    supplier: '',
    typeIntervention: InterventionType.Entretien,
    intervention: '',
  },
];

export const DEFAULT_REVISION_TABLE_HEAD: TableColumn[] = [
  { id: 'immatriculation', label: 'Immatriculation', type: 'text' },
  { 
    id: 'type', 
    label: 'Type', 
    type: 'status',
    options: Object.values(UserType).map(type => ({ value: type, label: type }))
  },
  { id: 'personne', label: 'Personne', type: 'text' },
  { id: 'dateRevision', label: 'Date Révision', type: 'date' },
  { 
    id: 'statutCT', 
    label: 'Statut CT', 
    type: 'status',
    options: Object.values(StatutCT).map(statut => ({ value: statut, label: statut }))
  },
  { id: 'kilometrage', label: 'Kilométrage', type: 'text' },
  { id: 'dateCT', label: 'Date CT', type: 'date' },
  { id: 'derniereMiseAJour', label: 'Dernière mise à jour', type: 'date' },
];

// Display table head with Actions column for proper header alignment
export const DISPLAY_REVISION_TABLE_HEAD: TableColumn[] = [
  ...DEFAULT_REVISION_TABLE_HEAD,
  { id: 'actions', label: 'Action', type: 'action', align: 'center' },
];

// Complete table head with all columns for column manager and export
export const COMPLETE_REVISION_TABLE_HEAD: TableColumn[] = [
  { id: 'immatriculation', label: 'Immatriculation', type: 'text' },
  { 
    id: 'type', 
    label: 'Type', 
    type: 'status',
    options: Object.values(UserType).map(type => ({ value: type, label: type }))
  },
  { id: 'personne', label: 'Personne', type: 'text' },
  { id: 'dateRevision', label: 'Date Révision', type: 'date' },
  { id: 'garageRevision', label: 'Garage Révision', type: 'text' },
  { id: 'adresse', label: 'Adresse', type: 'text' },
  { id: 'revisions', label: 'Révisions', type: 'text' },
  { 
    id: 'statutCT', 
    label: 'Statut CT', 
    type: 'status',
    options: Object.values(StatutCT).map(statut => ({ value: statut, label: statut }))
  },
  { id: 'kilometrage', label: 'Kilométrage', type: 'text' },
  { id: 'observation', label: 'Observation', type: 'text' },
  { id: 'dateCT', label: 'Date CT', type: 'date' },
  { id: 'copieCT', label: 'Copie CT', type: 'file' },
  { id: 'idfFlotteVehicule', label: 'IDF Flotte Véhicule', type: 'text' },
  { id: 'derniereMiseAJour', label: 'Dernière mise à jour', type: 'date' },
];

export const INITIAL_REVISION_DATA: IRevision = {
  id: '',
  immatriculation: '',
  type: UserType.CHAUFFEUR,
  personne: '',
  dateRevision: '',
  garageRevision: '',
  adresse: '',
  statutCT: StatutCT.A_FAIRE,
  kilometrage: '',
  observation: '',
  dateCT: '',
  copieCT: '',
  idfFlotteVehicule: '',
  derniereMiseAJour: '',
  isActive: true,
  supplier: '',
  typeIntervention: InterventionType.Entretien,
  intervention: '',
};

export const _garageRevisions = [
  'Garage Central',
  'Auto Service Pro',
  'Mécanique Express',
  'Garage du Centre',
  'Service Auto Plus',
];

export const _responsables = [
  'Jean Dupont',
  'Marie Martin', 
  'Pierre Durand',
  'Sophie Lambert',
  'Luc Bernard',
];

// Mock history data
export const _revisionHistory: IRevisionHistory[] = [
  {
    id: 'hist_1',
    revisionId: '1',
    action: RevisionAction.CREATED,
    actionBy: 'Administrateur Système',
    actionDate: '2024-01-15T10:30:00',
    comment: 'Création initiale de la révision'
  },
  {
    id: 'hist_2', 
    revisionId: '1',
    action: RevisionAction.STATUS_CHANGED,
    actionBy: 'Jean Dupont',
    actionDate: '2024-01-18T14:20:00',
    previousStatus: StatutCT.A_FAIRE,
    newStatus: StatutCT.EN_COURS,
    comment: 'Révision prise en charge'
  },
  {
    id: 'hist_3',
    revisionId: '2', 
    action: RevisionAction.CT_DOCUMENT_UPLOADED,
    actionBy: 'Marie Martin',
    actionDate: '2024-01-25T16:45:00',
    comment: 'Document CT ajouté'
  },
  {
    id: 'hist_4',
    revisionId: '3',
    action: RevisionAction.STATUS_CHANGED,
    actionBy: 'Pierre Durand',
    actionDate: '2024-01-30T11:15:00',
    previousStatus: StatutCT.EN_COURS,
    newStatus: StatutCT.TERMINE,
    comment: 'Révision terminée avec succès'
  },
  {
    id: 'hist_5',
    revisionId: '5',
    action: RevisionAction.ARCHIVED,
    actionBy: 'Administrateur RH',
    actionDate: '2024-02-10T09:00:00',
    comment: 'Véhicule archivé suite à fin de contrat'
  }
];

// Action labels for history display
export const getRevisionActionLabel = (action: RevisionAction): string => {
  const actionLabels: { [key in RevisionAction]: string } = {
    [RevisionAction.CREATED]: 'Créé',
    [RevisionAction.UPDATED]: 'Modifié',
    [RevisionAction.STATUS_CHANGED]: 'Statut modifié',
    [RevisionAction.ARCHIVED]: 'Archivé',
    [RevisionAction.RESTORED]: 'Restauré',
    [RevisionAction.CT_DOCUMENT_UPLOADED]: 'Document CT ajouté',
    [RevisionAction.CT_DOCUMENT_REMOVED]: 'Document CT supprimé',
  };
  return actionLabels[action] || action;
}; 

// Function to calculate if revision is critical (J-30 or overdue)
export const isRevisionCritical = (revision: IRevision): boolean => {
  const today = new Date();
  const revisionDate = new Date(revision.dateRevision);
  const ctDate = new Date(revision.dateCT);
  
  // Calculate days until revision
  const daysUntilRevision = Math.ceil((revisionDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  // Calculate days until CT expiry (assuming 2-year validity)
  const ctExpiryDate = new Date(ctDate);
  ctExpiryDate.setFullYear(ctExpiryDate.getFullYear() + 2);
  const daysUntilCTExpiry = Math.ceil((ctExpiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  // Critical if revision due within 30 days or overdue, OR CT expires within 30 days
  return (daysUntilRevision <= 30 && revision.statutCT !== StatutCT.TERMINE) || 
         (daysUntilCTExpiry <= 30);
};

// Function to get alert message for critical revisions
export const getRevisionAlertMessage = (revision: IRevision): string | null => {
  const today = new Date();
  const revisionDate = new Date(revision.dateRevision);
  const ctDate = new Date(revision.dateCT);
  
  const daysUntilRevision = Math.ceil((revisionDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  // CT expiry calculation
  const ctExpiryDate = new Date(ctDate);
  ctExpiryDate.setFullYear(ctExpiryDate.getFullYear() + 2);
  const daysUntilCTExpiry = Math.ceil((ctExpiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  if (revision.statutCT !== StatutCT.TERMINE) {
    if (daysUntilRevision < 0) {
      return `Révision en retard de ${Math.abs(daysUntilRevision)} jour(s)`;
    } else if (daysUntilRevision <= 30) {
      return `Révision dans ${daysUntilRevision} jour(s)`;
    }
  }
  
  if (daysUntilCTExpiry <= 30) {
    if (daysUntilCTExpiry < 0) {
      return `CT expiré depuis ${Math.abs(daysUntilCTExpiry)} jour(s)`;
    } else {
      return `CT expire dans ${daysUntilCTExpiry} jour(s)`;
    }
  }
  
  return null;
};

// Function to get alert color based on urgency
export const getAlertColor = (revision: IRevision): string => {
  const today = new Date();
  const revisionDate = new Date(revision.dateRevision);
  const ctDate = new Date(revision.dateCT);
  
  const daysUntilRevision = Math.ceil((revisionDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  // CT expiry calculation
  const ctExpiryDate = new Date(ctDate);
  ctExpiryDate.setFullYear(ctExpiryDate.getFullYear() + 2);
  const daysUntilCTExpiry = Math.ceil((ctExpiryDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
  
  // Critical (red): overdue or expires within 7 days
  if (daysUntilRevision < 0 || daysUntilCTExpiry < 0 || 
      daysUntilRevision <= 7 || daysUntilCTExpiry <= 7) {
    return '#FF3434';
  }
  
  // Warning (orange): within 30 days
  if (daysUntilRevision <= 30 || daysUntilCTExpiry <= 30) {
    return '#FF9500';
  }
  
  return '#36B37E'; // Green - all good
}; 