import React from 'react';
import { Box, Paper, Typography, styled } from '@mui/material';
import { useTheme, alpha } from '@mui/material/styles';

const DAYS = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
const HOURS = Array.from({ length: 11 }, (_, i) => i + 8); // 8:00 to 18:00

const PlanningCell = styled(Box)(({ theme }) => ({
  border: `1px solid ${theme.palette.divider}`,
  padding: theme.spacing(1),
  height: '40px',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  flex: 1,
  minWidth: '100px',
}));

const TimeCell = styled(Box)(({ theme }) => ({
  padding: theme.spacing(1),
  height: '40px',
  width: '80px',
  minWidth: '80px',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  borderRight: `1px solid ${theme.palette.divider}`,
}));

interface WorkingHours {
  day: number; // 0-6 for Monday-Sunday
  startHour: number;
  endHour: number;
}

interface SalariePlanningProps {
  workingHours: WorkingHours[];
  isReadOnly?: boolean;
  onChange?: (newWorkingHours: WorkingHours[]) => void;
}

export default function SalariePlanning({ workingHours, isReadOnly = true, onChange }: SalariePlanningProps) {
  const theme = useTheme();

  const isWorking = (day: number, hour: number) => {
    return workingHours.some(
      (schedule) =>
        schedule.day === day &&
        hour >= schedule.startHour &&
        hour < schedule.endHour
    );
  };

  const handleCellClick = (day: number, hour: number) => {
    if (isReadOnly) return;

    const existingSchedule = workingHours.find(
      (schedule) => schedule.day === day && schedule.startHour <= hour && schedule.endHour > hour
    );

    let newWorkingHours: WorkingHours[] = [...workingHours]; // Initialize with current hours

    if (existingSchedule) {
      // Remove the hour from existing schedule
      if (hour === existingSchedule.startHour) {
        // If clicking start hour, increment start
        if (existingSchedule.endHour - existingSchedule.startHour > 1) {
          newWorkingHours = workingHours.map(schedule =>
            schedule === existingSchedule 
              ? { ...schedule, startHour: schedule.startHour + 1 }
              : schedule
          );
        } else {
          // Remove schedule if it's only 1 hour
          newWorkingHours = workingHours.filter(schedule => schedule !== existingSchedule);
        }
      } else if (hour === existingSchedule.endHour - 1) {
        // If clicking end hour, decrement end
        newWorkingHours = workingHours.map(schedule =>
          schedule === existingSchedule 
            ? { ...schedule, endHour: schedule.endHour - 1 }
            : schedule
        );
      }
    } else {
      // Add new hour
      const adjacentBefore = workingHours.find(
        schedule => schedule.day === day && schedule.endHour === hour
      );
      const adjacentAfter = workingHours.find(
        schedule => schedule.day === day && schedule.startHour === hour + 1
      );

      if (adjacentBefore) {
        // Extend existing schedule
        newWorkingHours = workingHours.map(schedule =>
          schedule === adjacentBefore
            ? { ...schedule, endHour: hour + 1 }
            : schedule
        );
      } else if (adjacentAfter) {
        // Extend existing schedule backwards
        newWorkingHours = workingHours.map(schedule =>
          schedule === adjacentAfter
            ? { ...schedule, startHour: hour }
            : schedule
        );
      } else {
        newWorkingHours = [...workingHours, { day, startHour: hour, endHour: hour + 1 }];
      }
    }

    if (newWorkingHours) {
      onChange?.(newWorkingHours);
    }
  };

  return (
    <Paper sx={{ p: 2, mt: 2, overflowX: 'auto' }}>
     
    
      <Box sx={{ 
        display: 'flex',
        flexDirection: 'column',
        minWidth: 'fit-content'
      }}>
        <Box sx={{ display: 'flex' }}>
          <TimeCell sx={{ 
            backgroundColor: theme.palette.grey[100],
            borderTop: `1px solid ${theme.palette.divider}`
          }} />
          
          {DAYS.map((day) => (
            <PlanningCell
              key={day}
              sx={{
                backgroundColor: theme.palette.primary.main,
                color: 'white',
                fontWeight: 'bold',
                borderTop: `1px solid ${theme.palette.divider}`,
              }}
            >
              {day}
            </PlanningCell>
          ))}
        </Box>

        {/* Time slots */}
        {HOURS.map((hour) => (
          <Box key={hour} sx={{ display: 'flex' }}>
            {/* Time column */}
            <TimeCell sx={{ backgroundColor: theme.palette.grey[100] }}>
              {`${hour}:00`}
            </TimeCell>

            {/* Schedule cells */}
            {DAYS.map((_, dayIndex) => (
              <PlanningCell
                key={`${dayIndex}-${hour}`}
                onClick={() => handleCellClick(dayIndex, hour)}
                sx={{
                  backgroundColor: isWorking(dayIndex, hour)
                    ? alpha(theme.palette.primary.main, 0.2)
                    : 'transparent',
                  cursor: isReadOnly ? 'default' : 'pointer',
                  '&:hover': !isReadOnly ? {
                    backgroundColor: isWorking(dayIndex, hour)
                      ? alpha(theme.palette.primary.main, 0.3)
                      : alpha(theme.palette.grey[200], 0.5),
                    outline: `2px solid ${theme.palette.primary.main}`,
                  } : {},
                }}
              />
            ))}
          </Box>
        ))}
      </Box>
    </Paper>
  );
}