"use client";

import React from 'react';
import { Box } from '@mui/system';
import { Grid, Paper, Typography } from '@mui/material';
import AccessTimeIcon from '@mui/icons-material/AccessTime';
import type { WorkSchedule, WeeklySchedule, DaySchedule } from '@/shared/types/client';

const DAYS_OF_WEEK = [
  { key: 'monday', label: 'Lundi', shortLabel: 'Lun' },
  { key: 'tuesday', label: 'Mardi', shortLabel: 'Mar' },
  { key: 'wednesday', label: 'Mercredi', shortLabel: 'Mer' },
  { key: 'thursday', label: 'Jeudi', shortLabel: 'Jeu' },
  { key: 'friday', label: 'Vendredi', shortLabel: 'Ven' },
  { key: 'saturday', label: 'Samedi', shortLabel: 'Sam' },
  { key: 'sunday', label: 'Dimanche', shortLabel: 'Dim' },
];

function getTotalWorkingHours(schedule?: WorkSchedule) {
  if (!schedule?.weeklySchedule) return 0;
  let totalHours = 0;
  Object.values(schedule.weeklySchedule).forEach((day) => {
    if (day.isWorkingDay && day.startTime && day.endTime) {
      const start = new Date(`2000-01-01T${day.startTime}`);
      const end = new Date(`2000-01-01T${day.endTime}`);
      if (!isNaN(start.getTime()) && !isNaN(end.getTime())) {
        const diffMs = end.getTime() - start.getTime();
        totalHours += diffMs / (1000 * 60 * 60);
      }
    }
  });
  return totalHours;
}

function DayItem({ day, schedule }: { day: typeof DAYS_OF_WEEK[number]; schedule?: WorkSchedule }) {
  if (!schedule?.weeklySchedule) return null;
  const daySchedule = schedule.weeklySchedule[day.key as keyof WeeklySchedule];
  if (!daySchedule || typeof daySchedule === 'string') return null;

  const isWorkingDay = (daySchedule as DaySchedule).isWorkingDay;
  return (
    <Grid item xs sx={{ p: 2, textAlign: 'center' }} key={day.key}>
      <Typography variant="body2" sx={{ fontWeight: 'medium', mb: 1, color: isWorkingDay ? 'text.primary' : 'text.disabled' }}>
        {day.label}
      </Typography>
      {isWorkingDay && daySchedule.startTime && daySchedule.endTime ? (
        <Typography variant="body2">
          {daySchedule.startTime} - {daySchedule.endTime}
        </Typography>
      ) : (
        <Typography variant="body2" sx={{ color: 'text.disabled' }}>
          {isWorkingDay ? 'Horaires non définis' : 'Jour libre'}
        </Typography>
      )}
    </Grid>
  );
}

export default function WeeklySchedulePreview({ schedule }: { schedule?: WorkSchedule }) {
  const total = getTotalWorkingHours(schedule).toFixed(1);
  return (
    <Box sx={{ mb: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center' }}>
          <AccessTimeIcon sx={{ mr: 1, color: 'text.secondary' }} />
          <Typography variant="subtitle1">Jours et heures de travail</Typography>
        </Box>
        <Typography variant="subtitle1">Capacité hebdomadaire : {total}h</Typography>
      </Box>

      <Paper sx={{ bgcolor: '#f5f5f5', borderRadius: 1 }}>
        <Grid container>
          {DAYS_OF_WEEK.map((day) => (
            <DayItem key={day.key} day={day} schedule={schedule} />
          ))}
        </Grid>
      </Paper>
    </Box>
  );
}


