'use client';

import { useEffect, useRef, useState } from 'react';
import { format } from 'date-fns';
import { fr } from 'date-fns/locale';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
  Typography,
  Box,
  IconButton,
  Tooltip,
} from '@mui/material';
import FontAwesome from '@/shared/components/fontawesome';
import { faCar, faUser, faEye, faEyeSlash } from '@fortawesome/free-solid-svg-icons';
import { faOrcid } from '@fortawesome/free-brands-svg-icons';
import { StyledTableContainer } from '@/shared/theme/css';
import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { VehicleTimeSlotBlock } from './draggable-time-slot';
import { VehiculeDetailsPopover } from './vehicule-details-popover';
import { _planningEvents } from '@/shared/_mock/_planningEvents';
import { calculateTimeSlotWidth, groupOverlappingSlots, findSlotIndexInGroup, StatusColor } from '../utils/schedule-utils';
import PlanningEventDetailsDialog from './event-details-dialog';
import AddInterventionDialog from './add-intervention-dialog';
import InterventionTableView from './intervention-table-view';
import { InterventionDetailsPopover } from './intervention-details-popover';
import { PlanningToolbar } from './planning-toolbar';
import { HeaderCell } from './styled-components';
import { 
  INTERVAL_MINUTES, 
  CELL_WIDTH, 
  SLOT_HEIGHT, 
  LEFT_COLUMN_WIDTH, 
  PLANNING_TABLE_COLUMNS 
} from '../constants/planning-constants';
import {
  getHourIntervals,
  getMinuteIntervals,
  isTimeSlotInCell,
  convertEventsToTimeSlots
} from '../utils/planning-utils';
import { Dayjs } from 'dayjs';
import { TimeUnit } from '@/shared/types/common';
import CustomTooltip from '@/shared/components/tooltips/tooltip-custom';
import { DRIVER_TABLE_COLUMNS, mockScheduleData } from '@/shared/_mock/_driverSchedule';
import { DriverDraggableTimeSlot } from '@/shared/sections/chauffeur/planingChauffeur/components/draggable-time-slot';
import { TrajetDetailsPopover } from '../../chauffeur/planingChauffeur/components/trajet-details.popover';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

// Extract unique vehicles from planning events
const uniqueVehicles = [
  ..._planningEvents.reduce((acc: any[], event) => {
    if (!acc.some(v => v.registration === event.vehicle.immatriculation)) {
      acc.push({
        id: event.vehicle.immatriculation,
        name: `${event.vehicle.marque} ${event.vehicle.modele}`,
        type: event.vehicle.modele,
        registration: event.vehicle.immatriculation,
        driver: event.vehicle.chauffeur || 'Non Affecté'
      });
    }
    return acc;
  }, [])
];

const tableConfig: TableConfig<any> = {
  type: 'schedule',
  initialData: uniqueVehicles,
  defaultTableHead: PLANNING_TABLE_COLUMNS,
};

const mockTimeSlots = convertEventsToTimeSlots(_planningEvents);

export default function PlanningView() {
  const [selectedDate, setSelectedDate] = useState(new Date(2024, 11, 10));
  const [zoomLevel, setZoomLevel] = useState(50);
  const [showVehicleEvents, setShowVehicleEvents] = useState(true);
  const headerCellRef = useRef<HTMLTableCellElement>(null);
  const minuteCellRef = useRef<HTMLTableCellElement>(null);
  const [leftColumnWidth, setLeftColumnWidth] = useState(LEFT_COLUMN_WIDTH);
  const [cellWidth, setCellWidth] = useState(CELL_WIDTH);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const [hoveredVehicle, setHoveredVehicle] = useState<any>(null);
  const [anchorElT, setAnchorElT] = useState<HTMLElement | null>(null);
  const [hoveredSlot, setHoveredSlot] = useState<any>(null);
  const [scheduleData, setScheduleData] = useState({ 
    vehicles: uniqueVehicles,
    timeSlots: mockTimeSlots 
  });
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<any>(null);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [isInterventionTableOpen, setIsInterventionTableOpen] = useState(false);
  const [showDriverEvents, setShowDriverEvents] = useState(false);
  const [driverTimeSlots, setDriverTimeSlots] = useState<any[]>([]);

  const [currentTableHead, setCurrentTableHead] = useState(PLANNING_TABLE_COLUMNS)
  const { filteredData, tableHead, handleFilterChange, handleResetFilters } =
  useTableManager<any>({
    ...tableConfig,
    defaultTableHead: currentTableHead,
  })

  useEffect(() => {
    if (minuteCellRef.current) {
      const width = minuteCellRef.current.getBoundingClientRect().width;
      setCellWidth(width);
    }
  }, [zoomLevel]);

  useEffect(() => {
    if (headerCellRef.current) {
      const width = headerCellRef.current.getBoundingClientRect().width;
      setLeftColumnWidth(width);
    }
  }, []);

  useEffect(() => {
    if (showDriverEvents) {
      setDriverTimeSlots(mockScheduleData.timeSlots);
      const combinedColumns = [
        ...PLANNING_TABLE_COLUMNS,
        ...DRIVER_TABLE_COLUMNS.filter(
          (driverCol) => !PLANNING_TABLE_COLUMNS.some((planningCol) => planningCol.id === driverCol.id),
        ),
      ]
      setCurrentTableHead(combinedColumns)
      console.log(combinedColumns)
    } else {
      setDriverTimeSlots([]);
      setCurrentTableHead(PLANNING_TABLE_COLUMNS)
    }
  }, [showDriverEvents]);

  const handleDateChange = (date: Date | Dayjs, timeUnit?: TimeUnit) => {
    setSelectedDate(date instanceof Date ? date : date.toDate());
  };

  const handleZoomChange = (zoom: number) => {
    setZoomLevel(zoom);
  };

  const handlePopoverOpen = (event: React.MouseEvent<HTMLElement>, vehicle: any) => {
    if (vehicle.id !== '1') {
      event.preventDefault();
      event.stopPropagation();
      setAnchorEl(event.currentTarget);
      setHoveredVehicle(vehicle);
    }
  };

  const handlePopoverClose = () => {
    setAnchorEl(null);
    setHoveredVehicle(null);
  };

  const handlePopoverOpenT = (event: React.MouseEvent<HTMLElement>, slot: any) => {
    event.stopPropagation();
    setAnchorElT(event.currentTarget);
    setHoveredSlot(slot);
  };

  const handlePopoverCloseT = () => {
    setAnchorElT(null);
    setHoveredSlot(null);
  };

  const handleTimeSlotDoubleClick = (slot: any) => {
    const planningEvent = _planningEvents.find(event => event.id === slot.id);
    if (planningEvent) {
      setSelectedTimeSlot(planningEvent);
      setIsDrawerOpen(true);
    }
  };

  const handleEventUpdate = (updatedEvent: any) => {
    setIsDrawerOpen(false);
  };

  const handleAddClick = () => {
    setIsAddDialogOpen(true);
  };

  const handleAddDialogClose = () => {
    setIsAddDialogOpen(false);
  };

  const handleAddEvent = (interventionData: any) => {
    setIsAddDialogOpen(false);
  };

  const handleInterventionTableClose = () => {
    setIsInterventionTableOpen(false);
  };

  const handleInterventionEventClick = (event: any) => {
    setSelectedTimeSlot(event);
    setIsDrawerOpen(true);
    setIsInterventionTableOpen(false);
  };

  const handleBackClick = () => {
    setIsInterventionTableOpen(true);
  };

  const toggleDriverEvents = () => {
    setShowDriverEvents(prev => !prev);
  };

  const planningEventsButton = (
    <CustomTooltip arrow title={showDriverEvents ? "Masquer les événements chauffeurs" : "Afficher les événements chauffeurs"}>
      <IconButton
        onClick={toggleDriverEvents}
        sx={{
          bgcolor: showDriverEvents ? 'primary.main' : 'white',
          color: showDriverEvents ? 'white' : 'primary.main',
          '&:hover': {
            bgcolor: showDriverEvents ? 'primary.dark' : 'primary.lighter',
          },
        }}
      >
        <FontAwesome icon={showDriverEvents ? faEyeSlash : faEye} width={18} />
      </IconButton>
    </CustomTooltip>
  );
  
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={fr}>
      <Box 
        sx={{ 
          display: 'flex',
          width: '100%',
          height: '100%',
          position: 'relative',
          transition: 'all 0.3s ease',
          marginRight: isDrawerOpen ? '400px' : 0,
        }}
      >
        <Box sx={{ 
          flex: 1,
          overflow: 'hidden',
          display: 'flex',
          flexDirection: 'column',
        }}>
          <Box sx={{ 
            display: 'flex', 
            alignItems: 'center', 
            gap: 1,
          }}>
            <PlanningToolbar
              date={selectedDate}
              onDateChange={handleDateChange}
              onZoomChange={handleZoomChange}
              onResetFilters={() => {}}
              onFilters={() => {}}
              initialColumns={currentTableHead}
              onBackClick={handleBackClick}
              onAddClick={handleAddClick}
              rightAction={planningEventsButton}
            />
          </Box>
          <Box
            sx={{
              mt: 2,
              ml: `${leftColumnWidth}px`,
              py: 1,
              borderTopLeftRadius: 16,
              borderTopRightRadius: 16,
              display: 'flex',
              fontWeight: 500,
              justifyContent: 'center',
              backgroundColor: 'white',
            }}
          >
            {format(selectedDate, 'EEEE dd/MM/yyyy', { locale: fr })}
          </Box>
          <StyledTableContainer
            sx={{
              flex: 1,
              maxHeight: 'calc(100vh - 200px)',
            }}
          >
            <Table stickyHeader size="small">
              <TableHead>
                <TableRow>
                  <HeaderCell
                    ref={headerCellRef}
                    sx={{
                      position: 'sticky',
                      zIndex: 3,
                      left: 0,
                      backgroundColor: 'primary.lighter',
                      border: 'none',
                      width: leftColumnWidth,
                      minWidth: leftColumnWidth,
                    }}
                    rowSpan={2}
                  />
                  {getHourIntervals(selectedDate).map((interval) => {
                    const currentHour = new Date().getHours();
                    const isCurrentHour = currentHour === parseInt(interval.hour, 10);
                    return (
                      <HeaderCell
                        key={interval.hour}
                        colSpan={4}
                        sx={{
                          position: 'sticky',
                          backgroundColor: isCurrentHour ? 'primary.main' : '#F5F4FC',
                          top: 0,
                          zIndex: 2,
                          border: 'none',
                          color: isCurrentHour ? 'white' : 'inherit',
                        }}
                      >
                        {interval.hour}
                      </HeaderCell>
                    );
                  })}
                </TableRow>
                <TableRow>
                  {getHourIntervals(selectedDate).map((hour) =>
                    getMinuteIntervals().map((minute) => (
                      <HeaderCell
                        key={`${hour.hour}:${minute}`}
                        ref={minuteCellRef}
                        sx={{
                          position: 'sticky',
                          top: 32,
                          zIndex: 2,
                          fontSize: '0.75rem',
                          paddingInline: (theme) => theme.spacing((4 * zoomLevel) / 100),
                        }}
                      >
                        {minute}
                      </HeaderCell>
                    ))
                  )}
                </TableRow>
              </TableHead>
              <TableBody>
                {scheduleData.vehicles.map((vehicle) => (
                  <TableRow
                    key={vehicle.id}
                    hover
                  >
                    <TableCell
                      sx={{
                        position: 'sticky',
                        left: 0,
                        backgroundColor: 'background.paper',
                        zIndex: 2,
                      }}
                      onMouseEnter={(e) => handlePopoverOpen(e, vehicle)}
                      onMouseLeave={handlePopoverClose}
                    >
                      <Box sx={{ whiteSpace: 'nowrap' }} display="flex" alignItems="center">
                        <FontAwesome
                          icon={faCar}
                          color="primary.main"
                          width={12}
                          sx={{ mr: 1 }}
                        />
                        <Typography sx={{ fontWeight: 500 }} variant="caption">
                          {vehicle.name}
                        </Typography>
                      </Box>
                      <ConditionalComponent isValid={!!vehicle.type}>
                        <Box sx={{ whiteSpace: 'nowrap' }} display="flex" alignItems="center">
                          <FontAwesome icon={faCar} color="primary.main" width={12} sx={{ mr: 1 }} />
                          <Typography sx={{ fontWeight: 500 }} variant="caption" display="block">
                            {vehicle.type}
                          </Typography>
                        </Box>
                      </ConditionalComponent>
                      <ConditionalComponent isValid={!!vehicle.registration}>
                        <Box sx={{ whiteSpace: 'nowrap' }} display="flex" alignItems="center">
                          <FontAwesome icon={faOrcid} color="primary.main" width={12} sx={{ mr: 1 }} />
                          <Typography sx={{ fontWeight: 500 }} variant="caption">
                            {vehicle.registration}
                          </Typography>
                        </Box>
                      </ConditionalComponent>
                      <ConditionalComponent isValid={!!vehicle.driver}>
                        <Box sx={{ whiteSpace: 'nowrap' }} display="flex" alignItems="center">
                          <FontAwesome icon={faUser} color="primary.main" width={12} sx={{ mr: 1 }} />
                          <Typography sx={{ fontWeight: 500 }} variant="caption">
                            {vehicle.driver}
                          </Typography>
                        </Box>
                      </ConditionalComponent>
                    </TableCell>
                    {getHourIntervals(selectedDate).map((hour) =>
                      getMinuteIntervals().map((minute) => {
                        const vehicleSlots = scheduleData.timeSlots.filter(
                          (slot) => slot.vehicleId === vehicle.id
                        );                        
                        const driverSlots = showDriverEvents
                          ? driverTimeSlots.filter((slot) => slot.vehicleId === vehicle.id)
                          : [];
                          

                        const allSlots = [...vehicleSlots, ...driverSlots];
                        const overlappingGroups = groupOverlappingSlots(allSlots);
                        
                        const slotsInCell = allSlots.filter((slot) =>
                          isTimeSlotInCell(slot, hour.hour, minute)
                        );

                        const maxGroupHeight = overlappingGroups.reduce(
                          (max, group) => Math.max(max, group.length),
                          0
                        );

                        const cellHeight = maxGroupHeight <= 1 ? '100%' : `${(SLOT_HEIGHT + 2) * maxGroupHeight}px`;

                        return (
                          <TableCell
                            key={`${hour.hour}:${minute}`}
                            sx={{
                              position: 'relative',
                              backgroundColor: "white",
                              height: cellHeight,
                              padding: 0,
                              "&:last-of-type": {
                                borderRight: (theme) => `1px solid ${theme.palette.divider}`,
                              },
                              borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
                              borderLeft: (theme) => `1px solid ${theme.palette.divider}`,
                            }}
                          >
                            {slotsInCell.map((slot) => {
                              const indexInGroup = findSlotIndexInGroup(slot, overlappingGroups);
                              
                              if ("vehicle" in slot) {
                                return (
                                  <VehicleTimeSlotBlock
                                  key={slot.id}
                                  slot={slot}
                                  width={calculateTimeSlotWidth(
                                    slot.startHeure,
                                    slot.startMinute,
                                    slot.endHeure,
                                    slot.endMinute,
                                    INTERVAL_MINUTES,
                                    cellWidth
                                  )}
                                  height={maxGroupHeight <= 1 ? '100%' : `${SLOT_HEIGHT}px`}
                                  top={maxGroupHeight <= 1 ? 0 : indexInGroup * (SLOT_HEIGHT + 2)}
                                  handlePopoverOpenT={handlePopoverOpenT}
                                  handlePopoverCloseT={handlePopoverCloseT}
                                  onDoubleClick={() => handleTimeSlotDoubleClick(slot)}
                                />
                                );
                              }

                              return (
                                <DriverDraggableTimeSlot
                                key={slot.id}
                                slot={slot}
                                width={calculateTimeSlotWidth(
                                  slot.startHeure,
                                  slot.startMinute,
                                  slot.endHeure,
                                  slot.endMinute,
                                  INTERVAL_MINUTES,
                                  cellWidth
                                )}
                                height={maxGroupHeight <= 1 ? '100%' : `${SLOT_HEIGHT}px`}
                                top={maxGroupHeight <= 1 ? 0 : indexInGroup * (SLOT_HEIGHT + 2)}
                                handlePopoverOpenT={handlePopoverOpenT}
                                handlePopoverCloseT={handlePopoverCloseT}
                                onDoubleClick={() => void 0}
                                onCopySlot={() => void 0}
                              />
                              );
                            })}
                          </TableCell>
                        );
                      })
                    )}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </StyledTableContainer>
        </Box>

        <PlanningEventDetailsDialog
          open={isDrawerOpen}
          onClose={() => setIsDrawerOpen(false)}
          event={selectedTimeSlot}
          onEventUpdate={handleEventUpdate}
        />
      </Box>

      <AddInterventionDialog
        open={isAddDialogOpen}
        onClose={handleAddDialogClose}
        onSubmit={handleAddEvent}
      />

      <InterventionTableView
        open={isInterventionTableOpen}
        onClose={handleInterventionTableClose}
        events={_planningEvents}
        onEventClick={handleInterventionEventClick}
        handleResetFilters={() => {}}
        handleFilters={() => {}}
      />


      {hoveredSlot ? (
          <ConditionalComponent
            isValid={"vehicle" in hoveredSlot!}
          defaultComponent={
            <TrajetDetailsPopover
              anchorEl={anchorElT}
              color={hoveredSlot!.driverId === "1" ? StatusColor.PRIMARY : hoveredSlot!.color}
              onClose={handlePopoverCloseT}
              data={{
                circuit: "Circuit Résidentiel Nord",
                trajet: "Trajet 001 - Matin",
                schedule: "Lundi à Vendredi (09h00 à 17h00)",
                wheelchairCount: 5,
              }}
            />
          }
        >
          <InterventionDetailsPopover
            anchorEl={anchorElT}
            onClose={handlePopoverCloseT}
            slot={hoveredSlot}
          />
        </ConditionalComponent>
      ) : null}
    </LocalizationProvider>
  );
}