'use client';

import { INITIAL_CHAUFFEUR_DATA } from '@/shared/_mock/_chauffeurs';
import { JoursAttribues, WeekDays } from '@/shared/types/chauffeur';
import { Box, Checkbox, Stack, Typography, Tooltip } from '@mui/material';
import { styled } from '@mui/material/styles';
import { useState, useEffect } from 'react';
import ConditionalComponent from '../table/ConditionalComponent';
import CustomTooltip from '../tooltips/tooltip-custom';

const DayCheckbox = styled(Checkbox)(({ theme }) => ({
  width: 24,
  height: 24,
  padding: 0,
  borderRadius: '50%',
  '& .MuiSvgIcon-root': {
    display: 'none',
  },
  '&.Mui-checked': {
    backgroundColor: theme.palette.primary.main,
  },
  '&:not(.Mui-checked)': {
    backgroundColor: 'transparent',
    border: `1px solid ${theme.palette.primary.main}`,
  },
  '&.Mui-disabled:not(.Mui-checked)': {
    border: `1px solid ${theme.palette.action.disabled}`,
  },
  '&.Mui-disabled.Mui-checked': {
    backgroundColor: theme.palette.action.disabled,
  },
}));

const DayLabel = styled(Typography)(({ theme }) => ({
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  fontSize: '0.6rem',
  pointerEvents: 'none',
}));

interface JoursAttribuesInputProps {
  initialJours?: JoursAttribues;
  otherJours?: JoursAttribues[];
  onChange: (jours: JoursAttribues) => void;
  isReadOnly: boolean;
}

const daysMap = {
  lundi: 'L',
  mardi: 'M',
  mercredi: 'M',
  jeudi: 'J',
  vendredi: 'V',
  samedi: 'S',
  dimanche: 'D',
};

export default function JoursAttribuesInput({
  initialJours,
  otherJours = [],
  onChange,
  isReadOnly,
}: JoursAttribuesInputProps) {
  const [jours, setJours] = useState<JoursAttribues>(initialJours || INITIAL_CHAUFFEUR_DATA.joursAttribues);

  useEffect(() => {
    if (initialJours) {
      console.log("JoursAttribuesInput - initialJours:", initialJours);
      setJours(initialJours);
    }
  }, [initialJours]);

  const isPeriodSelectedInOtherJours = (
    weekType: 'pair' | 'impair',
    day: keyof WeekDays,
    period: 'matin' | 'soir'
  ): boolean => {
    if (!otherJours || otherJours.length === 0) {
      return false;
    }
    return otherJours.some((otherJour) => 
      otherJour && otherJour[weekType] && otherJour[weekType][day] && otherJour[weekType][day][period]
    );
  };

  const handleChange = (
    weekType: 'pair' | 'impair',
    day: keyof WeekDays,
    period: 'matin' | 'soir'
  ) => {
    if (!jours[weekType][day][period] && isPeriodSelectedInOtherJours(weekType, day, period)) {
      return;
    }

    const newJours = { ...jours };
    newJours[weekType][day][period] = !newJours[weekType][day][period];
    setJours(newJours);
    onChange(newJours);
  };

  const handleSelectAll = (weekType: 'pair' | 'impair', checked: boolean) => {
    const newJours = { ...jours };
    Object.keys(newJours[weekType]).forEach((day) => {
      const dayKey = day as keyof WeekDays;
      if (checked) {
        newJours[weekType][dayKey].matin = checked && !isPeriodSelectedInOtherJours(weekType, dayKey, 'matin');
        newJours[weekType][dayKey].soir = checked && !isPeriodSelectedInOtherJours(weekType, dayKey, 'soir');
      } else {
        newJours[weekType][dayKey].matin = false;
        newJours[weekType][dayKey].soir = false;
      }
    });
    setJours(newJours);
    onChange(newJours);
  };

  const renderDayPeriod = (weekType: 'pair' | 'impair', day: keyof WeekDays) => {
    if (!jours || !jours[weekType] || !jours[weekType][day]) {
      return null;
    }
    
    const isMatinDisabled = isReadOnly || (!jours[weekType][day].matin && isPeriodSelectedInOtherJours(weekType, day, 'matin'));
    const isSoirDisabled = isReadOnly || (!jours[weekType][day].soir && isPeriodSelectedInOtherJours(weekType, day, 'soir'));

    const matinCheckbox = (
      <Box sx={{ position: 'relative' }}>
        <DayCheckbox
          disabled={isMatinDisabled}
          checked={jours[weekType][day].matin}
          onChange={() => handleChange(weekType, day, 'matin')}
          size="small"
        />
        <DayLabel
          sx={{
            color: jours[weekType][day].matin
              ? (theme) => theme.palette.primary.contrastText
              : 'inherit',
          }}
        >{`${daysMap[day]}M`}</DayLabel>
      </Box>
    );

    const soirCheckbox = (
      <Box sx={{ position: 'relative' }}>
        <DayCheckbox
          disabled={isSoirDisabled}
          checked={jours[weekType][day].soir}
          onChange={() => handleChange(weekType, day, 'soir')}
          size="small"
        />
        <DayLabel
          sx={{
            color: jours[weekType][day].soir
              ? (theme) => theme.palette.primary.contrastText
              : 'inherit',
          }}
        >{`${daysMap[day]}S`}</DayLabel>
      </Box>
    );

    return (
      <Stack direction="row" spacing={0.3} alignItems="center">
        <ConditionalComponent
          isValid={isMatinDisabled && !isReadOnly}
          defaultComponent={matinCheckbox}
        >
          <CustomTooltip arrow   colorSchema="warning" title="Cette période est déjà sélectionnée dans un autre établissement">
            {matinCheckbox}
          </CustomTooltip>
        </ConditionalComponent>

        <ConditionalComponent
          isValid={isSoirDisabled && !isReadOnly}
          defaultComponent={soirCheckbox}
        >
          <CustomTooltip arrow colorSchema="warning" title="Cette période est déjà sélectionnée dans un autre établissement">
            {soirCheckbox}
          </CustomTooltip>
        </ConditionalComponent>
      </Stack>
    );
  };

  const isAllSelected = (weekType: 'pair' | 'impair') => {
    if (!jours || !jours[weekType]) {
      return false;
    }
    return Object.values(jours[weekType]).every((day) => day.matin && day.soir);
  };

  const canSelectAll = (weekType: 'pair' | 'impair'): boolean => {
    if (!jours || !jours[weekType]) {
      return true; // or false, depending on your requirements
    }
    
    for (const day of Object.keys(jours[weekType]) as Array<keyof WeekDays>) {
      if (isPeriodSelectedInOtherJours(weekType, day, 'matin') ||
        isPeriodSelectedInOtherJours(weekType, day, 'soir')) {
        return false;
      }
    }
    return true;
  };

  return (
    <Stack spacing={1.5}>
      <Box>
        <Stack direction="row" alignItems="center" spacing={1}>
          <Stack direction="row" alignItems="center" spacing={0.5}>
            <ConditionalComponent
              isValid={!(canSelectAll('pair') || isReadOnly)}
              defaultComponent={
                <Checkbox
                  sx={{ p: 0 }}
                  disabled={isReadOnly}
                  checked={isAllSelected('pair')}
                  onChange={(e) => handleSelectAll('pair', e.target.checked)}
                  size="small"
                />
              }
            >
              <CustomTooltip arrow colorSchema="warning" title="Certaines périodes sont déjà sélectionnées dans d'autres établissements">
                <span>
                  <Checkbox
                    sx={{ p: 0 }}
                    disabled={true}
                    checked={isAllSelected('pair')}
                    size="small"
                  />
                </span>
              </CustomTooltip>
            </ConditionalComponent>
            <Typography sx={{ fontSize: '10px', minWidth: 40, textAlign: 'left' }}>
              Paire
            </Typography>
          </Stack>
          <Stack direction="row" spacing={1} justifyContent="space-between" flexGrow={1}>
            {jours && jours.pair && Object.entries(jours.pair).map(([day, periods]) => (
              <Box key={`pair-${day}`}>{renderDayPeriod('pair', day as keyof WeekDays)}</Box>
            ))}
          </Stack>
        </Stack>
      </Box>
      <Box>
        <Stack direction="row" alignItems="center" spacing={1}>
          <Stack direction="row" alignItems="center" spacing={0.5}>
            <ConditionalComponent
              isValid={!(canSelectAll('impair') || isReadOnly)}
              defaultComponent={
                <Checkbox
                  sx={{ p: 0 }}
                  disabled={isReadOnly}
                  checked={isAllSelected('impair')}
                  onChange={(e) => handleSelectAll('impair', e.target.checked)}
                  size="small"
                />
              }
            >
              <CustomTooltip arrow colorSchema="warning" title="Certaines périodes sont déjà sélectionnées dans d'autres établissements">
                <span>
                  <Checkbox
                    sx={{ p: 0 }}
                    disabled={true}
                    checked={isAllSelected('impair')}
                    size="small"
                  />
                </span>
              </CustomTooltip>
            </ConditionalComponent>
            <Typography sx={{ fontSize: '10px', minWidth: 40 }}>Impaire</Typography>
          </Stack>
          <Stack direction="row" spacing={1} justifyContent="space-between" flexGrow={1}>
            {jours && jours.impair && Object.entries(jours.impair).map(([day, periods]) => (
              <Box key={`impair-${day}`}>{renderDayPeriod('impair', day as keyof WeekDays)}</Box>
            ))}
          </Stack>
        </Stack>
      </Box>
    </Stack>
  );
}
