import { IconButton, TableCell, TableRow } from '@mui/material';
import ValidationCombinedTableCell from './combined-table-validation-cell';
import React, { useState } from 'react';
import { CombinedTableDay, PeriodType, WorkedDay } from '@/shared/types/roadMap';
import { TrajetStyledRow, WhiteStyledRow } from '@/shared/sections/contract/styles';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import { useRoadMapStore } from '@/shared/api/stores/roadMapStore';
import dayjs from 'dayjs';
import { useSnackbar } from 'notistack';
import ConditionalComponent from '@/shared/components/table/ConditionalComponent';

interface ValidationCombinedTableRowProps {
  combinedTableRow?: CombinedTableDay;
  driverRouteSheetRow?: WorkedDay;
  date: Date;
  dayId: number;
  isFinalResult?: boolean;
}
export default function ValidationCombinedTableRow({
  combinedTableRow,
  driverRouteSheetRow,
  date,
  dayId,
  isFinalResult,
}: ValidationCombinedTableRowProps) {
  const RowComponent = isFinalResult ? WhiteStyledRow : TrajetStyledRow;
  const [modalOpen, setModalOpen] = React.useState(false);
  const [isChecked, setIsChecked] = React.useState(combinedTableRow?.isChecked || false);
  const [timeSlots, setTimeSlots] = useState<
    Record<string, { startHour: string | null; endHour: string | null }>
  >({});
  const createOrUpdateDailyRoadMap = useRoadMapStore((state) => state.createOrUpdateDailyRoadMap);
  const getValidedRoadmap = useRoadMapStore((state) => state.getValidedRoadmap);
  const { enqueueSnackbar } = useSnackbar();

  const handleTimeChange = (routeType: PeriodType, newTime: string, timeType: 'start' | 'end') => {
    setTimeSlots((prev) => {
      const currentSlot = prev[routeType] || { startHour: null, endHour: null };

      const updatedSlot = {
        ...currentSlot,
        [timeType === 'start' ? 'startHour' : 'endHour']: newTime || null,
      };

      const updatedSlots = {
        ...prev,
        [routeType]: updatedSlot,
      };

      return updatedSlots;
    });
  };

  const toggleCheck = async () => {
    try {
      const payload = Object.entries(timeSlots).map(([type, times]) => ({
        startHour: times.startHour,
        endHour: times.endHour,
        type,
      }));
      await createOrUpdateDailyRoadMap(4, 5, dayjs(date).format('YYYY-MM-DD'), payload);
      await getValidedRoadmap(4);
      setIsChecked(true);
      enqueueSnackbar('Heures validée avec succès.', { variant: 'success' });
    } catch (error) {
      console.error('Error saving route sheet:', error);
    }
  };
  if (!combinedTableRow && !driverRouteSheetRow) {
    return (
      <RowComponent>
        <TableCell align="center">{date.toLocaleDateString()}</TableCell>
        <TableCell align="center" colSpan={9}>
          Aucune donnée
        </TableCell>
      </RowComponent>
    );
  }
  const timeSlotsTypes: PeriodType[] = [
    PeriodType.Matin,
    PeriodType.Midi,
    PeriodType.ApresMidi,
    PeriodType.Soir,
  ];

  const getRouteTime = (
    type: PeriodType,
    isCombined: boolean,
    timeType: 'start' | 'end'
  ): string | null => {
    const routeList = isCombined ? combinedTableRow?.roads : driverRouteSheetRow?.roads;
    const route = routeList ? routeList.find((route) => route.type === type) : null;
    const time = route ? (timeType === 'start' ? route.startHour : route.endHour) : null;

    return typeof time === 'string' ? time : null;
  };

  return (

    <RowComponent
      sx={{
        backgroundColor: isChecked ? '#c3f6c3' : undefined,
      }}
    >
      <TableCell >
        {date.toLocaleDateString()}
      </TableCell>

      {timeSlotsTypes.map((timeSlot, index) => (
        <React.Fragment key={index}>
          <ValidationCombinedTableCell
            key={`${timeSlot}-start`}
            routeType={timeSlot}
            combinedRouteTime={getRouteTime(timeSlot, true, 'start')}
            driverRouteTime={getRouteTime(timeSlot, false, 'start')}
            dayId={dayId}
            onTimeChange={(type, time, timeType) => handleTimeChange(type, time, timeType)}
            timeType="start"
          />
          <ValidationCombinedTableCell
            key={`${timeSlot}-end`}
            routeType={timeSlot}
            combinedRouteTime={getRouteTime(timeSlot, true, 'end')}
            driverRouteTime={getRouteTime(timeSlot, false, 'end')}
            dayId={dayId}
            onTimeChange={(type, time, timeType) => handleTimeChange(type, time, timeType)}
            timeType="end"
          />
        </React.Fragment>
      ))}

      <TableCell>
        <IconButton onClick={() => toggleCheck()}>
          <ConditionalComponent
            isValid={isChecked}
            defaultComponent={<CheckCircleIcon fontSize="small" />}
          >
            <CheckCircleIcon fontSize="small" sx={{ color: '#138013' }} />
          </ConditionalComponent>
        </IconButton>
      </TableCell>
    </RowComponent>
  );
}
