'use client';

import React from 'react';
import { Box, Typography, Chip, Tooltip } from '@mui/material';
import { WorkSchedule } from '@/shared/types/client';
import { AccessTime, Schedule } from '@mui/icons-material';

interface ScheduleSummaryProps {
  schedule?: WorkSchedule;
  compact?: boolean;
}

export default function ScheduleSummary({ schedule, compact = false }: ScheduleSummaryProps) {
  if (!schedule) {
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Schedule sx={{ fontSize: 16, color: 'text.disabled' }} />
        {!compact && (
          <Typography variant="body2" color="text.disabled">
            Aucun emploi du temps
          </Typography>
        )}
      </Box>
    );
  }

  const workingDays = Object.values(schedule.weeklySchedule).filter(day => day.isWorkingDay).length;
  const totalHours = Object.values(schedule.weeklySchedule).reduce((total, 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}`);
      const diffMs = end.getTime() - start.getTime();
      const diffHours = diffMs / (1000 * 60 * 60);
      return total + diffHours;
    }
    return total;
  }, 0);

  const averageHours = workingDays > 0 ? totalHours / workingDays : 0;

  if (compact) {
    return (
      <Tooltip
        title={
          <Box>
            <Typography variant="body2" fontWeight="bold">
              Emploi du temps
            </Typography>
            <Typography variant="body2">
              {workingDays} jours travaillés
            </Typography>
            <Typography variant="body2">
              {totalHours.toFixed(1)}h total • {averageHours.toFixed(1)}h/jour
            </Typography>
          </Box>
        }
        arrow
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
          <AccessTime sx={{ fontSize: 14, color: 'primary.main' }} />
          <Typography variant="caption" color="primary.main" fontWeight="medium">
            {workingDays}j
          </Typography>
        </Box>
      </Tooltip>
    );
  }

  return (
    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
      <AccessTime sx={{ fontSize: 16, color: 'primary.main' }} />
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Chip
            label={`${workingDays} jours`}
            size="small"
            color="primary"
            variant="outlined"
          />
          <Typography variant="body2" color="text.secondary">
            {totalHours.toFixed(1)}h total
          </Typography>
        </Box>
        <Typography variant="caption" color="text.secondary">
          Moyenne: {averageHours.toFixed(1)}h/jour
        </Typography>
      </Box>
    </Box>
  );
}
