'use client';

import React, { useState } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  FormControl,
  Stack,
  Box,
  FormControlLabel,
  Radio,
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { StyledRadioGroup, StyledTextField } from '@/shared/theme/css';
import { CustomDateIcon } from '@/shared/components/form/form-field';
import { RoadMapStyledDatePicker, RoadMapStyledTimePicker } from '@/shared/theme/css';
import { Dayjs } from 'dayjs';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import { faClock } from '@fortawesome/free-solid-svg-icons';
import FontAwesome from '@/shared/components/fontawesome';
import DriverSelector from './driver-selector';
import { IDriver } from '@/shared/types/driver';
import { _drivers } from '@/shared/_mock/_drivers';
import { StyledDialog } from '@/shared/sections/rh/styles';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

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

export default function SendPlanningDialog({
  open,
  onClose,
  onSend,
  drivers,
}: SendPlanningDialogProps) {
  const [title, setTitle] = React.useState('');
  const [selectedDrivers, setSelectedDrivers] = useState<IDriver[]>([]);
  const [mode, setMode] = React.useState<'quotidienne' | 'hebdomadaire' | 'journee'>('quotidienne');
  const [startDate, setStartDate] = React.useState<Dayjs | Date | null>(null);
  const [endDate, setEndDate] = React.useState<Dayjs | Date | null>(null);
  const [schedule, setSchedule] = React.useState<string>('00:00 - 23:59');
  const handleSend = () => {
    onSend({ title, driver: selectedDrivers, startDate, endDate, schedule });
    onClose();
    setTitle('');
    setSelectedDrivers([]);
    setStartDate(null);
    setEndDate(null);
    setSchedule('');
  };

  const handleModeChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value as 'quotidienne' | 'hebdomadaire' | 'journee';
    setMode(value);
    setSchedule(value === 'quotidienne' ? '00:00 - 23:59' : '00:00');
    setStartDate(null);
    setEndDate(null);
  };
  const handleStartDateChange = (value: Dayjs | Date | null, context: any) => {
    setStartDate(value);
  };

  const handleEndDateChange = (value: Dayjs | Date | null, context: any) => {
    if (value instanceof Dayjs) {
      setEndDate(value);
    }
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullWidth
      maxWidth="sm"
      PaperProps={{
        sx: {
          borderRadius: 4,
          overflow: 'hidden',
        },
      }}
    >
      <Box sx={{ bgcolor: 'primary.main' }}>
        <DialogTitle sx={{ color: 'white' }}>Envoi de nouvelle feuille de route</DialogTitle>
      </Box>{' '}
      <DialogContent>
        <Stack spacing={2} mt={1}>
          <StyledTextField
            label="Titre d'envoi"
            fullWidth
            required
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
          <DriverSelector
            drivers={_drivers}
            selectedDrivers={selectedDrivers}
            setSelectedDrivers={setSelectedDrivers}
          />
          <FormControl fullWidth>
            <LocalizationProvider dateAdapter={AdapterDayjs}>
              <Box mb={2}>
                <StyledRadioGroup value={mode} onChange={handleModeChange}>
                  <FormControlLabel value="journee" control={<Radio />} label="Journée" />
                  <FormControlLabel value="quotidienne" control={<Radio />} label="Quotidienne" />
                  <FormControlLabel value="hebdomadaire" control={<Radio />} label="Hebdomadaire" />
                </StyledRadioGroup>

                <Stack direction="row" spacing={2} mt={2}>
                  <ConditionalComponent
                    isValid={mode === 'journee'}
                    defaultComponent={
                      <>
                        <RoadMapStyledDatePicker
                          value={startDate}
                          onChange={handleStartDateChange}
                          views={['year', 'month', 'day']}
                          slots={{ openPickerIcon: CustomDateIcon }}
                          openTo="day"
                          slotProps={{
                            textField: {
                              placeholder: 'Date de début',
                              InputLabelProps: { shrink: true },
                            },
                          }}
                        />
                        <RoadMapStyledDatePicker
                          value={endDate}
                          onChange={handleEndDateChange}
                          views={['year', 'month', 'day']}
                          slots={{ openPickerIcon: CustomDateIcon }}
                          openTo="day"
                          slotProps={{
                            textField: {
                              placeholder: 'Date de fin',
                              InputLabelProps: { shrink: true },
                            },
                          }}
                        />
                        <RoadMapStyledTimePicker
                          label="Sélectionner l'heure"
                          slots={{
                            openPickerIcon: () => (
                              <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                            ),
                          }}
                          slotProps={{
                            textField: {
                              placeholder: "Sélectionner l'heure",
                            },
                          }}
                          views={['hours', 'minutes']}
                          format="HH:mm"
                        />
                      </>
                    }
                  >
                    <>
                      <RoadMapStyledDatePicker
                        value={startDate}
                        onChange={handleStartDateChange}
                        views={['year', 'month', 'day']}
                        slots={{ openPickerIcon: CustomDateIcon }}
                        openTo="day"
                        slotProps={{
                          textField: {
                            placeholder: 'Date',
                            InputLabelProps: { shrink: true },
                          },
                        }}
                      />
                      <RoadMapStyledTimePicker
                        label="Sélectionner l'heure"
                        slots={{
                          openPickerIcon: () => (
                            <FontAwesome icon={faClock} sx={{ color: 'primary.main' }} />
                          ),
                        }}
                        slotProps={{
                          textField: {
                            placeholder: "Sélectionner l'heure",
                          },
                        }}
                        views={['hours', 'minutes']}
                        format="HH:mm"
                      />
                    </>
                  </ConditionalComponent>
                </Stack>
              </Box>
            </LocalizationProvider>
          </FormControl>
        </Stack>
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Annuler</Button>
        <Button variant="contained" onClick={handleSend}>
          Envoyer
        </Button>
      </DialogActions>
    </Dialog>
  );
}
