"use client";

import { useEffect, useState, useCallback, useMemo } from 'react';
import { Box, Typography, CircularProgress, Alert } from '@mui/material';
import { AttendanceSheet } from '@/shared/types/attendance-sheet';
import { useAttendanceSheetStore } from '@/shared/api/stores/attendanceSheetStore';
import MultiSectionForm from '../components/multiSection-form';
import { ModeType } from '@/shared/types/common';
import { HEADER } from '@/layouts/config-layout';

interface AttendanceDetailViewProps {
  attendance: AttendanceSheet;
  mode: ModeType;
  onClose: (isSaved: boolean) => void;
  onEdit?: (item: AttendanceSheet) => void;
}

export default function AttendanceDetailView({
  attendance,
  mode,
  onClose,
  onEdit
}: AttendanceDetailViewProps) {
  const { getAttendanceSheetDetails } = useAttendanceSheetStore();
  const [details, setDetails] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isEditMode, setIsEditMode] = useState(false);

  const fetchDetails = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      const monthNumber = typeof attendance.month === "string" && attendance.month.includes("-")
        ? parseInt(attendance.month.split("-")[0].trim())
        : Number(attendance.month);

      const detailsData = await getAttendanceSheetDetails(
        Number(attendance.id),
        monthNumber,
        attendance.year
      );

      setDetails(detailsData);
    } catch (err: any) {
      console.error('Erreur lors du chargement des détails:', err);
      setError(err.message || 'Erreur lors du chargement');
    } finally {
      setLoading(false);
    }
  }, [attendance.id, attendance.month, attendance.year, getAttendanceSheetDetails]);

  useEffect(() => {
    fetchDetails();
  }, [fetchDetails]);

  const handleEditToggle = useCallback(() => {
    setIsEditMode(!isEditMode);
  }, [isEditMode]);

  const handleSaveAndReturn = useCallback((isSaved: boolean) => {
    if (isSaved) {
      fetchDetails();
    }
    setIsEditMode(false);
  }, [fetchDetails]);

  const vacationData = useMemo(() => {
    if (!details) return null;

    const passengers = details.passengers || [];
    const isCherDepartment = details.departmentName?.toLowerCase() === 'cher';

    const routeSheets = isCherDepartment 
      ? passengers.map((passenger: any) => {
          const convertedDays = details.days?.map((day: any) => {
            const passengerAttendance = day.passengerAttendances?.find(
              (pa: any) => pa.passengerId === passenger.id
            );
            
            const passengerStatuses: { [key: string]: { outbound: boolean; return: boolean } } = {};
            const concernedTrips = passengerAttendance?.concernedTrips || [];
            
            passengerStatuses[passenger.id.toString()] = {
              outbound: !concernedTrips.includes('Outbound'),
              return: !concernedTrips.includes('Return')
            };

            return {
              dayOfMonth: new Date(day.date).getDate(),
              dayOfWeek: day.dayOfWeek,
              weekend: day.weekend || false,
              holiday: false,
              passengerStatuses
            };
          }) || [];

          return {
            id: `${attendance.id}-${passenger.id}`,
            attendanceSheetNumber: details.number,
            circuitName: details.circuitName || attendance.circuitName,
            departmentName: details.departmentName || attendance.departmentName,
            establishment: details.establishment,
            month: details.month || Number(attendance.month),
            year: details.year || attendance.year,
            driver: details.driver,
            passengers: [passenger], 
            generatedAt: new Date().toISOString(),
            calendar: {
              days: convertedDays,
              passengers: [passenger]
            },
            observation: details.observation || ''
          };
        })
      : [
          {
            id: attendance.id,
            attendanceSheetNumber: details.number,
            circuitName: details.circuitName || attendance.circuitName,
            departmentName: details.departmentName || attendance.departmentName,
            establishment: details.establishment,
            month: details.month || Number(attendance.month),
            year: details.year || attendance.year,
            driver: details.driver,
            passengers: passengers,
            generatedAt: new Date().toISOString(),
            calendar: {
              days: details.days?.map((day: any) => {
                const passengerStatuses: { [key: string]: { outbound: boolean; return: boolean } } = {};
                
                day.passengerAttendances?.forEach((passengerAttendance: any) => {
                  const passengerId = passengerAttendance.passengerId.toString();
                  const concernedTrips = passengerAttendance.concernedTrips || [];
                  
                  passengerStatuses[passengerId] = {
                    outbound: !concernedTrips.includes('Outbound'),
                    return: !concernedTrips.includes('Return')
                  };
                });

                return {
                  dayOfMonth: new Date(day.date).getDate(),
                  dayOfWeek: day.dayOfWeek,
                  weekend: day.weekend || false,
                  holiday: false,
                  passengerStatuses
                };
              }) || [],
              passengers: passengers
            },
            observation: details.observation || ''
          }
        ];

    return {
      ...attendance,
      routeSheets
    };
  }, [details, attendance]);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (error) {
    return (
      <Box sx={{ p: 3 }}>
        <Alert severity="error">Erreur lors du chargement des détails: {error}</Alert>
      </Box>
    );
  }

  if (!details || !vacationData) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
        <Typography>Aucun détail disponible</Typography>
      </Box>
    );
  }

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        maxHeight: `calc(100vh - ${HEADER.H_DESKTOP + 8}px)`,
        overflow: "auto",
      }}
    >
      <MultiSectionForm
        onReturn={isEditMode ? () => handleSaveAndReturn(false) : () => onClose(false)}
        mode={isEditMode ? "edit" : "view"}
        vacation={vacationData}
        initialDepartement={details.departmentName || ''}
        onClose={isEditMode ? handleSaveAndReturn : onClose}
        attendance={{}}
        updateTabAttendance={() => { }}
        tabId={attendance.id}
        onEdit={handleEditToggle}
        showEditButton={!isEditMode}
      />
    </Box>
  );
}