'use client';

import React from 'react';
import { Grid, Box, Typography } 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';

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

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


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 }> = ({ label }) => {
  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 handleToggle = (checked: boolean) => {
    setFieldValue(`roads.${label}.disabled`, !checked);
  };

  const active = !data.disabled;

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

      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <RoadMapStyledTimePicker
          label={`Départ ${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}
        />

        <RoadMapStyledTimePicker
          label={`Fin ${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}
        />
      </Box>
    </Grid>
  );
};

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

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

export default RoadMapTimePickerComponent;
