'use client';

import * as React from 'react';
import { useFormikContext } from 'formik';
import { Box, Grid, Typography, Stack, Button, FormControl, FormHelperText } from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { RoadMapStyledTimePicker, StyledTextField } from '@/shared/theme/css';
import FontAwesome from '@/shared/components/fontawesome';
import { faClock, faNoteSticky } from '@fortawesome/free-solid-svg-icons';
import { pxToRem } from '@/shared/theme/typography';
import { fr } from 'date-fns/locale';
import { Dayjs } from 'dayjs';

interface VisitFormValues {
  garageStart: string;
  garageEnd: string;
  medicalStart: string;
  medicalEnd: string;
  observation: string;
}

interface VisitSectionProps {
  isEditMode: boolean;
}

const stringToTime = (str: string): Date | null => {
  if (!str) return null;
  const [h, m] = str.split(':').map(Number);
  const d = new Date();
  d.setHours(h || 0, m || 0, 0, 0);
  return d;
};

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

const VisitSection: React.FC<VisitSectionProps> = ({ isEditMode }) => {
  const { values, setFieldValue, handleBlur, errors, touched } =
    useFormikContext<VisitFormValues>();
  const [garageEndError, setGarageEndError] = React.useState('');
  const [medicalEndError, setMedicalEndError] = React.useState('');

  // Validation à chaque changement
  const validateTime = (
    start: string,
    end: string,
    setError: React.Dispatch<React.SetStateAction<string>>,
    label: string
  ) => {
    if (!start || !end) {
      setError('');
      return;
    }
    if (end <= start) {
      setError(`L'heure de fin ${label} doit être supérieure à l'heure de début.`);
    } else {
      setError('');
    }
  };
  const handleGarageStartChange = (val: Date | Dayjs | null) => {
    if (!val) return;
    const dateVal = val instanceof Date ? val : val.toDate();
    const newVal = dateToHHmm(dateVal);
    setFieldValue('garageStart', newVal);
    validateTime(newVal, values.garageEnd, setGarageEndError, 'de la visite garage');
  };
  const handleGarageEndChange = (val: Date | Dayjs | null) => {
    if (!val) return;
    const dateVal = val instanceof Date ? val : val.toDate();
    const newVal = dateToHHmm(dateVal);
    setFieldValue('garageEnd', newVal);
    validateTime(values.garageStart, newVal, setGarageEndError, 'de la visite garage');
  };

  const handleMedicalStartChange = (val: Date | Dayjs | null) => {
    if (!val) return;
    const dateVal = val instanceof Date ? val : val.toDate();
    const newVal = dateToHHmm(dateVal);
    setFieldValue('medicalStart', newVal);
    validateTime(newVal, values.medicalEnd, setMedicalEndError, 'de la visite médicale');
  };

  const handleMedicalEndChange = (val: Date | Dayjs | null) => {
    if (!val) return;
    const dateVal = val instanceof Date ? val : val.toDate();
    const newVal = dateToHHmm(dateVal);
    setFieldValue('medicalEnd', newVal);
    validateTime(values.medicalStart, newVal, setMedicalEndError, 'de la visite médicale');
  };

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Typography
        variant="h5"
        sx={{
          color: 'primary.main',
          fontSize: pxToRem(22),
          fontWeight: (theme) => theme.typography.fontWeightBold,
          m: 3,
        }}
      >
        Autres trajets
      </Typography>

      <Box
        sx={{
          backgroundColor: 'white',
          borderRadius: 2,
          p: 3,
          boxShadow: 1,
        }}
      >
        <Grid container spacing={4}>
          {/* Garage */}
          <Grid item xs={6}>
            <Typography variant="h6">Visite garage</Typography>
            <Box mt={1}>
              <Stack direction="row" spacing={2}>
                <RoadMapStyledTimePicker
                  label="Début visite garage"
                  value={stringToTime(values.garageStart)}
                  onChange={handleGarageStartChange}
                  views={['hours', 'minutes']}
                  format="HH:mm"
                  slots={{
                    openPickerIcon: () => (
                      <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                    ),
                  }}
                  disabled={!isEditMode}
                />
                <FormControl error={Boolean(garageEndError)} fullWidth>
                  <RoadMapStyledTimePicker
                    label="Fin visite garage"
                    value={stringToTime(values.garageEnd)}
                    onChange={handleGarageEndChange}
                    views={['hours', 'minutes']}
                    format="HH:mm"
                    slots={{
                      openPickerIcon: () => (
                        <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                      ),
                    }}
                    disabled={!isEditMode}
                  />
                  {garageEndError && <FormHelperText>{garageEndError}</FormHelperText>}
                </FormControl>
              </Stack>
            </Box>
          </Grid>

          {/* Médicale */}
          <Grid item xs={6}>
            <Typography variant="h6">Visite médicale</Typography>
            <Box mt={1}>
              <Stack direction="row" spacing={2}>
                <RoadMapStyledTimePicker
                  label="Début visite médicale"
                  value={stringToTime(values.medicalStart)}
                  onChange={handleMedicalStartChange}
                  views={['hours', 'minutes']}
                  format="HH:mm"
                  slots={{
                    openPickerIcon: () => (
                      <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                    ),
                  }}
                  disabled={!isEditMode}
                />
                <FormControl error={Boolean(medicalEndError)} fullWidth>
                  <RoadMapStyledTimePicker
                    label="Fin visite médicale"
                    value={stringToTime(values.medicalEnd)}
                    onChange={handleMedicalEndChange}
                    views={['hours', 'minutes']}
                    format="HH:mm"
                    slots={{
                      openPickerIcon: () => (
                        <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                      ),
                    }}
                    disabled={!isEditMode}
                  />
                  {medicalEndError && <FormHelperText>{medicalEndError}</FormHelperText>}
                </FormControl>
              </Stack>
            </Box>
          </Grid>
        </Grid>
      </Box>

      {/* Observation */}
      <Typography
        variant="h5"
        sx={{
          color: 'primary.main',
          fontSize: pxToRem(22),
          fontWeight: (theme) => theme.typography.fontWeightBold,
          m: 3,
        }}
      >
        Observation
      </Typography>

      <Box
        sx={{
          backgroundColor: 'white',
          borderRadius: 2,
          p: 3,
          boxShadow: 1,
          mb: 5,
        }}
      >
        <StyledTextField
          fullWidth
          multiline
          label="Observations"
          placeholder="Saisissez vos observations"
          name="observation"
          value={values.observation}
          onChange={(e) => setFieldValue('observation', e.target.value)}
          onBlur={handleBlur}
          error={touched.observation && Boolean(errors.observation)}
          helperText={touched.observation ? errors.observation : ''}
          InputLabelProps={{
            shrink: true,
          }}
          InputProps={{
            endAdornment: <FontAwesome icon={faNoteSticky} sx={{ color: 'primary.main' }} />,
          }}
          disabled={!isEditMode}
        />
      </Box>
    </LocalizationProvider>
  );
};
export default VisitSection;
