import React, { useState, useEffect } from 'react';
import {
  Dialog,
  IconButton,
  Typography,
  Box,
  Chip,
  Grid,
  Paper,
  CircularProgress
} from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import MoreHorizIcon from '@mui/icons-material/MoreHoriz';
import FlightTakeoffIcon from '@mui/icons-material/FlightTakeoff';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import { IAgent, WorkSchedule, WeeklySchedule, DaySchedule } from '@/shared/types/client';
import { useAbsenceStoree } from '@/shared/api/stores/absenceStore';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';
import WeeklySchedulePreview from './account-schedule/WeeklySchedulePreview';
import LeavesList from './account-schedule/LeavesList';
import SettingsDialog from './account-schedule/SettingsDialog';

interface AccountScheduleModalProps {
  open: boolean;
  onClose: () => void;
  collaborator?: IAgent | null;
}

interface UserLeaveByYear {
  absenceType: string | null;
  totalDays: number;
  startDate: string;
  endDate: string;
}

const DAYS_OF_WEEK = [
  { key: 'monday', label: 'Lundi', shortLabel: 'Lun' },
  { key: 'tuesday', label: 'Mardi', shortLabel: 'Mar' },
  { key: 'wednesday', label: 'Mercredi', shortLabel: 'Mer' },
  { key: 'thursday', label: 'Jeudi', shortLabel: 'Jeu' },
  { key: 'friday', label: 'Vendredi', shortLabel: 'Ven' },
  { key: 'saturday', label: 'Samedi', shortLabel: 'Sam' },
  { key: 'sunday', label: 'Dimanche', shortLabel: 'Dim' },
];

const AccountScheduleModal: React.FC<AccountScheduleModalProps> = ({ open, onClose, collaborator }) => {

  const [year, setYear] = useState<number>(new Date().getFullYear());
  const [openModal, setOpenModal] = useState<boolean>(false);
  const [leaves, setLeaves] = useState<UserLeaveByYear[]>([]);
  const [absences, setAbsences] = useState<UserLeaveByYear[]>([]);
  const [loadingLeaves, setLoadingLeaves] = useState<boolean>(false);
  const [loadingAbsences, setLoadingAbsences] = useState<boolean>(false);

  const { getUserLeavesByYear } = useAbsenceStoree();

  // Récupérer les congés et absences quand l'année change
  useEffect(() => {
    if (open && collaborator?.id) {
      loadLeavesAndAbsences();
    }
  }, [year, open, collaborator?.id]);

  const loadLeavesAndAbsences = async () => {
    if (!collaborator?.id) return;

    const userId = parseInt(collaborator.id);
    
    // Charger les congés
    setLoadingLeaves(true);
    try {
      const leavesData = await getUserLeavesByYear(userId, 'LEAVE', year);
      setLeaves(leavesData);
    } catch (error) {
      console.error('Erreur lors du chargement des congés:', error);
      setLeaves([]);
    } finally {
      setLoadingLeaves(false);
    }

    // Charger les absences
    setLoadingAbsences(true);
    try {
      const absencesData = await getUserLeavesByYear(userId, 'ABSENCE', year);
      setAbsences(absencesData);
    } catch (error) {
      console.error('Erreur lors du chargement des absences:', error);
      setAbsences([]);
    } finally {
      setLoadingAbsences(false);
    }
  };

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return date.toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
      });
    } catch {
      return dateString;
    }
  };

  const translateAbsenceType = (absenceType: string | null): string => {
    if (!absenceType) return '';
    
    const typeTranslations: { [key: string]: string } = {
      'EXTERNAL_ASSIGNMENT': 'Mission externe',
      'PROFESSIONAL_TRAINING': 'Formation professionnelle',
      'EXCEPTIONAL_REMOTE_WORK': 'Télétravail exceptionnel',
      'AUTHORIZED_ABSENCE': 'Absence autorisée',
      'UNAUTHORIZED_ABSENCE': 'Absence non autorisée',
      'MEDICAL_APPOINTMENT': 'Rendez-vous médical',
      'OTHER': 'Autre',
      // Types de congés
      'LEAVE_SICK': 'Congé maladie',
      'LEAVE_PARENTAL': 'Congé parental',
      'LEAVE_PAID': 'Congé payé',
      'LEAVE_UNPAID': 'Congé sans solde',
      'LEAVE_RTT': 'RTT',
      'LEAVE_MALADIE': 'Congé maladie'
    };
    
    return typeTranslations[absenceType] || absenceType;
  };

  const getWorkingDaysCount = (schedule?: WorkSchedule) => {
    if (!schedule?.weeklySchedule) return 0;
    return Object.values(schedule.weeklySchedule).filter(day => day.isWorkingDay).length;
  };

  const getTotalWorkingHours = (schedule?: WorkSchedule) => {
    if (!schedule?.weeklySchedule) return 0;
    
    let totalHours = 0;
    Object.values(schedule.weeklySchedule).forEach(day => {
      if (day.isWorkingDay && day.startTime && day.endTime) {
        const start = new Date(`2000-01-01T${day.startTime}`);
        const end = new Date(`2000-01-01T${day.endTime}`);
        if (!isNaN(start.getTime()) && !isNaN(end.getTime())) {
          const diffMs = end.getTime() - start.getTime();
          const diffHours = diffMs / (1000 * 60 * 60);
          totalHours += diffHours;
        }
      }
    });
    return totalHours;
  };

  const renderDaySchedule = (day: typeof DAYS_OF_WEEK[0], schedule?: WorkSchedule) => {
    if (!schedule?.weeklySchedule) return null;
    
    const daySchedule = schedule.weeklySchedule[day.key as keyof WeeklySchedule];
    if (!daySchedule || typeof daySchedule === 'string') return null;
    
    const isWorkingDay = daySchedule.isWorkingDay;

    return (
      <Grid item xs sx={{ p: 2, textAlign: 'center' }} key={day.key}>
        <Typography variant="body2" sx={{ fontWeight: 'medium', mb: 1, color: isWorkingDay ? 'text.primary' : 'text.disabled' }}>
          {day.label}
        </Typography>
        <ConditionalComponent
          isValid={!!(isWorkingDay && daySchedule.startTime && daySchedule.endTime)}
          defaultComponent={
            <Typography variant="body2" sx={{ color: 'text.disabled' }}>
              {isWorkingDay ? 'Horaires non définis' : 'Jour libre'}
            </Typography>
          }
        >
          <Typography variant="body2">
            {daySchedule.startTime} - {daySchedule.endTime}
          </Typography>
        </ConditionalComponent>
      </Grid>
    );
  };

  return (
    <Dialog
      open={open}
      onClose={onClose}
      fullWidth
      maxWidth="md"
      PaperProps={{
        sx: {
          borderRadius: 2,
          maxHeight: '80vh'
        }
      }}
    >
      <Box sx={{ p: 3 }}>
        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
          <Typography variant="h5" component="h2" sx={{ fontWeight: 'bold' }}>
            Emploi du temps du compte
          </Typography>
          <Box sx={{ display: 'flex', alignItems: 'center' }}>
            <Chip
              label="Par défaut"
              size="medium"
              sx={{
                bgcolor: 'rgba(25, 118, 210, 0.1)',
                color: 'primary.main',
                mr: 1
              }}
              icon={<InfoOutlinedIcon fontSize="small" />}
            />
            <IconButton onClick={() => setOpenModal(!openModal)} size="small">
              <MoreHorizIcon />
            </IconButton>
            <IconButton onClick={onClose}>
              <CloseIcon />
            </IconButton>
          </Box>

          <SettingsDialog open={openModal} onClose={() => setOpenModal(false)} />
        </Box>


        <WeeklySchedulePreview schedule={collaborator?.schedule} />

        <Box sx={{ mb: 3 }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <FlightTakeoffIcon sx={{ mr: 1, color: 'text.secondary' }} />
              <Typography variant="subtitle1">Congés et Absences {year}</Typography>
              <IconButton onClick={() => setYear(year - 1)} size="small">
                <ArrowBackIosNewIcon fontSize="small" />
              </IconButton>
              <IconButton onClick={() => setYear(year + 1)} size="small">
                <ArrowForwardIosIcon fontSize="small" />
              </IconButton>
            </Box>
          </Box>

          {/* Mise en page en colonnes pour séparer congés et absences */}
          <Grid container spacing={3}>
            {/* Colonne de gauche - Congés */}
            <Grid item xs={12} md={6}>
              <Box sx={{ p: 2, bgcolor: 'grey.50', borderRadius: 2, border: '1px solid', borderColor: 'grey.200', height: '100%' }}>
                <LeavesList
                  title="Congés"
                  color="primary"
                  loading={loadingLeaves}
                  items={leaves}
                  translateAbsenceType={(t) => translateAbsenceType(t)}
                  formatDate={(d) => formatDate(d)}
                />
              </Box>
            </Grid>

            {/* Colonne de droite - Absences */}
            <Grid item xs={12} md={6}>
              <Box sx={{ p: 2, bgcolor: 'grey.50', borderRadius: 2, border: '1px solid', borderColor: 'grey.200', height: '100%' }}>
                <LeavesList
                  title="Absences"
                  color="warning"
                  loading={loadingAbsences}
                  items={absences}
                  translateAbsenceType={(t) => translateAbsenceType(t)}
                  formatDate={(d) => formatDate(d)}
                />
              </Box>
            </Grid>
          </Grid>
        </Box>
      </Box>
    </Dialog>
  );
};

export default AccountScheduleModal;