'use client';

import React from 'react';
import {
  Box,
  Button,
  Stack,
  Typography,
  Dialog,
  DialogTitle,
  DialogContent,
  IconButton,
  useTheme,
  DialogActions,
  Chip,
  Divider,
  Paper,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  SelectChangeEvent
} from '@mui/material';
import FullCalendar from '@fullcalendar/react';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin from '@fullcalendar/interaction';
import frLocale from '@fullcalendar/core/locales/fr';
import {
  faChevronLeft,
  faEye,
  faDownload,
  faPrint,
  faTimes,
  faCalendar,
  faFileExport
} from '@fortawesome/free-solid-svg-icons';
import { IRHAbsence } from '@/shared/types/absence-rh';
import FontAwesome from '@/shared/components/fontawesome';
import { StyledDialog, StyledDialogTitleGrey } from '../../styles';
import { RoadMapStyledSelect, StyledMenuItem, WhiteIconButtonStyle } from '@/shared/theme/css';
import ExportButton from '@/shared/components/table/table-export-button';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { DriverAbsenceStatus } from '@/shared/types/driver-absence';

interface AbsenceCalendarProps {
  open: boolean;
  onClose: () => void;
  absences: IRHAbsence[];
  onViewAbsence: (absence: IRHAbsence) => void;
}

const STATUS_OPTIONS = [
  { value: 'all', label: 'Tous les statuts' },
  { value: 'validated', label: 'Validé' },
  { value: 'rejected', label: 'Refusé' },
  { value: 'pending', label: 'En attente' },
];


export default function AbsenceCalendar({ open, onClose, absences, onViewAbsence }: AbsenceCalendarProps) {
  const theme = useTheme();
  const [selectedDate, setSelectedDate] = React.useState<Date | null>(null);
  const [selectedDateAbsences, setSelectedDateAbsences] = React.useState<IRHAbsence[]>([]);
  const [calendarView, setCalendarView] = React.useState<'calendar' | 'details'>('calendar');
  const [statusFilter, setStatusFilter] = React.useState<string>('all');

  const handleStatusFilterChange = (v: string) => {
    setStatusFilter(v);
  };

  const handleCloseCalendar = () => {
    onClose();
    setSelectedDate(null);
    setSelectedDateAbsences([]);
    setCalendarView('calendar');
    setStatusFilter('all');
  };

  // Filter absences based on status filter
  const filteredCalendarAbsences = React.useMemo(() => {
    if (statusFilter === 'all') return absences;
    return absences.filter(absence => {
      switch (statusFilter) {
        case 'validated':
          return absence.statut === DriverAbsenceStatus.Valide;
        case 'rejected':
          return absence.statut === DriverAbsenceStatus.Rejete;
        case 'pending':
          return absence.statut === DriverAbsenceStatus.EnCours || absence.statut === DriverAbsenceStatus.NonTraite;
        default:
          return true;
      }
    });
  }, [absences, statusFilter]);

  // Count absences per day for visual indicators
  const absencesCountByDay = React.useMemo(() => {
    const countMap: Record<string, number> = {};

    filteredCalendarAbsences.forEach(absence => {
      const startDate = new Date(absence.dateDebut);
      const endDate = new Date(absence.dateFin);

      for (let date = new Date(startDate); date <= endDate; date.setDate(date.getDate() + 1)) {
        const dateStr = date.toISOString().split('T')[0];
        countMap[dateStr] = (countMap[dateStr] || 0) + 1;
      }
    });

    return countMap;
  }, [filteredCalendarAbsences]);

  // Convert absences to calendar events
  const calendarEvents = React.useMemo(() => {
    return filteredCalendarAbsences.map(absence => {
      let backgroundColor, textColor = '#fff', borderColor;

      switch (absence.statut) {
        case DriverAbsenceStatus.Valide:
          backgroundColor = theme.palette.success.light;
          borderColor = theme.palette.success.main;
          textColor = theme.palette.success.darker;
          break;
        case DriverAbsenceStatus.Rejete:
          backgroundColor = theme.palette.error.lighter;
          borderColor = theme.palette.error.main;
          textColor = theme.palette.error.darker;
          break;
        case DriverAbsenceStatus.EnCours:
          backgroundColor = theme.palette.warning.lighter;
          borderColor = theme.palette.warning.main;
          textColor = theme.palette.warning.darker;
          break;
        case DriverAbsenceStatus.NonTraite:
          backgroundColor = theme.palette.info.lighter;
          borderColor = theme.palette.info.main;
          textColor = theme.palette.info.darker;
          break;
        default:
          backgroundColor = theme.palette.primary.lighter;
          borderColor = theme.palette.primary.main;
          textColor = theme.palette.primary.main;
      }

      return {
        id: absence.id,
        title: `${absence.nomChauffeur} - ${absence.typeAbsence}`,
        start: absence.dateDebut,
        end: absence.dateFin,
        backgroundColor,
        borderColor,
        textColor,
        extendedProps: {
          absence
        }
      };
    });
  }, [filteredCalendarAbsences, theme]);

  // Add special indicators for days with multiple absences
  const dayCellDidMount = React.useCallback((arg: any) => {
    const dateStr = arg.date.toISOString().split('T')[0];
    const count = absencesCountByDay[dateStr] || 0;

    if (count > 0) {
      const dayNumberElement = arg.el.querySelector('.fc-daygrid-day-number');
      const indicator = document.createElement('div');
      indicator.className = 'multiple-absences-indicator';
      indicator.innerHTML = `<span>${count}</span>`;
      indicator.style.position = 'absolute';
      indicator.style.top = '-4px';
      indicator.style.right = '-4px';
      indicator.style.backgroundColor = count > 2 ? theme.palette.error.main : theme.palette.primary.main;
      indicator.style.color = 'white';
      indicator.style.borderRadius = '50%';
      indicator.style.width = '20px';
      indicator.style.height = '20px';
      indicator.style.display = 'flex';
      indicator.style.alignItems = 'center';
      indicator.style.justifyContent = 'center';
      indicator.style.fontSize = '10px';
      indicator.style.fontWeight = 'bold';
      indicator.style.boxShadow = '0 2px 4px rgba(0,0,0,0.2)';
      indicator.style.zIndex = '1';

      if (dayNumberElement) {
        dayNumberElement.style.position = 'relative';
        dayNumberElement.style.display = 'inline-block';
        dayNumberElement.style.zIndex = '0';
        dayNumberElement.appendChild(indicator);
      } else {
        arg.el.appendChild(indicator);
        arg.el.style.position = 'relative';
      }
    }
  }, [absencesCountByDay, theme]);

  // Handle date click in calendar
  const handleDateClick = (info: any) => {
    const clickedDate = new Date(info.dateStr);
    setSelectedDate(clickedDate);
    setCalendarView('details');

    const absencesForDate = filteredCalendarAbsences.filter(absence => {
      const startDate = new Date(absence.dateDebut);
      const endDate = new Date(absence.dateFin);
      return clickedDate >= startDate && clickedDate <= endDate;
    });

    setSelectedDateAbsences(absencesForDate);
  };

  const getStatusChip = (status: string) => {
    switch (status) {
      case 'Validé':
        return <Chip
          label="Validé"
          size="small"
          sx={{
            bgcolor: theme.palette.success.lighter,
            color: theme.palette.success.darker,
            fontWeight: 'medium',
            border: `1px solid ${theme.palette.success.main}`
          }}
        />;
      case 'Refusé':
        return <Chip
          label="Refusé"
          size="small"
          sx={{
            bgcolor: theme.palette.error.lighter,
            color: theme.palette.error.darker,
            fontWeight: 'medium',
            border: `1px solid ${theme.palette.error.main}`
          }}
        />;
      case 'En cours':
        return <Chip
          label="En cours"
          size="small"
          sx={{
            bgcolor: theme.palette.warning.lighter,
            color: theme.palette.warning.darker,
            fontWeight: 'medium',
            border: `1px solid ${theme.palette.warning.main}`
          }}
        />;
      case 'Non traité':
        return <Chip
          label="Non traité"
          size="small"
          sx={{
            bgcolor: theme.palette.info.lighter,
            color: theme.palette.info.darker,
            fontWeight: 'medium',
            border: `1px solid ${theme.palette.info.main}`
          }}
        />;
      default:
        return <Chip
          label={status}
          size="small"
          sx={{
            bgcolor: theme.palette.grey[200],
            color: theme.palette.grey[800],
            fontWeight: 'medium'
          }}
        />;
    }
  };

  return (
    <StyledDialog
      open={open}
      onClose={handleCloseCalendar}
      maxWidth="xl"
      fullWidth
    >
      <StyledDialogTitleGrey >
        <Stack direction="row" alignItems="center" spacing={1}>
          <FontAwesome icon={faCalendar} width={18} />
          <Typography variant="h6" component="div">
            {calendarView === 'calendar'
              ? 'Calendrier global des absences des chauffeurs'
              : `Absences du ${selectedDate?.toLocaleDateString('fr-FR')}`
            }
          </Typography>
          {calendarView === 'details' ? (
            <Chip
              label={`${selectedDateAbsences.length} absence(s)`}
              size="small"
              sx={{
                ml: 1,
                bgcolor: theme.palette.primary.lighter,
                color: theme.palette.primary.darker,
                fontWeight: 'medium'
              }}
            />
          ) : <></>}
        </Stack>
        <IconButton
          edge="end"
          color="inherit"
          onClick={handleCloseCalendar}
          aria-label="close"
          sx={{ color: theme.palette.grey[500] }}
        >
          <FontAwesome icon={faTimes} width={16} />
        </IconButton>
      </StyledDialogTitleGrey>

      {calendarView === 'calendar' ? (
        <Box sx={{
          px: 2,
          py: 1,
          borderBottom: `1px solid ${theme.palette.divider}`,
          bgcolor: 'primary.lighter'
        }}>
          <Stack
            direction={{ xs: 'column', sm: 'row' }}
            spacing={2}
            alignItems={{ xs: 'flex-start', sm: 'center' }}
            justifyContent="space-between"
          >
            <Typography variant="body2" color="text.secondary">
              Cliquez sur un jour pour voir les absences des chauffeurs.
            </Typography>
            <Box sx={{ display: 'flex', gap: 1 }}>


              <RoadMapStyledSelect
                labelId="status-filter-label"
                id="status-filter"
                onChange={(e) => handleStatusFilterChange(e.target.value as string)}
                value={statusFilter}
                displayEmpty
              >
                {STATUS_OPTIONS.map((option) => (
                  <StyledMenuItem
                    key={option.value}
                    value={option.value}
                  >
                    {option.label}
                  </StyledMenuItem>
                ))}
              </RoadMapStyledSelect>
              <Box
                sx={{
                  borderLeft: 1,
                  mt: '2px',
                  height: 40,
                  borderColor: (theme) => theme.palette.text.disabled,
                }}
              />
              <CustomTooltip title={"Imprimer"} arrow>
                <IconButton onClick={() => void 0} sx={{ mt: '4px', ...WhiteIconButtonStyle }} >
                  <FontAwesome icon={faPrint} width={18} />
                </IconButton>
              </CustomTooltip>
              <CustomTooltip title={"exporter"} arrow>
                <IconButton onClick={() => void 0} sx={{ mt: '4px', ...WhiteIconButtonStyle }}>
                  <FontAwesome icon={faFileExport} width={18} />
                </IconButton>
              </CustomTooltip>
            </Box>

          </Stack>
        </Box>
      ) : <></>}

      <DialogContent sx={{ p: 0 }}>
        {calendarView === 'calendar' ? (
          <Box sx={{ p: 2, pb: 1 }}>
            <Box sx={{
              height: 800,
              '& .fc .fc-toolbar': {
                mb: 0,
                p: 1,
                borderRadius: 1,
                borderBottomLeftRadius: 0,
                borderBottomRightRadius: 0,
                bgcolor: theme.palette.background.neutral
              },
              '& .fc .fc-toolbar-title': {
                fontSize: '1.25rem',
                fontWeight: 'bold',
                color: theme.palette.primary.main
              },
              '& .fc .fc-button': {
                textTransform: 'capitalize',
                boxShadow: 'none',
                padding: '4px 8px',
                borderRadius: '6px',
                fontWeight: 'medium'
              },
              '& .fc .fc-button-primary': {
                bgcolor: theme.palette.primary.main,
                borderColor: theme.palette.primary.main,
                '&:hover': {
                  bgcolor: theme.palette.primary.dark,
                  borderColor: theme.palette.primary.dark
                }
              },
              '& .fc .fc-button-primary:not(:disabled).fc-button-active': {
                bgcolor: theme.palette.primary.dark,
                borderColor: theme.palette.primary.dark
              },
              '& .fc-daygrid-day': {
                border: `2px solid ${theme.palette.divider}`, // Bordure normale
              },
              '& .fc-day-today': {
                bgcolor: `${theme.palette.primary.lighter} !important`
              },
              '& .fc-day-other': {
                bgcolor: theme.palette.grey[50]
              },
              '& .fc-daygrid-day-number': {
                padding: '4px',
                fontSize: '0.875rem',
                position: 'relative',
                display: 'inline-flex',
                alignItems: 'center',
                justifyContent: 'center',
                minWidth: '32px'
              },
              '& .fc-event': {
                borderRadius: '4px',
                padding: '0px 4px',
                margin: '1px 0',
                cursor: 'pointer',
                borderWidth: '1px',
                boxShadow: '0 1px 2px rgba(0,0,0,0.05)'
              },
              '& .fc-h-event .fc-event-title': {
                fontWeight: 'medium',
                padding: '2px 4px'
              },
              '& .fc-more-link': {
                bgcolor: theme.palette.background.paper,
                padding: '2px 4px',
                borderRadius: '4px',
                fontWeight: 'medium',
                color: theme.palette.primary.main
              },
              "& .fc-daygrid-day-frame": {
                minHeight: "100px",
                position: "relative",
              },
              '& .fc-more-popover': {
                maxWidth: '400px !important',
                maxHeight: '60vh !important',
                zIndex: theme.zIndex.modal + 1,
                '& .fc-popover-body': {
                  padding: '8px !important',
                  },
                '& .fc-event-title': {
                  whiteSpace: 'normal !important', //
                  wordBreak: 'break-word',
                  lineHeight: '1.3'
                }
              },



            }}>
              <FullCalendar
                plugins={[dayGridPlugin, interactionPlugin]}
                initialView="dayGridMonth"
                events={calendarEvents}
                headerToolbar={{
                  left: 'prev,next today',
                  center: 'title',
                  right: 'dayGridMonth'
                }}
                locale={frLocale}
                dateClick={handleDateClick}
                eventDisplay="block"
                height="100%"
                dayCellDidMount={dayCellDidMount}
                eventTimeFormat={{
                  hour: '2-digit',
                  minute: '2-digit',
                  meridiem: false
                }}
                dayMaxEvents={3}
                moreLinkText={count => `+${count} absence(s)`}
                eventContent={(eventInfo) => {
                  return (
                    <Box sx={{
                      p: 0.5,
                      fontSize: '0.8rem',
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      fontWeight: 'medium',
                      borderRadius: '4px',
                      width: '100%'
                    }}>
                      {eventInfo.event.title}
                    </Box>
                  )
                }}
              />
            </Box>

            <Box sx={{ mt: 1, display: 'flex', flexWrap: 'wrap', gap: 2, justifyContent: 'center' }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: theme.palette.success.main }} />
                <Typography variant="caption">Validé</Typography>
              </Box>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: theme.palette.error.main }} />
                <Typography variant="caption">Refusé</Typography>
              </Box>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: theme.palette.warning.main }} />
                <Typography variant="caption">En cours</Typography>
              </Box>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                <Box sx={{ width: 12, height: 12, borderRadius: '50%', bgcolor: theme.palette.info.main }} />
                <Typography variant="caption">Non traité</Typography>
              </Box>
            </Box>
          </Box>
        ) : (
          <Box sx={{ p: 2 }}>
            <Stack direction="row" spacing={1} sx={{ mb: 2 }}>
              <Button
                startIcon={<FontAwesome icon={faChevronLeft} width={14} />}
                onClick={() => setCalendarView('calendar')}
                variant="outlined"
                size="small"
                sx={{ borderRadius: '8px' }}
              >
                Retour au calendrier
              </Button>
            </Stack>

            {selectedDateAbsences.length > 0 ? (
              <Box sx={{
                display: 'grid',
                gridTemplateColumns: { xs: '1fr', sm: '1fr 1fr', md: 'repeat(3, 1fr)' },
                gap: 2
              }}>
                {selectedDateAbsences.map((absence) => (
                  <Paper
                    key={absence.id}
                    elevation={0}
                    sx={{
                      p: 2,
                      borderRadius: 2,
                      bgcolor: 'background.paper',
                      border: '1px solid',
                      borderColor: 'divider',
                      position: 'relative',
                      transition: 'all 0.2s',
                      '&:hover': {
                        boxShadow: '0 4px 12px rgba(0,0,0,0.08)',
                        borderColor: 'primary.main'
                      },
                      '&::before': {
                        content: '""',
                        position: 'absolute',
                        top: 0,
                        left: 0,
                        width: '4px',
                        height: '100%',
                        borderTopLeftRadius: '8px',
                        borderBottomLeftRadius: '8px',
                        backgroundColor:
                          absence.statut === DriverAbsenceStatus.Valide
                            ? 'success.main'
                            : absence.statut === DriverAbsenceStatus.Rejete
                              ? 'error.main'
                              : absence.statut === DriverAbsenceStatus.EnCours
                                ? 'warning.main'
                                : 'info.main'
                      }
                    }}
                  >
                    <Stack direction="row" justifyContent="space-between" alignItems="flex-start" sx={{ mb: 1 }}>
                      <Typography variant="subtitle1" sx={{ pl: 1, fontWeight: 'bold' }}>
                        {absence.nomChauffeur}
                      </Typography>
                      {getStatusChip(absence.statut)}
                    </Stack>

                    <Divider sx={{ my: 1.5 }} />

                    <Stack spacing={1.5} sx={{ pl: 1 }}>
                      <Stack direction="row" spacing={1} alignItems="center">
                        <Typography variant="body2" color="text.secondary" sx={{ minWidth: 100 }}>
                          Type:
                        </Typography>
                        <Typography variant="body2" fontWeight="medium">
                          {absence.typeAbsence}
                        </Typography>
                      </Stack>

                      <Stack direction="row" spacing={1} alignItems="center">
                        <Typography variant="body2" color="text.secondary" sx={{ minWidth: 100 }}>
                          Début:
                        </Typography>
                        <Typography variant="body2" fontWeight="medium">
                          {new Date(absence.dateDebut).toLocaleDateString('fr-FR')}
                        </Typography>
                      </Stack>

                      <Stack direction="row" spacing={1} alignItems="center">
                        <Typography variant="body2" color="text.secondary" sx={{ minWidth: 100 }}>
                          Fin:
                        </Typography>
                        <Typography variant="body2" fontWeight="medium">
                          {new Date(absence.dateFin).toLocaleDateString('fr-FR')}
                        </Typography>
                      </Stack>
                    </Stack>

                    <Stack direction="row" spacing={1} sx={{ mt: 2, justifyContent: 'flex-end' }}>
                      <IconButton
                        size="small"
                        sx={{
                          color: theme.palette.primary.main,
                          bgcolor: theme.palette.primary.lighter,
                          '&:hover': {
                            bgcolor: theme.palette.primary.light
                          }
                        }}
                        onClick={() => onViewAbsence(absence)}
                      >
                        <FontAwesome icon={faEye} width={14} />
                      </IconButton>
                    </Stack>
                  </Paper>
                ))}
              </Box>
            ) : (
              <Paper
                elevation={0}
                sx={{
                  p: 3,
                  textAlign: 'center',
                  borderRadius: 2,
                  bgcolor: theme.palette.background.neutral,
                  border: `1px dashed ${theme.palette.divider}`
                }}
              >
                <Typography variant="body1" sx={{ mb: 1, color: 'text.secondary' }}>
                  Aucune absence pour cette date.
                </Typography>
              </Paper>
            )}
          </Box>
        )}
      </DialogContent>

      {calendarView === 'details' ? (
        <DialogActions sx={{ p: 2, borderTop: `1px solid ${theme.palette.divider}` }}>
          <Button
            onClick={() => setCalendarView('calendar')}
            variant="outlined"
            size="small"
            sx={{ ml: 'auto', borderRadius: '8px' }}
          >
            Fermer
          </Button>
        </DialogActions>
      ) : <></>}
    </StyledDialog>
  );
}