'use client';

import { JoursAttribues, WeekDays } from '@/shared/types/chauffeur';
import { Box, Checkbox, Stack, Theme, Typography } from '@mui/material';
import { useState, useEffect } from 'react';
import ConditionalComponent from '../table/ConditionalComponent';
import CustomTooltip from '../tooltips/tooltip-custom';
import { DayCheckbox, DayLabel } from './style';
import { INITIAL_JOURS_ATTRIBUES_DATA } from '@/shared/_mock/_preparationUsager';

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_JOURS_ATTRIBUES_DATA);

  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) => 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) => 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>
  );
}
