'use client';

import * as React from 'react';
import { useFormikContext } from 'formik';
import { Box, Grid, Typography, Stack, Button } 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';

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

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

export default function VisitSection() {
  const {
    values,
    setFieldValue,
    handleBlur,
    errors,
    touched,
  } = useFormikContext<VisitFormValues>();

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      <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={(val) => setFieldValue('garageStart', dateToHHmm(val as Date))}
                  views={['hours', 'minutes']}
                  format="HH:mm"
                  slots={{
                    openPickerIcon: () => (
                      <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                    ),
                  }}
                />
                <RoadMapStyledTimePicker
                  label="Fin visite garage"
                  value={stringToTime(values.garageEnd)}
                  onChange={(val) => setFieldValue('garageEnd', dateToHHmm(val as Date))}
                  views={['hours', 'minutes']}
                  format="HH:mm"
                  slots={{
                    openPickerIcon: () => (
                      <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                    ),
                  }}
                />
              </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={(val) => setFieldValue('medicalStart', dateToHHmm(val as Date))}
                  views={['hours', 'minutes']}
                  format="HH:mm"
                  slots={{
                    openPickerIcon: () => (
                      <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                    ),
                  }}
                />
                <RoadMapStyledTimePicker
                  label="Fin visite médicale"
                  value={stringToTime(values.medicalEnd)}
                  onChange={(val) => setFieldValue('medicalEnd', dateToHHmm(val as Date))}
                  views={['hours', 'minutes']}
                  format="HH:mm"
                  slots={{
                    openPickerIcon: () => (
                      <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                    ),
                  }}
                />
              </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' }} />,
          }}
        />
      </Box>

    </LocalizationProvider>
  );
}
