'use client';

import { Box, Grid, Typography } from '@mui/material';
import { styled } from '@mui/material/styles';
import {
  startOfMonth,
  endOfMonth,
  eachDayOfInterval,
  format,
  isSameMonth,
  isToday,
  getDay,
} from 'date-fns';
import { fr } from 'date-fns/locale';
import { CalendarEvent } from '../types/calendar-types';

const DayCell = styled(Box)(({ theme }) => ({
  padding: theme.spacing(1),
  borderRight: `1px solid ${theme.palette.divider}`,
  borderBottom: `1px solid ${theme.palette.divider}`,
  backgroundColor: theme.palette.background.paper,
  minHeight: '40px',
  display: 'flex',
  justifyContent: 'flex-start',
  alignItems: 'flex-start',
  position: 'relative',
  '&:hover': {
    backgroundColor: theme.palette.action.hover,
  },
}));

interface Props {
  date: Date;
  events: CalendarEvent[];
  onDayClick: (date: Date) => void;
}

export default function CalendarGrid({ date, events, onDayClick }: Props) {
  const monthStart = startOfMonth(date);
  const monthEnd = endOfMonth(monthStart);
  const allDays = eachDayOfInterval({ start: monthStart, end: monthEnd });
  
  // Weekday names in French
  const weekDays = ['lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.', 'dim.'];

  const daysByWeekday = allDays.reduce((acc, day) => {
    const weekdayIndex = getDay(day); // 0-6
    const adjustedIndex = weekdayIndex === 0 ? 6 : weekdayIndex - 1; 
    if (!acc[adjustedIndex]) {
      acc[adjustedIndex] = [];
    }
    acc[adjustedIndex].push(day);
    return acc;
  }, {} as Record<number, Date[]>);

  return (
    <Box sx={{ width: '100%' }}>
      {/* Days of the week */}
      <Grid container>
        {weekDays.map((day) => (
          <Grid item xs key={day}>
            <Typography 
              variant="body2" 
              sx={{ 
                textAlign: 'center',
                py: 1,
                color: 'text.secondary',
                fontWeight: 500,
                borderBottom: 1,
                borderRight: 1,
                borderColor: 'divider'
              }}
            >
              {day}
            </Typography>
          </Grid>
        ))}
      </Grid>

      {/* Calendar grid with days in columns */}
      <Grid container>
        {weekDays.map((_, weekdayIndex) => (
          <Grid item xs key={weekdayIndex} sx={{ display: 'flex', flexDirection: 'column' }}>
            {daysByWeekday[weekdayIndex]?.map((day) => (
              <DayCell
                key={day.toString()}
                onClick={() => onDayClick(day)}
                sx={{
                  bgcolor: isToday(day) ? 'action.hover' : 'background.paper',
                  opacity: isSameMonth(day, date) ? 1 : 0.5,
                  p: 0,
                }}
              >
                <Typography 
                  variant="body2"
                  sx={{
                    position: 'absolute',
                    top: 8,
                    left: 8,
                    color: !isSameMonth(day, date) ? 'text.disabled' : 'text.primary',
                    fontWeight: isToday(day) ? 600 : 400,
                  }}
                >
                  {format(day, 'd')}
                </Typography>
              </DayCell>
            ))}
          </Grid>
        ))}
      </Grid>
    </Box>
  );
} 