'use client';

import React, { useEffect, useState } from 'react';
import {
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions,
    Button,
    FormControl,
    Stack,
    Box,
    FormControlLabel,
    Radio,
    Typography,
    IconButton,
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { StyledRadioGroup, StyledTextField } from '@/shared/theme/css';

import dayjs, { Dayjs } from 'dayjs';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';
dayjs.extend(isSameOrAfter);

import { IActiveDriver, IActivePlanningDriver } from '@/shared/types/driver';
import { _drivers } from '@/shared/_mock/_drivers';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import * as Yup from 'yup';
import { useFormik } from 'formik';
import { enqueueSnackbar } from 'notistack';
import { useDriverStore } from '@/shared/api/stores/driverStore';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fr } from 'date-fns/locale';
import DriverSelector from '@/shared/sections/chauffeur/roadmap/components/roadmap-list/add-roadmap/driver-selector';
import ActionButtons from '@/shared/components/form/buttons-action';
import WeeklyFormSection from '@/shared/sections/chauffeur/roadmap/components/roadmap-list/add-roadmap/weekly-form-section';
import SingleDayFormSection from '@/shared/sections/chauffeur/roadmap/components/roadmap-list/add-roadmap/single-day-form-section';
import DailyFormSection from '@/shared/sections/chauffeur/roadmap/components/roadmap-list/add-roadmap/daily-form-section';
import CloseIcon from '@mui/icons-material/Close';
import DepartmentSelectorAutocomplete from '@/shared/sections/chauffeur/roadmap/components/roadmap-list/add-roadmap/department-selector';
import SingleDayFormPlanningSection from './single-day-form-planning-section';
import { SchedulePlanningPayload, SendRoadMapPlanningFormValues } from '@/shared/types/roadMap';


type SendPlanningDialogProps = {
    open: boolean;
    onClose: () => void;
    onSend: (data: any) => void;
    planningDriver: IActivePlanningDriver;
};

const validationSchema = Yup.object().shape({
    title: Yup.string().required('Le titre est requis'),
});

export default function SendDriverPlanningDialog({
    open,
    onClose,
    onSend,
    planningDriver
}: SendPlanningDialogProps) {
    const initialValues: SendRoadMapPlanningFormValues = {
        sendDate: null as Dayjs | Date | null,
        startDate: null as Dayjs | Date | null,
        selectedDrivers: [] as IActiveDriver[],
        title: '',
        endDate: null as Dayjs | Date | null,
        sendHour: null,
        planningDayOption: 'specific',
        planningDate: planningDriver.planningDay,
        dayOfWeek: 'Lundi',
        mode: 'journee',

    };

    const { schedulePlanning } = useRoadMapStore();
    const [activeDrivers, setActiveDrivers] = useState<IActiveDriver[]>([]);

    const formik = useFormik<SendRoadMapPlanningFormValues>({
        initialValues,
        validationSchema,
        onSubmit: async (values) => {
            const requestPayload: SchedulePlanningPayload = {
                type: "journee",
                title: values.title,
                sendDate: null,
                sendTime: dayjs().format('HH:mm:ss'),
                planningDayOption: 'specific',      
                planningDate: dayjs(planningDriver.planningDay).format('YYYY-MM-DD'),
               startDate: dayjs().format('YYYY-MM-DD'),
                endDate: null,                     
                dayOfWeek: null,                     
                driverIds: [planningDriver.id],
            };
            await schedulePlanning(requestPayload);
            onSend(requestPayload);
            handleCancel();
            enqueueSnackbar('Le planning a été programmé avec succès.', { variant: 'success' });
        },
    });

    const { getActiveDrivers } = useDriverStore();

    useEffect(() => {
        if (open) {
            getActiveDrivers().then((drivers) => {
                setActiveDrivers(drivers);
                formik.setFieldValue('selectedDrivers', drivers);
            });
        }
    }, [open]);

    const handleCancel = () => {
        formik.resetForm();
        onClose();
    };

    return (
        <Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
            <form onSubmit={formik.handleSubmit}>
                <Box sx={{ bgcolor: 'primary.main' }}>
                    <DialogTitle sx={{ color: 'white', position: 'relative' }}>
                        Envoi de nouvelle feuille de route
                        <IconButton
                            aria-label="close"
                            onClick={handleCancel}
                            sx={{ position: 'absolute', right: 8, top: 8, color: 'white' }}
                        >
                            <CloseIcon />
                        </IconButton>
                    </DialogTitle>
                </Box>
                <DialogContent>
                    <Stack spacing={2} mt={1}>
                        <StyledTextField
                            name="title"
                            label="Titre d'envoi"
                            fullWidth
                            required
                            value={formik.values.title}
                            onChange={formik.handleChange}
                            error={!!(formik.touched.title && formik.errors.title)}
                            helperText={formik.touched.title && formik.errors.title}
                        />
                        <SingleDayFormPlanningSection
                            formik={formik}
                            planningDay={planningDriver.planningDay}
                        />

                        <Box sx={{ p: 1.5, border: '1px solid', borderColor: 'divider', borderRadius: 2, backgroundColor: 'background.paper' }}>
                            <Typography variant="subtitle2" sx={{ fontWeight: 'bold', mb: 0.5 }}>
                                Département
                            </Typography>
                            <Typography variant="body1">{planningDriver.departmentName}</Typography>
                        </Box>

                        <Box sx={{ p: 1.5, border: '1px solid', borderColor: 'divider', borderRadius: 2, backgroundColor: 'background.paper' }}>
                            <Typography variant="subtitle2" sx={{ fontWeight: 'bold', mb: 0.5 }}>
                                Chauffeur
                            </Typography>
                            <Typography variant="body1">{planningDriver.name}</Typography>
                        </Box>
                    </Stack>
                </DialogContent>
                <DialogActions>
                    <ActionButtons onSave={formik.handleSubmit} onCancel={handleCancel} secoundButtonText="Envoyer" />
                </DialogActions>
            </form>
        </Dialog>
    );
}

