'use client';

import React, { useEffect, useState } from 'react';
import {
  DialogTitle,
  DialogContent,
  DialogActions,
  Stack,
  IconButton,
  Typography,
  Box,
  Checkbox,
  ListItemText,
  MenuItem,
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import {
  dialogTitleStyles,
  dialogTitleTextStyles,
  StyledDatePicker,
  StyledTextField,
} from '@/shared/theme/css';
import dayjs, { Dayjs } from 'dayjs';
import DriverSelector from './add-roadmap/driver-selector';
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 DepartmentSelectorAutocomplete from './add-roadmap/department-selector';

type NewRoadmapDialogProps = {
  open: boolean;
  onClose: () => void;
  onSend: (data: { driver: IActiveDriver[]; startDate: Dayjs | Date | null }) => void;
};
export interface ManualRoadMapCreationResult {
  createdDriverIds: number[];
  existingDriverIds: { id: number; name: string }[];
}

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 { createValidatedRoadMapsManually } = useRoadMapStore();

  const formik = useFormik({
    initialValues,
    validationSchema,
    onSubmit: async (values) => {
      try {
        const result: ManualRoadMapCreationResult = await createValidatedRoadMapsManually({
          driverIds: values.selectedDrivers.map((driver) => driver.id),
          date: dayjs(values.startDate).format('YYYY-MM-DD'),
        });

        const { createdDriverIds, existingDriverIds } = result;

        if (createdDriverIds.length > 0) {
          enqueueSnackbar(
            `Feuilles de route créées avec succès pour ${createdDriverIds.length} chauffeur(s).`,
            {
              variant: 'success',
            }
          );
        }

        if (existingDriverIds.length > 0) {
          const names = existingDriverIds.map((d: { name: string }) => d.name).join(', ');
          enqueueSnackbar(
            `Les chauffeurs suivants ont déjà une feuille pour le mois choisi : ${names}`,
            {
              variant: 'error',
            }
          );
        }

        if (createdDriverIds.length > 0) {
          onSend?.({
            driver: values.selectedDrivers,
            startDate: values.startDate,
          });
          handleClose();
        }
      } catch (error) {
        enqueueSnackbar('Erreur lors de la création des feuilles de route.', { variant: 'error' });
        console.error(error);
      }
    },
  });

  const [activeDrivers, setActiveDrivers] = useState<IActiveDriver[]>([]);
  const [selectedDepartments, setSelectedDepartments] = useState<string[]>([]);
  const [filteredDrivers, setFilteredDrivers] = useState<IActiveDriver[]>([]);
  const [departments, setDepartments] = useState<string[]>([]);
  const handleClose = () => {
    formik.resetForm();
    setSelectedDepartments([]);
    setFilteredDrivers([]);
    onClose();
  };

  const { getActiveDrivers } = useDriverStore();

  useEffect(() => {
    if (open) {
      getActiveDrivers().then((drivers) => {
        setActiveDrivers(drivers);
        const uniqueDepartments = Array.from(new Set(drivers.map((d) => d.departmentName)));
        setDepartments(uniqueDepartments);
      });
    }
  }, [open]);

  useEffect(() => {
    if (selectedDepartments.length > 0) {
      const driversFromDept = activeDrivers.filter((d) =>
        selectedDepartments.includes(d.departmentName)
      );

      if (formik.values.selectedDrivers.length === 0) {
        setFilteredDrivers(driversFromDept);
        formik.setFieldValue('selectedDrivers', driversFromDept);
      } else {
        const currentSelected = formik.values.selectedDrivers;

        const selectedIds = new Set(currentSelected.map((d) => d.id));

        const driversToAdd = driversFromDept.filter((d) => !selectedIds.has(d.id));

        const newSelectedDrivers = [...currentSelected, ...driversToAdd];

        setFilteredDrivers(driversFromDept);
        formik.setFieldValue('selectedDrivers', newSelectedDrivers);
      }
    } else {
      setFilteredDrivers(activeDrivers);
      formik.setFieldValue('selectedDrivers', []);
    }
  }, [selectedDepartments, activeDrivers]);

  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={handleClose} 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']}
                slots={{
                  openPickerIcon: () => <CustomDateIcon />,
                }}
                openTo="year"
                value={formik.values.startDate}
                onChange={(value) => formik.setFieldValue('startDate', value)}
                slotProps={{
                  textField: (params: any) => ({
                    ...params,
                    fullWidth: true,
                    placeholder: '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>
            <DepartmentSelectorAutocomplete
              departments={departments}
              selectedDepartments={selectedDepartments}
              setSelectedDepartments={setSelectedDepartments}
            />

            <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={handleClose}
            secoundButtonText="Créer"
          />
        </DialogActions>
      </form>
    </StyledDialog>
  );
}
