'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,
  CircularProgress
} 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';
import { useRHAbsenceCalendarStore } from '@/shared/api/stores/hr-service/rhAbsenceCalendar';

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

const STATUS_OPTIONS = [
  { value: 'all', label: 'Tous les statuts' },
  { value: 'Approved', label: 'Validé' },
  { value: 'Rejected', label: 'Refusé' },
  { value: 'In_progress', label: 'En cours' },
  { value: 'Unprocessed', label: 'Non traité' },
];

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

  // Use the Zustand store
  const {
    loading,
    error,
    calendarAbsences,
    selectedDateAbsences,
    fetchAbsencesForMonth,
    fetchAbsencesForDate,
    clearAbsences,
    setError
  } = useRHAbsenceCalendarStore();

  const handleStatusFilterChange = (v: string) => {
    setStatusFilter(v);
    loadCalendarData(); // Reload data when filter changes
  };

  const handleCloseCalendar = () => {
    onClose();
    setSelectedDate(null);
    setCalendarView('calendar');
    setStatusFilter('all');
    clearAbsences();
    setError(null);
  };

  // Load calendar data from API
  const loadCalendarData = React.useCallback(async () => {
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1; // FullCalendar uses 0-based months
    
    const statusesToFilter = statusFilter === 'all' ? undefined : [statusFilter];
    
    try {
      await fetchAbsencesForMonth(year, month, statusesToFilter);
    } catch (err) {
      console.error('Failed to load calendar data:', err);
    }
  }, [currentDate, statusFilter, fetchAbsencesForMonth]);

  // Load data when component mounts or dependencies change
  React.useEffect(() => {
    if (open) {
      loadCalendarData();
    }
  }, [open, loadCalendarData]);

  // Filter absences based on status filter (fallback for prop-based data)
  const filteredCalendarAbsences = React.useMemo(() => {
    const dataToFilter = calendarAbsences.length > 0 ? calendarAbsences : absences;
    
    if (statusFilter === 'all') return dataToFilter;
    return dataToFilter.filter(absence => {
      switch (statusFilter) {
        case 'Approved':
          return absence.statut === DriverAbsenceStatus.Valide || absence.statut === 'Validé';
        case 'Rejected':
          return absence.statut === DriverAbsenceStatus.Rejete || absence.statut === 'Refusé';
        case 'In_progress':
          return absence.statut === DriverAbsenceStatus.EnCours || absence.statut === 'En cours';
        case 'Unprocessed':
          return absence.statut === DriverAbsenceStatus.NonTraite || absence.statut === 'Non traité';
        default:
          return true;
      }
    });
  }, [calendarAbsences, absences, statusFilter]);

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

    filteredCalendarAbsences.forEach(absence => {
      // Add null checks for dates
      if (!absence.dateDebut || !absence.dateFin) return;
      
      const startDate = new Date(absence.dateDebut);
      const endDate = new Date(absence.dateFin);

      // Validate dates
      if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) return;

      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:
        case 'Validé':
          backgroundColor = theme.palette.success.light;
          borderColor = theme.palette.success.main;
          textColor = theme.palette.success.darker;
          break;
        case DriverAbsenceStatus.Rejete:
        case 'Refusé':
          backgroundColor = theme.palette.error.lighter;
          borderColor = theme.palette.error.main;
          textColor = theme.palette.error.darker;
          break;
        case DriverAbsenceStatus.EnCours:
        case 'En cours':
          backgroundColor = theme.palette.warning.lighter;
          borderColor = theme.palette.warning.main;
          textColor = theme.palette.warning.darker;
          break;
        case DriverAbsenceStatus.NonTraite:
        case 'Non traité':
          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 || 'N/A'} - ${absence.typeAbsence || 'N/A'}`,
        start: absence.dateDebut || new Date().toISOString(),
        end: absence.dateFin || new Date().toISOString(),
        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 = async (info: any) => {
    const clickedDate = new Date(info.dateStr);
    setSelectedDate(clickedDate);
    setCalendarView('details');

    const dateStr = info.dateStr;
    const statusesToFilter = statusFilter === 'all' ? undefined : [statusFilter];

    try {
      // Get absences for the specific date from store
      await fetchAbsencesForDate(dateStr, statusesToFilter);
    } catch (err) {
      console.error('Failed to load absences for date:', err);
      // Fallback to filtering existing data
      const absencesForDate = filteredCalendarAbsences.filter(absence => {
        if (!absence.dateDebut || !absence.dateFin) return false;
        
        const startDate = new Date(absence.dateDebut);
        const endDate = new Date(absence.dateFin);
        
        if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) return false;
        
        return clickedDate >= startDate && clickedDate <= endDate;
      });
      // Note: selectedDateAbsences is now managed by the store
    }
  };

  // Handle calendar navigation
  const handleDatesSet = (dateInfo: any) => {
    const newDate = dateInfo.view.currentStart;
    setCurrentDate(new Date(newDate));
  };

  const getStatusChip = (status: string | undefined) => {
    if (!status) return null;
    
    switch (status) {
      case 'Validé':
      case DriverAbsenceStatus.Valide:
        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é':
      case DriverAbsenceStatus.Rejete:
        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':
      case DriverAbsenceStatus.EnCours:
        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é':
      case DriverAbsenceStatus.NonTraite:
        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, alignItems: 'center' }}>
              {loading && <CircularProgress size={20} />}
              
              <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 }}>
            {error && (
              <Box sx={{ mb: 2, p: 2, bgcolor: 'error.lighter', borderRadius: 1 }}>
                <Typography color="error">
                  Erreur lors du chargement: {error}
                </Typography>
              </Box>
            )}
            
            <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}`,
              },
              '& .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}
                datesSet={handleDatesSet}
                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>

            {loading ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
                <CircularProgress />
              </Box>
            ) : 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 || absence.statut === 'Validé'
                            ? 'success.main'
                            : absence.statut === DriverAbsenceStatus.Rejete || absence.statut === 'Refusé'
                              ? 'error.main'
                              : absence.statut === DriverAbsenceStatus.EnCours || absence.statut === 'En cours'
                                ? '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 || 'N/A'}
                      </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 || 'N/A'}
                        </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">
                          {absence.dateDebut ? new Date(absence.dateDebut).toLocaleDateString('fr-FR') : 'N/A'}
                        </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">
                          {absence.dateFin ? new Date(absence.dateFin).toLocaleDateString('fr-FR') : 'N/A'}
                        </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>
  );
}