'use client';

import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  Grid,
  Typography,
  Box,
  Alert,
  Stack,
  Chip,
} from '@mui/material';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker';
import { fr } from 'date-fns/locale';
import { format, addDays, isWeekend, nextMonday, addWeeks } from 'date-fns';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { 
  faCalendarDays, 
  faClock, 
  faUser, 
  faMapMarkerAlt,
  faCheckCircle 
} from '@fortawesome/free-solid-svg-icons';
import { ICandidature } from '@/shared/types/candidature';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { useSnackbar } from 'notistack';

interface ScheduleRdvModalProps {
  open: boolean;
  onClose: () => void;
  candidature: ICandidature | null;
  onSchedule: (candidateId: string, rdvDateTime: string) => Promise<void>;
  useBackend?: boolean;
}

export default function ScheduleRdvModal({
  open,
  onClose,
  candidature,
  onSchedule,
  useBackend = false,
}: ScheduleRdvModalProps) {
  const { enqueueSnackbar } = useSnackbar();
  const [selectedDateTime, setSelectedDateTime] = useState<Date | null>(null);
  const [loading, setLoading] = useState(false);

  // Suggest next week Monday at 9 AM as default
  useEffect(() => {
    if (open && candidature) {
      const nextWeek = addWeeks(new Date(), 1);
      const defaultDate = nextMonday(nextWeek);
      defaultDate.setHours(9, 0, 0, 0);
      setSelectedDateTime(defaultDate);
    }
  }, [open, candidature]);

  const handleSchedule = async () => {
    if (!candidature || !selectedDateTime) {
      enqueueSnackbar('Veuillez sélectionner une date et heure', { variant: 'warning' });
      return;
    }

    setLoading(true);
    try {
      // Format date for backend (ISO string)
      const rdvDateTime = selectedDateTime.toISOString();
      
      await onSchedule(candidature.id, rdvDateTime);
      
      enqueueSnackbar(
        `RDV programmé pour ${candidature.prenom} ${candidature.nom} le ${format(selectedDateTime, 'dd/MM/yyyy à HH:mm')}`,
        { variant: 'success' }
      );
      
      onClose();
    } catch (error: any) {
      console.error('Error scheduling RDV:', error);
      const message = error.response?.data?.message || 'Erreur lors de la programmation du RDV';
      enqueueSnackbar(message, { variant: 'error' });
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    if (!loading) {
      setSelectedDateTime(null);
      onClose();
    }
  };

  const isValidDate = (date: Date) => {
    const now = new Date();
    const minDate = new Date();
    minDate.setHours(0, 0, 0, 0);
    
    // Allow booking from today, but suggest future dates
    return date >= minDate;
  };

  const getWeekPeriod = () => {
    if (!selectedDateTime) return '';
    
    const startOfWeek = new Date(selectedDateTime);
    startOfWeek.setDate(selectedDateTime.getDate() - selectedDateTime.getDay() + 1); // Monday
    const endOfWeek = new Date(startOfWeek);
    endOfWeek.setDate(startOfWeek.getDate() + 4); // Friday
    
    return `Semaine du ${format(startOfWeek, 'dd MMM', { locale: fr })} au ${format(endOfWeek, 'dd MMM yyyy', { locale: fr })}`;
  };

  const getQuickDateOptions = () => {
    const options = [];
    const today = new Date();
    
    // Next Monday 9 AM
    const nextMon = nextMonday(today);
    nextMon.setHours(9, 0, 0, 0);
    options.push({ label: 'Lundi prochain 9h', date: new Date(nextMon) });
    
    // Next Tuesday 9 AM
    const nextTue = new Date(nextMon);
    nextTue.setDate(nextMon.getDate() + 1);
    options.push({ label: 'Mardi prochain 9h', date: new Date(nextTue) });
    
    // Next Wednesday 14h
    const nextWed = new Date(nextMon);
    nextWed.setDate(nextMon.getDate() + 2);
    nextWed.setHours(14, 0, 0, 0);
    options.push({ label: 'Mercredi prochain 14h', date: new Date(nextWed) });
    
    // Next Thursday 10h
    const nextThu = new Date(nextMon);
    nextThu.setDate(nextMon.getDate() + 3);
    nextThu.setHours(10, 0, 0, 0);
    options.push({ label: 'Jeudi prochain 10h', date: new Date(nextThu) });
    
    return options;
  };

  if (!candidature) {
    return null;
  }

  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Dialog 
        open={open} 
        onClose={handleClose}
        maxWidth="md"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: 2,
            boxShadow: '0px 8px 32px rgba(0, 0, 0, 0.12)',
          }
        }}
      >
        <DialogTitle>
          <Box display="flex" alignItems="center" gap={2}>
            <FontAwesomeIcon icon={faCalendarDays} color="#1976d2" />
            <Box>
              <Typography variant="h6" component="div">
                Programmer un RDV
              </Typography>
              <Typography variant="body2" color="text.secondary">
                Planifier un rendez-vous pour la semaine prochaine
              </Typography>
            </Box>
          </Box>
        </DialogTitle>

        <DialogContent>
          <Grid container spacing={3}>
            {/* Candidate Information */}
            <Grid item xs={12}>
              <Box
                sx={{
                  p: 2,
                  bgcolor: 'primary.lighter',
                  borderRadius: 1,
                  border: '1px solid',
                  borderColor: 'primary.light',
                }}
              >
                <Stack direction="row" spacing={2} alignItems="center">
                  <FontAwesomeIcon icon={faUser} color="#1976d2" />
                  <Box>
                    <Typography variant="h6" color="primary.main">
                      {candidature.prenom} {candidature.nom}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {candidature.email} • {candidature.telephone}
                    </Typography>
                    <Box display="flex" alignItems="center" gap={1} mt={0.5}>
                      <FontAwesomeIcon icon={faMapMarkerAlt} size="sm" />
                      <Typography variant="body2">
                        {candidature.ville} ({candidature.codePostal})
                      </Typography>
                      <Chip 
                        label={candidature.statut} 
                        size="small" 
                        color="primary"
                        variant="outlined"
                      />
                    </Box>
                  </Box>
                </Stack>
              </Box>
            </Grid>

            {/* Quick Date Selection */}
            <Grid item xs={12}>
              <Typography variant="subtitle2" gutterBottom>
                <FontAwesomeIcon icon={faClock} style={{ marginRight: 8 }} />
                Créneaux suggérés
              </Typography>
              <Stack direction="row" spacing={1} flexWrap="wrap" gap={1}>
                {getQuickDateOptions().map((option, index) => (
                  <Button
                    key={index}
                    variant={selectedDateTime?.getTime() === option.date.getTime() ? "contained" : "outlined"}
                    size="small"
                    onClick={() => setSelectedDateTime(option.date)}
                    sx={{ 
                      borderRadius: 1,
                      textTransform: 'none',
                    }}
                  >
                    {option.label}
                  </Button>
                ))}
              </Stack>
            </Grid>

            {/* Custom Date/Time Picker */}
            <Grid item xs={12}>
              <Typography variant="subtitle2" gutterBottom>
                Ou choisir une date/heure personnalisée
              </Typography>
              <DateTimePicker
                label="Date et heure du RDV"
                value={selectedDateTime}
                onChange={(newValue) => {
                  if (newValue) {
                    // Limite les heures entre 8h et 18h
                    const adjustedDate = new Date(newValue);
                    if (adjustedDate.getHours() < 8) {
                      adjustedDate.setHours(8, 0, 0, 0);
                    } else if (adjustedDate.getHours() >= 18) {
                      adjustedDate.setHours(18, 0, 0, 0);
                    }
                    setSelectedDateTime(adjustedDate);
                  } else {
                    setSelectedDateTime(newValue);
                  }
                }}
                shouldDisableDate={(date) => !isValidDate(date)}
                shouldDisableTime={(value, view) => {
                  if (view === 'hours' && value instanceof Date && !isNaN(value.getTime())) {
                    const hour = value.getHours();
                    return hour < 8 || hour > 18;
                  }
                  return false;
                }}
                minDateTime={new Date()}
                ampm={false}
                format="dd/MM/yyyy HH:mm"
                slotProps={{
                  textField: {
                    fullWidth: true,
                    variant: 'outlined',
                    placeholder: "jj/mm/aaaa hh:mm",
                    inputProps: {
                      inputMode: 'numeric',
                      pattern: '[0-9/:]*'
                    },
                    helperText: "Saisie directe possible • Heures : 8h00 - 18h00",
                  },
                  field: {
                    readOnly: false,
                    clearable: true
                  },
                  actionBar: {
                    actions: ['clear', 'today', 'accept']
                  }
                }}
              />
            </Grid>

            {/* Week Period Display */}
            {selectedDateTime && (
              <Grid item xs={12}>
                <Alert 
                  severity="info" 
                  icon={<FontAwesomeIcon icon={faCalendarDays} />}
                  sx={{ borderRadius: 1 }}
                >
                  <Typography variant="body2">
                    <strong>RDV programmé pour :</strong><br />
                    {format(selectedDateTime, 'dd/MM/yyyy à HH:mm')}
                  </Typography>
                  <Typography variant="caption" display="block" mt={0.5}>
                    {getWeekPeriod()}
                  </Typography>
                </Alert>
              </Grid>
            )}

            {/* Warning for weekends */}
            {selectedDateTime && isWeekend(selectedDateTime) && (
              <Grid item xs={12}>
                <Alert severity="warning">
                  <Typography variant="body2">
                    Attention : Le RDV est programmé un weekend. 
                    Assurez-vous que l&apos;agence est ouverte.
                  </Typography>
                </Alert>
              </Grid>
            )}
          </Grid>
        </DialogContent>

        <DialogActions sx={{ p: 3, gap: 1 }}>
          <Button 
            onClick={handleClose} 
            variant="outlined"
            disabled={loading}
          >
            Annuler
          </Button>
          <Button
            onClick={handleSchedule}
            variant="contained"
            disabled={!selectedDateTime || loading}
            startIcon={
              loading ? undefined : <FontAwesomeIcon icon={faCheckCircle} />
            }
            sx={{
              minWidth: 140,
              borderRadius: 1,
            }}
          >
            {loading ? 'Programmation...' : 'Programmer RDV'}
          </Button>
        </DialogActions>
      </Dialog>
    </LocalizationProvider>
  );
}
