'use client';

import React, { useEffect, useState } from 'react';
import {
  DialogTitle,
  DialogContent,
  DialogActions,
  Stack,
  IconButton,
  Typography,
  Box,
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import { dialogTitleStyles, dialogTitleTextStyles, StyledDatePicker } from '@/shared/theme/css';
import dayjs, { Dayjs } from 'dayjs';
import { IActiveDriver, IDriver } from '@/shared/types/driver';
import { StyledDialog } from '@/shared/sections/rh/styles';
import ActionButtons from '@/shared/components/form/buttons-action';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import CloseIcon from '@mui/icons-material/Close';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import { enqueueSnackbar } from 'notistack';
import DriverSelector from '../roadmap-list/add-roadmap/driver-selector';

type NewRoadmapDialogProps = {
  open: boolean;
  onClose: () => void;
  onSend: (data: { driver: IActiveDriver[]; startDate: Dayjs | Date | null }) => void;
};

const validationSchema = Yup.object().shape({
  startDate: Yup.date().nullable().required('La date est requise'),
  selectedDrivers: Yup.array()
    .of(Yup.object())
    .min(1, 'Au moins un chauffeur doit être sélectionné')
    .required('La sélection des chauffeurs est requise'),
});

export default function NewRoadmapDialog({ open, onClose, onSend }: NewRoadmapDialogProps) {
  const initialValues = {
    startDate: null as Dayjs | Date | null,
    selectedDrivers: [] as IActiveDriver[],
  };
  const { createRoadMapsManually } = useRoadMapStore();

  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit: async (values) => {
      try { 
        await createRoadMapsManually({
          driverIds: values.selectedDrivers.map((driver) => driver.id),
          date: dayjs(values.startDate).format('YYYY-MM-DD'),
        });
        enqueueSnackbar('Feuilles de route créées avec succès.', { variant: 'success' });

        onSend?.({
          driver: values.selectedDrivers,
          startDate: values.startDate,
        });
        onClose();
      } catch (error) {
        enqueueSnackbar('Erreur lors de la création des feuilles de route.', { variant: 'error' });
        console.log('error');
      }
    },
  });
  const [activeDrivers, setActiveDrivers] = useState<IActiveDriver[]>([]);
  const { getActiveDrivers } = useDriverStore();

  useEffect(() => {
    if (open) {
      getActiveDrivers().then(setActiveDrivers);
    }
  }, [open]);

  return (
    <StyledDialog open={open} fullWidth maxWidth="sm">
      <DialogTitle sx={(theme) => dialogTitleStyles(theme)}>
        <Typography sx={dialogTitleTextStyles}>Nouvelle feuille de route</Typography>
        <IconButton aria-label="close" onClick={onClose} size="small" sx={{ color: 'white' }}>
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <form onSubmit={formik.handleSubmit}>
        <DialogContent>
          <Stack spacing={3} mt={3}>
            <LocalizationProvider
              dateAdapter={AdapterDateFns}
              adapterLocale={fr}
              localeText={{
                clearButtonLabel: 'Effacer',
                todayButtonLabel: "Aujourd'hui",
                cancelButtonLabel: 'Annuler',
              }}
            >
              <StyledDatePicker
                label={'Date'}
                views={['year', 'month', 'day']}
                slots={{
                  openPickerIcon: () => <CustomDateIcon />,
                }}
                openTo="year"
                value={formik.values.startDate}
                onChange={(value) => formik.setFieldValue('startDate', value)}
                slotProps={{
                  textField: (params: any) => ({
                    ...params,
                    fullWidth: true,
                    placeholder: 'DD/MM/YYYY',
                    InputLabelProps: {
                      shrink: true,
                    },
                    error: formik.touched.startDate && Boolean(formik.errors.startDate),
                    helperText: formik.touched.startDate && formik.errors.startDate,
                  }),
                  actionBar: {
                    actions: ['clear', 'today'],
                  },
                }}
              />
            </LocalizationProvider>
            <Box>
              <DriverSelector
                drivers={activeDrivers}
                selectedDrivers={formik.values.selectedDrivers}
                setSelectedDrivers={(drivers) => formik.setFieldValue('selectedDrivers', drivers)}
              />
              <ConditionalComponent
                isValid={!!(formik.touched.selectedDrivers && formik.errors.selectedDrivers)}
              >
                <Typography sx={{ ml: 2 }} color="error" variant="caption">
                  {formik.errors.selectedDrivers as string}
                </Typography>
              </ConditionalComponent>
            </Box>
          </Stack>
        </DialogContent>
        <DialogActions>
          <ActionButtons
            onSave={formik.handleSubmit}
            onCancel={onClose}
            secoundButtonText="Créer"
          />
        </DialogActions>
      </form>
    </StyledDialog>
  );
}
