import { type FC, useEffect, useState } from 'react';

import useHuGoTheme from 'src/hooks/useHuGoTheme';
import {
  type ControlRegister,
  type TimeOffPopoverInfo,
  UserAccountStatus,
} from 'src/types/timeTracking';

import { usePeriodDetailDrawer } from '../../../components/PeriodDetailDrawer/usePeriodDetailDrawer';
import TimeOffInfoPopover from '../../../EmployeeTimesheet/components/TimeOffPopover';

import DailyPeriodRow from './components/DailyPeriodRow';
import PeriodRow from './components/PeriodRow';
import RegistersTableSkeleton from './TableSkeleton';

type Props = {
  onNavigateToUser: (id: number) => void;
  onNavigateToProfile: (id: number) => void;
  registers: ControlRegister[];
  isLoadingSummaries: boolean;
  isDailyView: boolean;
};

type TimeOffPopoverData = {
  anchor: HTMLElement | null;
  data: TimeOffPopoverInfo;
};

const DailyRegistersTable: FC<Props> = props => {
  const {
    onNavigateToUser,
    onNavigateToProfile,
    registers,
    isLoadingSummaries,
    isDailyView,
  } = props;
  const [expandedRow, setExpandedRow] = useState<number>();
  const [selectedCollaboratorRegister, setSelectedCollaboratorRegister] =
    useState<number>();
  const [timeOffPopoverData, setTimeOffPopoverData] =
    useState<TimeOffPopoverData>();
  const HuGoThemeProvider = useHuGoTheme();

  const selectedRegister =
    selectedCollaboratorRegister !== undefined
      ? registers[selectedCollaboratorRegister]
      : undefined;

  const drawerCustomProps = {
    userStatus: selectedRegister?.status,
    currentDate: selectedRegister?.currentDate,
    loadingSummaries: isLoadingSummaries,
    dayInfo: selectedRegister?.daySummaries[0],
    isDeactivated:
      selectedRegister?.userAccountStatus === UserAccountStatus.DEACTIVATED,
  };

  const { showPeriodDetailDrawer, drawer: PeriodDetailDrawer } =
    usePeriodDetailDrawer(drawerCustomProps);

  useEffect(() => {
    setExpandedRow(undefined);
  }, [registers]);

  if (isLoadingSummaries) {
    return <RegistersTableSkeleton />;
  }

  return (
    <HuGoThemeProvider>
      {PeriodDetailDrawer}
      {!isDailyView &&
        registers?.length > 0 &&
        registers?.map(register => (
          <PeriodRow
            key={register.userId}
            controlRegister={register}
            navigateToUser={onNavigateToUser}
            navigateToProfile={onNavigateToProfile}
          />
        ))}
      {isDailyView &&
        registers?.length > 0 &&
        registers?.map((register, index) => (
          <DailyPeriodRow
            key={register.userId}
            controlRegister={register}
            navigateToUser={onNavigateToUser}
            navigateToProfile={onNavigateToProfile}
            onOpenDrawer={() => {
              setSelectedCollaboratorRegister(index);
              showPeriodDetailDrawer();
            }}
            isExpanded={expandedRow === register.userId}
            onToggleExpanded={() => {
              setExpandedRow(
                expandedRow === register.userId ? undefined : register.userId,
              );
            }}
            onOpenTimeOffPopover={(anchor, data) => {
              setTimeOffPopoverData({ anchor, data });
            }}
          />
        ))}
      {timeOffPopoverData && (
        <TimeOffInfoPopover
          anchor={timeOffPopoverData.anchor}
          timeOffInfo={timeOffPopoverData.data}
          closePopover={() => {
            setTimeOffPopoverData(undefined);
          }}
        />
      )}
    </HuGoThemeProvider>
  );
};

export default DailyRegistersTable;
