'use client';

import React, { useEffect } from 'react';
import { Grid, Box, Typography, FormHelperText, FormControl } from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { faClock } from '@fortawesome/free-solid-svg-icons';
import { RoadMapStyledTimePicker } from '@/shared/theme/css';
import { useFormikContext } from 'formik';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { pxToRem } from '@/shared/theme/typography';
import { AntSwitch } from '@/shared/components/table/styles';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { useTheme } from '@mui/material/styles';
import { fr } from 'date-fns/locale';

type RoadType = 'MATIN' | 'MIDI' | 'APRES_MIDI' | 'SOIR';

interface FormikValues {
  roads: {
    [key in RoadType]?: {
      startHour: string;
      endHour: string;
      disabled?: boolean;
    };
  };
}
interface RoadMapTimePickerProps {
  isEditMode: boolean;
}

const roadTypeLabelMap: Record<RoadType, string> = {
  MATIN: 'Matin',
  MIDI: 'Midi',
  APRES_MIDI: 'Après-midi',
  SOIR: 'Soir',
};

const stringToDate = (time: string): Date => {
  const [hours, minutes] = time.split(':');
  const date = new Date();
  date.setHours(parseInt(hours, 10));
  date.setMinutes(parseInt(minutes, 10));
  date.setSeconds(0);
  return date;
};

const dateToString = (date: Date | null): string => {
  if (!date) return '';
  return date.toTimeString().slice(0, 5);
};

const TimePickerSection: React.FC<{ label: RoadType; isEditMode: boolean }> = ({
  label,
  isEditMode,
}) => {
  const theme = useTheme();
  const { values, setFieldValue } = useFormikContext<FormikValues>();
  const data = values.roads?.[label] ?? { startHour: '', endHour: '', disabled: true };

  const handleTimeChange = (field: 'startHour' | 'endHour', val: Date | null) => {
    if (!val) return;
    const timeStr = dateToString(val);
    setFieldValue(`roads.${label}.${field}`, timeStr);
    const otherField = field === 'startHour' ? 'endHour' : 'startHour';
    const otherTime = values.roads?.[label]?.[otherField] || '';
    const currentStart = field === 'startHour' ? timeStr : values.roads?.[label]?.startHour;
    const currentEnd = field === 'endHour' ? timeStr : values.roads?.[label]?.endHour;

    if (currentStart && currentEnd) {
      const [sh, sm] = currentStart.split(':').map(Number);
      const [eh, em] = currentEnd.split(':').map(Number);
      const startMinutes = sh * 60 + sm;
      const endMinutes = eh * 60 + em;
      if (endMinutes <= startMinutes) {
        setEndHourError("L'heure de fin doit être supérieure l'heure de début.");
      } else {
        setEndHourError('');
      }
    } else {
      setEndHourError('');
    }
  };

  const handleToggle = (checked: boolean) => {
    setFieldValue(`roads.${label}.disabled`, !checked);
  };

  const active = !data.disabled;
  const [endHourError, setEndHourError] = React.useState('');
  return (
    <Grid item xs={12} sm={3}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
        <Typography sx={{ fontWeight: 'bold' }}> {roadTypeLabelMap[label]}</Typography>
        <CustomTooltip
          title={
            active
              ? `Désactiver le trajet ${roadTypeLabelMap[label].toLowerCase()}`
              : `Activer le trajet ${roadTypeLabelMap[label].toLowerCase()}`
          }
          arrow
        >
          <AntSwitch
            theme={theme}
            checked={active}
            onChange={(event) => handleToggle(event.target.checked)}
            size="small"
            disabled={!isEditMode}
          />
        </CustomTooltip>
      </Box>

      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <RoadMapStyledTimePicker
          label={`Départ ${roadTypeLabelMap[label].toLowerCase()}`}
          value={data.startHour ? stringToDate(data.startHour) : null}
          onChange={(val) => handleTimeChange('startHour', val as Date)}
          format="HH:mm"
          views={['hours', 'minutes']}
          slots={{
            openPickerIcon: () => <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />,
          }}
          disabled={!active || !isEditMode}
        />
        <FormControl error={Boolean(endHourError)} fullWidth>
          <RoadMapStyledTimePicker
            label={`Fin ${roadTypeLabelMap[label].toLowerCase()}`}
            value={data.endHour ? stringToDate(data.endHour) : null}
            onChange={(val) => handleTimeChange('endHour', val as Date)}
            format="HH:mm"
            views={['hours', 'minutes']}
            slots={{
              openPickerIcon: () => <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />,
            }}
            disabled={!active || !isEditMode}
          />
          {endHourError && <FormHelperText>{endHourError}</FormHelperText>}
        </FormControl>
      </Box>
    </Grid>
  );
};

const RoadMapTimePickerComponent: React.FC<RoadMapTimePickerProps> = ({ isEditMode }) => {
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Typography
        variant="h5"
        sx={{
          color: 'primary.main',
          fontSize: pxToRem(22),
          fontWeight: (theme) => theme.typography.fontWeightBold,
          mt:0,
          mb: 7,
        }}
      >
        Suivie des heures
      </Typography>

      <Box
        sx={{
          backgroundColor: 'white',
          borderRadius: 2,
          boxShadow: 1,
        }}
      >
        <Grid container spacing={4} sx={{ p: 3 }}>
          <TimePickerSection label="MATIN" isEditMode={isEditMode} />
          <TimePickerSection label="MIDI" isEditMode={isEditMode} />
          <TimePickerSection label="APRES_MIDI" isEditMode={isEditMode} />
          <TimePickerSection label="SOIR" isEditMode={isEditMode} />
        </Grid>
      </Box>
    </LocalizationProvider>
  );
};

export default RoadMapTimePickerComponent;
