import { alpha, Box } from '@mui/material';
import { primary, warning, success } from '@/shared/theme/palette';

export const EVENT_TYPE_STYLES :any = {
  'Visite Médicale (médecine du travail)': {
    icon: '🏥',
    showDetails: true 
  },
  'Visite Médicale (Préfectorale)': {
    icon: '🏥',
    showDetails: false
  },
  'Entretien Annuel': {
    icon: '📝',
    showDetails: false
  },
  'Formation': {
    icon: '📝',
    showDetails: false
  },
  'Autre': {
    icon: '📝',
    showDetails: false
  }
};

export const getEventColor = (status: string) => {
  switch (status) {
    case 'prevu':
      return {
        backgroundColor: alpha(primary.main, 0.08),
        textColor: primary.main,
        borderColor: primary.main,
        '--fc-event-border-color': primary.main, 
      };
    case 'annule':
      return {
        backgroundColor: alpha('#FF4842', 0.08),
        textColor: '#B71D18',
        borderColor: '#FF4842',
        '--fc-event-border-color': '#FF4842', 
      };
    case 'termine':
      return {
        backgroundColor: alpha(success.main, 0.08),
        textColor: success.dark,
        borderColor: success.main,
        '--fc-event-border-color': success.main, 
      };
    default:
      return {
        backgroundColor: alpha(primary.main, 0.08),
        textColor: primary.main,
        borderColor: primary.main,
        '--fc-event-border-color': primary.main, 
      };
  }
};

export const formatEventForCalendar = (appointment: any) => {
  const typeStyle = EVENT_TYPE_STYLES[appointment.type] || EVENT_TYPE_STYLES['Autre'];
  const statusStyle = getEventColor(appointment.status);

  // CORRIGÉ : Générer une heure de fin valide
  const generateEndTime = (startTime: string) => {
    if (!startTime) return null;
    
    // Parse de l'heure de début (format HH:mm:ss ou HH:mm)
    const timeParts = startTime.split(':');
    const hours = parseInt(timeParts[0], 10);
    const minutes = parseInt(timeParts[1], 10);
    
    // Ajouter 30 minutes pour l'heure de fin
    const endMinutes = minutes + 30;
    const endHours = hours + Math.floor(endMinutes / 60);
    const finalMinutes = endMinutes % 60;
    
    // Formater avec des zéros devant si nécessaire
    const formattedHours = endHours.toString().padStart(2, '0');
    const formattedMinutes = finalMinutes.toString().padStart(2, '0');
    
    return `${formattedHours}:${formattedMinutes}:00`;
  };

  const endTime = generateEndTime(appointment.time);

  return {
    id: appointment.id,
    title: appointment.driverName,
    start: `${appointment.date}T${appointment.time}`,
    end: endTime ? `${appointment.date}T${endTime}` : null, 
    backgroundColor: statusStyle.backgroundColor,
    borderColor: statusStyle.borderColor,
    textColor: statusStyle.textColor,
    display: 'block',
    extendedProps: {
      appointment,
      medicalCenter: appointment.medicalCenterName,
      doctorName: appointment.doctorName,
      type: appointment.type,
      icon: typeStyle.icon,
      showDetails: typeStyle.showDetails
    },
  };
};

export const renderEventContent = (arg: any) => {
  const { timeText, event } = arg;
  const { type, medicalCenter, doctorName } = event.extendedProps;
  const isMedicalVisit = type === 'Visite Médicale (médecine du travail)';

  const commonBoxStyles = {
    p: 0.25,
    height: '100%',
    display: 'flex',
    flexDirection: 'column',
    gap: 0.25,
    color: event.textColor,
  };

  const headerStyles = {
    display: 'flex',
    alignItems: 'center',
    gap: 0.25,
    fontWeight: 500,
    mb: 0.25, 
  };

  const contentStyles = {
    display: 'flex',
    flexDirection: 'column',
    gap: 0.25, 
  };

  if (isMedicalVisit) {
    return (
      <Box sx={commonBoxStyles}>
        <Box sx={headerStyles}>
          <span>{EVENT_TYPE_STYLES[type]?.icon}</span>
          <span style={{ fontSize: '0.7rem' }}>{timeText}</span>
        </Box>
        <Box sx={contentStyles}>
          <Box component="span" sx={{ fontSize: '0.75rem' }}>
            {event.title} - Dr. {doctorName}
          </Box>
          <Box component="span" sx={{ fontSize: '0.65rem' }}>
            {medicalCenter}
          </Box>
        </Box>
      </Box>
    );
  }

  return (
    <Box sx={commonBoxStyles}>
      <Box sx={headerStyles}>
        <span>{EVENT_TYPE_STYLES[type]?.icon}</span>
        <span style={{ fontSize: '0.7rem' }}>{timeText}</span>
      </Box>
      <Box sx={contentStyles}>
        <Box component="span" sx={{ fontSize: '0.75rem' }}>
          {event.title}
        </Box>
        <Box component="span" sx={{ 
          fontSize: '0.65rem',
          color: event.textColor,
          opacity: 0.85
        }}>
          {type}
        </Box>
      </Box>
    </Box>
  );
};