'use client';

import React 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 } from 'dayjs';
import DriverSelector from './add-roadmap/driver-selector';
import { 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';

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

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,
    drivers,
}: NewRoadmapDialogProps) {
    const initialValues = {
        startDate: null as Dayjs | Date | null,
        selectedDrivers: [] as IDriver[],
    };

    const formik = useFormik({
        initialValues,
        validationSchema,
        onSubmit: (values) => {
            onSend({ 
                driver: values.selectedDrivers, 
                startDate: values.startDate 
            });
            onClose();
        },
    });

    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={drivers}
                                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>
    );
}
