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

import { isBefore, startOfDay } from 'date-fns';
import {
  IconCalendarTime,
  IconChevronDown,
  IconDotsVertical,
  IconEdit,
  IconUserOff,
} from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAvatar from '@material-hu/components/design-system/Avatar';
import HuMenu from '@material-hu/components/design-system/Menu';
import HuMenuItem from '@material-hu/components/design-system/Menu/components/MenuItem';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';
import HuTitle from '@material-hu/components/design-system/Title';
import HuTooltip from '@material-hu/components/design-system/Tooltip';

import DayOffPopover from 'src/pages/dashboard/timeTracking/components/DayOffPopover';
import {
  type ControlRegister,
  type TimeOffPopoverInfo,
  UserAccountStatus,
} from 'src/types/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';
import {
  daySummaryWithAutoClosedEntry,
  displayHoursAndMinutes,
  getEffectiveWorkdayStatus,
  getNewestEntryPair,
  groupTimeSlotWithEntries,
  parseDayScheduleStatus,
} from 'src/utils/timeTracking';

import IncidenceSummary from '../../../../components/Incidences/IncidenceSummary';
import ProfilePicWithStatus from '../../../../components/ProfilePicWithStatus';
import ProgressBar from '../../../../components/ProgressBar';
import { STICKY_OPTIONS_CELL_SX } from '../constants';
import EntriesTime from '../EntriesTime';

import GroupSlots from './GroupSlots';
import ProgrammedHours from './ProgrammedHours';

type Props = {
  controlRegister: ControlRegister;
  navigateToUser: (id: number) => void;
  navigateToProfile: (id: number) => void;
  onOpenDrawer: () => void;
  isExpanded: boolean;
  onToggleExpanded: () => void;
  onOpenTimeOffPopover: (anchor: HTMLElement, data: TimeOffPopoverInfo) => void;
};

const sxFitContent = { width: 'fit-content' };

const DailyPeriodRow: FC<Props> = props => {
  const {
    controlRegister,
    onOpenDrawer,
    navigateToUser,
    navigateToProfile,
    isExpanded,
    onToggleExpanded,
    onOpenTimeOffPopover,
  } = props;
  const [menuAnchor, setMenuAnchor] = useState<HTMLButtonElement | null>(null);
  const [holidayPopoverAnchor, setHolidayPopoverAnchor] =
    useState<HTMLElement | null>(null);
  const { t } = useLokaliseTranslation('time_tracker');

  const isDeactivated =
    controlRegister.userAccountStatus === UserAccountStatus.DEACTIVATED;
  const dayInfo = controlRegister.daySummaries[0];
  const isPastDay = isBefore(
    new Date(`${dayInfo.date}T00:00:00`),
    startOfDay(new Date()),
  );
  const hasActivity = dayInfo.timeTrackingEntries.length > 0;
  const showRowContent = !isDeactivated || isPastDay || hasActivity;

  const handleToggleAccordion = () => {
    if (showRowContent) {
      onToggleExpanded();
    }
  };

  const DAY_SUMMARY_OPTIONS = [
    {
      onClick: () => {
        onOpenDrawer();
        setMenuAnchor(null);
      },
      icon: IconEdit,
      title: t('general:edit'),
      description: t('MENU_EDIT_TRACKINGS'),
    },
    {
      onClick: () => {
        navigateToUser(controlRegister.userId);
      },
      icon: IconCalendarTime,
      title: t('TIMESHEET'),
      description: t('MENU_TIMESHEET'),
    },
  ];

  const ActionCell = (
    <>
      <IconButton
        aria-controls="collaborator-actions"
        aria-label={t('general:actions')}
        aria-haspopup="true"
        onClick={event => {
          setMenuAnchor(event.currentTarget);
        }}
        sx={{ color: ({ palette }) => palette.new.text.neutral.default }}
      >
        <IconDotsVertical />
      </IconButton>
      <HuMenu
        id="collaborator-actions"
        open={Boolean(menuAnchor)}
        anchorEl={menuAnchor}
        onClose={() => {
          setMenuAnchor(null);
        }}
      >
        {DAY_SUMMARY_OPTIONS.map(({ description, icon, onClick, title }) => (
          <HuMenuItem
            key={title}
            onClick={onClick}
            sx={{ gap: 1 }}
          >
            <HuAvatar Icon={icon} />
            <HuTitle
              title={title}
              description={description}
              variant="S"
              sx={{ whiteSpace: 'normal' }}
            />
          </HuMenuItem>
        ))}
      </HuMenu>
    </>
  );

  const timeSlotGroups = useMemo(
    () =>
      groupTimeSlotWithEntries(
        dayInfo.timeSlots || [],
        dayInfo.timeTrackingEntries,
        getEffectiveWorkdayStatus(dayInfo),
      ),
    [dayInfo],
  );

  const newestEntryPair = getNewestEntryPair(dayInfo.timeTrackingEntries);
  const showIncidencesOnExpandedRow = dayInfo.incidences.length > 1;
  const { holiday, isScheduledDayOff } = parseDayScheduleStatus({
    holidays: dayInfo.holidays,
    isWorkday: dayInfo.isWorkday,
    scheduleSource: dayInfo.scheduleSource,
    timeOffRequests: dayInfo.timeOffRequests,
  });

  const handlePopoverOpen = (event: React.MouseEvent<HTMLElement>) => {
    event.stopPropagation();
    if (dayInfo.timeOffRequests.length > 0) {
      onOpenTimeOffPopover(event.currentTarget, {
        timeOff: dayInfo.timeOffRequests[0],
        schedule: {
          summaryHours: {
            scheduled: dayInfo.scheduledHours,
            worked: dayInfo.workedHours,
            estimated: dayInfo.estimatedHours,
            timeOff: 0,
          },
          timeSlots: dayInfo.timeSlots || [],
        },
      });
    } else if (dayInfo.holidays.length > 0) {
      setHolidayPopoverAnchor(event.currentTarget);
    }
  };

  const handleOpenUserProfile = () => {
    navigateToProfile(controlRegister.userId);
  };

  return (
    <>
      <HuTableRow
        sx={{
          '&:hover': {
            backgroundColor: ({ palette }) =>
              palette.new.background.elements.default,
          },
        }}
      >
        <HuTableCell
          align="center"
          sx={{ width: 72 }}
        >
          {showRowContent && (
            <IconButton
              aria-label={isExpanded ? t('COLLAPSE_ROW') : t('EXPAND_ROW')}
              onClick={handleToggleAccordion}
              sx={{ color: ({ palette }) => palette.new.text.neutral.default }}
            >
              <IconChevronDown
                style={{
                  transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
                  transition: 'transform 0.2s ease-in-out',
                }}
              />
            </IconButton>
          )}
        </HuTableCell>
        <HuTableCell
          align="left"
          onClick={handleOpenUserProfile}
          sx={{ cursor: 'pointer' }}
        >
          <HuTooltip
            title={t('general:deactivated_collaborator')}
            disableTooltip={!isDeactivated}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                gap: 1,
                cursor: 'pointer',
              }}
            >
              {isDeactivated && (
                <HuAvatar
                  Icon={IconUserOff}
                  size="small"
                  sx={{
                    color: ({ palette }) => palette.new.text.neutral.disabled,
                    backgroundColor: ({ palette }) =>
                      palette.new.background.layout.default,
                  }}
                />
              )}
              {!isDeactivated && (
                <ProfilePicWithStatus
                  status={controlRegister.status}
                  userAccountStatus={controlRegister.userAccountStatus}
                  userInfo={{
                    id: controlRegister.userId,
                    profilePicture: controlRegister.profilePicture,
                    fullName: controlRegister.fullName,
                  }}
                />
              )}
              <Typography
                variant="globalS"
                sx={sxFitContent}
              >
                {controlRegister.fullName}
              </Typography>
            </Stack>
          </HuTooltip>
        </HuTableCell>
        {showRowContent && (
          <>
            <HuTableCell align="left">
              <Stack
                sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}
              >
                <ProgrammedHours
                  scheduledHours={dayInfo.scheduledHours}
                  estimatedHours={dayInfo.estimatedHours}
                  holiday={holiday}
                  isScheduledDayOff={isScheduledDayOff}
                  onOpenDayOffPopover={handlePopoverOpen}
                  isWorkday={dayInfo.isWorkday}
                  dailyView
                />
              </Stack>
            </HuTableCell>
            <HuTableCell
              align="left"
              sx={{ minWidth: 183 }}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 0.5,
                  '& > :first-of-type': {
                    flex: 1,
                  },
                }}
              >
                <ProgressBar
                  worked={controlRegister.workedHours}
                  estimated={controlRegister.estimatedHours}
                  extra={controlRegister.extraHours}
                  autoClosed={daySummaryWithAutoClosedEntry(dayInfo)}
                  isDayOffOrHoliday={
                    isScheduledDayOff || Boolean(holiday?.name)
                  }
                  showTooltip
                />
                <Typography
                  variant="globalXS"
                  sx={sxFitContent}
                >
                  {displayHoursAndMinutes(
                    controlRegister.workedHours,
                    false,
                    true,
                  )}
                </Typography>
              </Stack>
            </HuTableCell>
            <HuTableCell align="left">
              <EntriesTime
                startTime={newestEntryPair.start}
                endTime={newestEntryPair.end}
                isNightShift={newestEntryPair.isNightShift}
              />
            </HuTableCell>
            <HuTableCell align="left">
              <Stack
                sx={{
                  flexDirection: 'row',
                  flexWrap: 'wrap',
                  gap: 2,
                }}
              >
                <IncidenceSummary
                  daySummary={dayInfo}
                  incidenceTags={controlRegister.incidencesTagsPresent}
                  isDeactivated={isDeactivated}
                />
              </Stack>
            </HuTableCell>
          </>
        )}
        {!showRowContent && (
          <>
            <HuTableCell align="left" />
            <HuTableCell
              align="left"
              sx={{ minWidth: 183 }}
            />
            <HuTableCell align="left" />
            <HuTableCell align="left" />
          </>
        )}
        <HuTableCell
          align="center"
          sx={{
            cursor: 'pointer',
            width: 72,
            ...STICKY_OPTIONS_CELL_SX,
            '& .tabler-icon': {
              stroke: ({ palette }) => palette.new.text.neutral.default,
            },
          }}
        >
          {ActionCell}
        </HuTableCell>
      </HuTableRow>
      {showRowContent && (
        <GroupSlots
          timeSlotGroups={timeSlotGroups}
          isExpanded={isExpanded}
          dayInfo={dayInfo}
          showIncidencesOnExpandedRow={showIncidencesOnExpandedRow}
          isDeactivated={isDeactivated}
        />
      )}
      <DayOffPopover
        dayOffEvent={dayInfo.timeOffRequests[0] || dayInfo.holidays[0]}
        isOpen={!!holidayPopoverAnchor}
        anchor={holidayPopoverAnchor}
        closePopover={() => {
          setHolidayPopoverAnchor(null);
        }}
      />
    </>
  );
};

export default DailyPeriodRow;
