import { IRHAbsence } from '../types/absence-rh';
import { TableColumn } from '../types/common';

// Backend request types
export const REQUEST_TYPES = ['LEAVE', 'ABSENCE'];

// Backend leave types
export const LEAVE_TYPES = ['LEAVE_PAID', 'LEAVE_SICK', 'LEAVE_RTT'];

// Backend absence types  
export const ABSENCE_TYPES = ['EXTERNAL_ASSIGNMENT', 'PROFESSIONAL_TRAINING', 'EXCEPTIONAL_REMOTE_WORK', 'AUTHORIZED_ABSENCE', 'UNAUTHORIZED_ABSENCE', 'MEDICAL_APPOINTMENT'];

// Backend receiving methods
export const RECEIVING_METHODS = ['APPLICATION', 'EMAIL', 'PHONE', 'PORTAL'];

// States
export const TREATED_STATES = ['Approved', 'Rejected', 'Cancelled', 'Processed'];
export const NON_TREATED_STATES = ['Untreated', 'NON_TRAITE', 'In_progress', 'Unprocessed', 'Waiting'];

// For compatibility with existing code
export const _TYPES_ABSENCE = ABSENCE_TYPES;
export const _CHAUFFEURS = ["Jean Dupont", "Marie Durand", "Pierre Martin", "Sophie Lefebvre", "Ahmed Benali"];
export const _MODES_RECEPTION = RECEIVING_METHODS;
export const _DEPARTEMENTS = ["Transport", "Logistique", "Administration", "Commercial", "Maintenance"];

// French labels for leave types
export const LEAVE_TYPE_LABELS: { [key: string]: string } = {
  'LEAVE_PAID': 'Congé payé',
  'LEAVE_SICK': 'Congé maladie',
  'LEAVE_RTT': 'RTT',
};

// French labels for absence types (excluding LEAVE types)
export const ABSENCE_TYPE_LABELS: { [key: string]: string } = {
  'EXTERNAL_ASSIGNMENT': 'Mission externe',
  'PROFESSIONAL_TRAINING': 'Formation professionnelle', 
  'EXCEPTIONAL_REMOTE_WORK': 'Télétravail exceptionnel',
  'AUTHORIZED_ABSENCE': 'Absence autorisée',
  'UNAUTHORIZED_ABSENCE': 'Absence non autorisée',
  'MEDICAL_APPOINTMENT': 'Rendez-vous médical',
  'OTHER': 'Autre',
};

const TOTAL_ABSENCES = 30;

// Function to generate random absence data
const generateRHAbsences = (states: string[]) => {
  const absences: IRHAbsence[] = [];
  
  const getRandomDate = (start: Date, end: Date) => {
    return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
  };
  
  const formatDate = (date: Date) => {
    return date.toISOString().split("T")[0];
  };
  
  const types: Array<'chauffeur' | 'sédentaire'> = ['chauffeur', 'sédentaire'];
  
  for (let i = 0; i < TOTAL_ABSENCES; i++) {
    const today = new Date();
    const threeMonthsAgo = new Date();
    threeMonthsAgo.setMonth(today.getMonth() - 3);
    
    const startDate = getRandomDate(threeMonthsAgo, today);
    const maxEndDate = new Date(startDate);
    maxEndDate.setDate(startDate.getDate() + 14);
    const endDate = getRandomDate(startDate, maxEndDate);
    
    const requestType = Math.random() > 0.2 ? 'ABSENCE' : 'LEAVE'; // 80% ABSENCE, 20% LEAVE
    const numberOfDays = Math.floor(Math.random() * 10) + 1;
    
    const absence: IRHAbsence = {
      // Backend structure
      id: `ABS-${String(i + 1).padStart(4, '0')}`,
      userId: Math.floor(Math.random() * 10) + 1,
      user: {
        firstName: `FirstName${i}`,
        lastName: `LastName${i}`
      },
      requestType: requestType as 'LEAVE' | 'ABSENCE',
      absenceType: requestType === 'ABSENCE' ? ABSENCE_TYPES[Math.floor(Math.random() * ABSENCE_TYPES.length)] : undefined,
      leaveType: requestType === 'LEAVE' ? LEAVE_TYPES[Math.floor(Math.random() * LEAVE_TYPES.length)] : undefined,
      state: states[Math.floor(Math.random() * states.length)],
      startDate: formatDate(startDate),
      endDate: formatDate(endDate),
      tripsIds: [],
      observations: `Observation ${i}`,
      forecastDate: formatDate(startDate),
      comment: `Comment ${i}`,
      receivingMethod: RECEIVING_METHODS[Math.floor(Math.random() * RECEIVING_METHODS.length)],
      submittedAt: formatDate(new Date()),
      processedAt: Math.random() > 0.5 ? formatDate(new Date()) : undefined,
      numberOfDays,
      authorizedBy: Math.random() > 0.5 ? `Authorizer${i}` : undefined,
      validatedBy: Math.random() > 0.5 ? `Validator${i}` : undefined,
      hoursCount: Math.random() > 0.5 ? Math.floor(Math.random() * 8) + 1 : undefined,
      affectedToTrip: Math.random() > 0.5,
      justificationFileUrl: Math.random() > 0.5 ? `http://example.com/file${i}.pdf` : undefined,
      
      // Legacy fields for backward compatibility
      numeroEnregistrement: `ABS-${String(i + 1).padStart(4, '0')}`,
      nomChauffeur: `${`FirstName${i}`} ${`LastName${i}`}`,
      type: types[Math.floor(Math.random() * types.length)],
      typeAbsence: ABSENCE_TYPES[Math.floor(Math.random() * ABSENCE_TYPES.length)],
      dateDebut: formatDate(startDate),
      dateFin: formatDate(endDate),
      statut: states[Math.floor(Math.random() * states.length)] as any,
      justificatif: `Justification ${i}`,
      affecteTrajet: Math.random() > 0.5 ? 'oui' : 'non',
      modeReception: RECEIVING_METHODS[Math.floor(Math.random() * RECEIVING_METHODS.length)],
      nbrHeures: Math.floor(Math.random() * 8) + 1,
      validerPar: `Validator${i}`,
      autorisePar: `Authorizer${i}`,
      departement: `Department${i % 5}`
    };
    
    absences.push(absence);
  }
  
  return absences;
};

const etatsTraites = ['Approved', 'Rejected', 'Cancelled'];
const etatsRecus = ['In_progress', 'Unprocessed'];

// Generated absence data
export const _absencesTraitees = generateRHAbsences(etatsTraites);
export const _absencesRecues = generateRHAbsences(etatsRecus);

// Function to get status label in French
export const getRHAbsenceStatut = (status: string): string => {
  const statusMap: { [key: string]: string } = {
    'In_progress': 'En cours',
    'Unprocessed': 'Non traité',
    'Approved': 'Validé',
    'Rejected': 'Rejeté',
    // Legacy mappings for backward compatibility
    'Cancelled': 'Rejeté',
    'Processed': 'Validé',
    'Untreated': 'Non traité',
    'NON_TRAITE': 'Non traité',
    'Waiting': 'En cours'
  };
  return statusMap[status] || status;
};

// Status options for RH absences in French (matching original driver absence statuses)
export const RH_ABSENCE_STATUS_OPTIONS = [
  { 
    value: 'In_progress', 
    label: 'En cours',
    statusForChip: 'en_cours'  // For StatusChip color mapping
  },
  { 
    value: 'Unprocessed', 
    label: 'Non traité',
    statusForChip: 'non_traite'  // For StatusChip color mapping
  },
  { 
    value: 'Approved', 
    label: 'Validé',
    statusForChip: 'valide'  // For StatusChip color mapping
  },
  { 
    value: 'Rejected', 
    label: 'Rejeté',
    statusForChip: 'non_valide'  // For StatusChip color mapping
  },
];

// Status options for non-treated absences (only status changes, not validation)
export const RH_ABSENCE_STATUS_UNPROCESSED_OPTIONS = [
  { 
    value: 'In_progress', 
    label: 'En cours',
    statusForChip: 'en_cours'  // For StatusChip color mapping
  },
  { 
    value: 'Unprocessed', 
    label: 'Non traité',
    statusForChip: 'non_traite'  // For StatusChip color mapping
  },
];

// Function to map backend status to DriverAbsenceStatus enum
export const mapToDriverAbsenceStatus = (backendStatus: string): string => {
  const statusMap: { [key: string]: string } = {
    'In_progress': 'en_cours',       // DriverAbsenceStatus.EnCours
    'Unprocessed': 'non_traite',     // DriverAbsenceStatus.NonTraite
    'Approved': 'valide',            // DriverAbsenceStatus.Valide
    'Rejected': 'non_valide',        // DriverAbsenceStatus.Rejete
    'Cancelled': 'non_valide',       // DriverAbsenceStatus.Rejete
    'Processed': 'valide',           // DriverAbsenceStatus.Valide
    'Untreated': 'non_traite',       // DriverAbsenceStatus.NonTraite
    'NON_TRAITE': 'non_traite',      // DriverAbsenceStatus.NonTraite
    'Waiting': 'en_cours'            // DriverAbsenceStatus.EnCours
  };
  return statusMap[backendStatus] || 'non_traite';
};

// Function to get state label
export const getAbsenceEtat = (status: string): string => {
  return getRHAbsenceStatut(status);
};

// Table configurations
export const DEFAULT_ABSENCE_TABLE_HEAD: TableColumn[] = [
  { id: 'numeroEnregistrement', label: 'N° d\'enregistrement', type: 'text', align: 'center' },
  { id: 'nomChauffeur', label: 'Nom du chauffeur', type: 'text', align: 'left' },
  { id: 'requestTypeLabel', label: 'Type de demande', type: 'text', align: 'left' },
  { id: 'typeAbsenceLabel', label: 'Type spécifique', type: 'text', align: 'left' },
  { id: 'dateDebut', label: 'Date de début', type: 'date', align: 'center' },
  { id: 'dateFin', label: 'Date de fin', type: 'date', align: 'center' },
  { id: 'nbrHeures', label: 'Nbr d\'heures', type: 'number', align: 'center' },
  { id: 'autorisePar', label: 'Autorisé par', type: 'text', align: 'left' },
  { id: 'validerPar', label: 'Validé par', type: 'text', align: 'left' },
  { id: 'departement', label: 'Département', type: 'text', align: 'left' },
  { id: 'statut', label: 'Statut de la demande', type: 'text', align: 'left' },
  { id: 'modeReception', label: 'Mode de réception', type: 'text', align: 'left' },
  { id: 'type', label: 'Fonction', type: 'text', align: 'left' },
  { id: 'affecteTrajet', label: 'Affecté au trajet', type: 'text', align: 'center' },
  { id: 'justificatif', label: 'Justificatif', type: 'text', align: 'center' },
  { id: 'actions', label: 'Actions', type: 'text', align: 'center' }
];

export const DEFAULT_ABSENCE_NONTREATED_TABLE_HEAD: TableColumn[] = [
  { id: 'numeroEnregistrement', label: 'N° d\'enregistrement', type: 'text', align: 'center' },
  { id: 'nomChauffeur', label: 'Nom du chauffeur', type: 'text', align: 'left' },
  { id: 'requestTypeLabel', label: 'Type de demande', type: 'text', align: 'left' },
  { id: 'typeAbsenceLabel', label: 'Type spécifique', type: 'text', align: 'left' },
  { id: 'dateDebut', label: 'Date de début', type: 'date', align: 'center' },
  { id: 'dateFin', label: 'Date de fin', type: 'date', align: 'center' },
  { id: 'nbrHeures', label: 'Nbr d\'heures', type: 'number', align: 'center' },
  { id: 'autorisePar', label: 'Autorisé par', type: 'text', align: 'left' },
  { id: 'validerPar', label: 'Validé par', type: 'text', align: 'left' },
  { id: 'departement', label: 'Département', type: 'text', align: 'left' },
  { id: 'statut', label: 'Statut de la demande', type: 'text', align: 'left' },
  { id: 'modeReception', label: 'Mode de réception', type: 'text', align: 'left' },
  { id: 'type', label: 'Fonction', type: 'text', align: 'left' },
  { id: 'affecteTrajet', label: 'Affecté au trajet', type: 'text', align: 'center' },
  { id: 'justificatif', label: 'Justificatif', type: 'text', align: 'center' },
  { id: 'actions', label: 'Actions', type: 'text', align: 'center' }
];

// Initial data for new absence form  
export const INITIAL_ABSENCE_DATA: IRHAbsence = {
  // Backend structure
  id: '',
  userId: 0,
  user: {
    firstName: "",
    lastName: ""
  },
  requestType: 'ABSENCE',
  absenceType: undefined,
  leaveType: undefined,
  state: 'Unprocessed',
  startDate: "",
  endDate: "",
  tripsIds: [],
  observations: "",
  forecastDate: "",
  comment: "",
  receivingMethod: 'APPLICATION',
  submittedAt: "",
  processedAt: undefined,
  numberOfDays: 0,
  authorizedBy: undefined,
  validatedBy: undefined,
  hoursCount: undefined,
  affectedToTrip: false,
  justificationFileUrl: undefined,
  
  // Legacy fields for backward compatibility
  numeroEnregistrement: "",
  nomChauffeur: "",
  type: 'chauffeur',
  typeAbsence: "",
  dateDebut: "",
  dateFin: "",
  statut: 'Unprocessed' as any,
  justificatif: "",
  affecteTrajet: 'non',
  modeReception: 'APPLICATION',
  nbrHeures: 0,
  validerPar: "",
  autorisePar: "",
  departement: ""
};

// Function to map backend status to StatusChip status for proper coloring
export const getStatusChipStatus = (backendStatus: string): string => {
  const statusMap: { [key: string]: string } = {
    'In_progress': 'en_cours',
    'Unprocessed': 'non_traite',
    'Approved': 'valide',
    'Rejected': 'non_valide',
    // Legacy mappings
    'Cancelled': 'non_valide',
    'Processed': 'valide',
    'Untreated': 'non_traite',
    'NON_TRAITE': 'non_traite',
    'Waiting': 'en_cours'
  };
  return statusMap[backendStatus] || 'non_traite';
};

// Function to get request type label in French
export const getRequestTypeLabel = (requestType: string | undefined): string => {
  const requestTypeMap: { [key: string]: string } = {
    'ABSENCE': 'Absence',
    'LEAVE': 'Congé',
    'OTHER': 'Autre demande',
  };
  return requestTypeMap[requestType || 'ABSENCE'] || requestType || '-';
};

// Function to get type label in French for both ABSENCE and LEAVE types
export function getAbsenceTypeLabel(absence: IRHAbsence): string;
export function getAbsenceTypeLabel(backendType: string | null, requestType: string): string;
export function getAbsenceTypeLabel(absenceOrType: IRHAbsence | string | null, requestType?: string): string {
  // Handle the case where first parameter is the actual backend object
  if (absenceOrType && typeof absenceOrType === 'object' && !requestType) {
    const { requestType: type, absenceType, leaveType } = absenceOrType;
    
    if (type === 'LEAVE' && leaveType) {
      return LEAVE_TYPE_LABELS[leaveType] || leaveType;
    }
    
    if (type === 'ABSENCE' && absenceType) {
      return ABSENCE_TYPE_LABELS[absenceType] || absenceType;
    }
    
    return '-';
  }
  
  // Legacy support: when called with (backendType, requestType) parameters
  const backendType = absenceOrType as string | null;
  
  if (requestType === 'LEAVE' && backendType) {
    return LEAVE_TYPE_LABELS[backendType] || backendType;
  }
  
  if (requestType === 'ABSENCE' && backendType) {
    return ABSENCE_TYPE_LABELS[backendType] || backendType;
  }
  
  return '-';
} 
