import { useMemo } from 'react';

import {
  IconCalendarEvent,
  IconDoorEnter,
  IconDoorExit,
} from '@material-hu/icons/tabler';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import Avatar from '@material-hu/components/design-system/Avatar';
import CardContainer from '@material-hu/components/design-system/CardContainer';
import Pills from '@material-hu/components/design-system/Pills';
import Tooltip from '@material-hu/components/design-system/Tooltip';

import { useAuth } from 'src/contexts/JWTContext';
import { SOURCE_INFO } from 'src/pages/dashboard/timeTracking/EmployeeTimesheet/utils';
import {
  type DaySummary,
  EntryType,
  type ParsedHoliday,
} from 'src/types/timeTracking';
import { formatToTime } from 'src/utils/date';
import { useLokaliseTranslation } from 'src/utils/i18n';
import { getCurrentLocale } from 'src/utils/locale';
import { iconsPolicyTypes } from 'src/utils/vacations';

import {
  getTimeOffPillLabel,
  isPeriodTimeOff,
  SOURCE_TOOLTIP_KEYS,
} from '../../constants';
import { getTimeOffCardDescription } from '../../utils/daySummary';

import DaySummaryEmpty from './DaySummaryEmpty';

const SectionTitle = ({ children }: { children: React.ReactNode }) => (
  <Typography
    variant="globalM"
    sx={{
      color: ({ palette }) => palette.new.text.neutral.default,
      fontWeight: 'fontWeightBold',
    }}
  >
    {children}
  </Typography>
);

const SecondaryText = ({ children }: { children: React.ReactNode }) => (
  <Typography
    variant="globalXXS"
    sx={{ color: ({ palette }) => palette.new.text.neutral.lighter }}
  >
    {children}
  </Typography>
);

const HolidayCard = ({
  holiday,
  description,
  pillLabel,
}: {
  holiday: ParsedHoliday;
  description: string;
  pillLabel: string;
}) => (
  <CardContainer
    fullWidth
    sx={{ borderRadius: theme => theme.shape.borderRadiusL }}
  >
    <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}>
      <Avatar
        color="default"
        Icon={holiday.icon}
        size="small"
      />
      <Stack sx={{ flex: 1 }}>
        <Typography
          variant="globalS"
          sx={{ fontWeight: 'fontWeightBold' }}
        >
          {holiday.name}
        </Typography>
        <SecondaryText>{description}</SecondaryText>
      </Stack>
      <Pills
        type="info"
        label={pillLabel}
        size="small"
        hasIcon
      />
    </Stack>
  </CardContainer>
);

type DaySummaryEntriesProps = {
  day: DaySummary;
};

const DaySummaryEntries = ({ day }: DaySummaryEntriesProps) => {
  const { user } = useAuth();
  const locale = getCurrentLocale(user);
  const { t } = useLokaliseTranslation([
    'clock',
    'time_tracker',
    'time_tracking_common',
  ]);

  const entries = useMemo(
    () =>
      [...(day.timeTrackingEntries ?? [])].sort((a, b) =>
        a.time.localeCompare(b.time),
      ),
    [day.timeTrackingEntries],
  );

  const timeOffRequest = day.timeOffRequests?.[0];
  const isPeriod = isPeriodTimeOff(timeOffRequest);
  const holiday = day.holidays?.[0];
  const hasTimeOff = !!timeOffRequest;
  const hasHoliday = !!holiday;
  const showDayOffSection = hasTimeOff || hasHoliday;

  return (
    <Stack sx={{ gap: 1 }}>
      {showDayOffSection && (
        <>
          <SectionTitle>{t('time_tracker:day_off_section')}</SectionTitle>
          {hasTimeOff && (
            <HolidayCard
              holiday={{
                name: timeOffRequest.timeOffPolicyTypeName,
                type: 'TIME_OFF',
                icon:
                  iconsPolicyTypes[timeOffRequest.timeOffPolicyTypeIcon] ??
                  IconCalendarEvent,
                hours: timeOffRequest.hours ?? 0,
              }}
              description={getTimeOffCardDescription(
                timeOffRequest,
                !!isPeriod,
                t,
              )}
              pillLabel={getTimeOffPillLabel(
                timeOffRequest,
                !!isPeriod,
                t,
                locale,
              )}
            />
          )}
          {hasHoliday && (
            <HolidayCard
              holiday={{
                name: holiday.holidayName,
                type: 'HOLIDAY',
                icon: IconCalendarEvent,
                hours: 0,
              }}
              description={t('time_tracker:holiday_description')}
              pillLabel={t('time_tracking_common:vacations_holidays')}
            />
          )}
        </>
      )}

      <SectionTitle>{t('history.tracks')}</SectionTitle>

      {entries.length === 0 && <DaySummaryEmpty />}
      {entries.length > 0 && (
        <Stack sx={{ gap: 1 }}>
          {entries.map(entry => {
            const isStart = entry.type === EntryType.START;
            const EntryIcon = isStart ? IconDoorEnter : IconDoorExit;
            const label = isStart
              ? t('time_tracker:entry')
              : t('time_tracker:exit');
            const sourceInfo = SOURCE_INFO[entry.source] as
              | (typeof SOURCE_INFO)[keyof typeof SOURCE_INFO]
              | undefined;
            const SourceIcon = sourceInfo?.icon;

            return (
              <CardContainer
                key={entry.id}
                fullWidth
              >
                <Stack
                  sx={{ flexDirection: 'row', alignItems: 'center', gap: 2 }}
                >
                  <Avatar
                    color="default"
                    Icon={EntryIcon}
                    size="small"
                  />

                  <Stack>
                    <Typography
                      variant="globalS"
                      sx={{ fontWeight: 'fontWeightBold' }}
                    >
                      {formatToTime(entry.time)}
                    </Typography>
                    <Stack
                      sx={{
                        flexDirection: 'row',
                        alignItems: 'baseline',
                        gap: 0.5,
                      }}
                    >
                      <SecondaryText>{label}</SecondaryText>
                      {(SourceIcon || entry.siteName) && (
                        <SecondaryText>&bull;</SecondaryText>
                      )}
                      {SourceIcon && (
                        <Tooltip
                          title={t('time_tracker:include_clock_method')}
                          description={t(
                            SOURCE_TOOLTIP_KEYS[sourceInfo.context] ?? '',
                          )}
                        >
                          <Stack
                            sx={{
                              cursor: 'pointer',
                              flexShrink: 0,
                              alignSelf: 'center',
                            }}
                          >
                            <SourceIcon size={14} />
                          </Stack>
                        </Tooltip>
                      )}
                      {entry.siteName && (
                        <SecondaryText>{entry.siteName}</SecondaryText>
                      )}
                    </Stack>
                  </Stack>
                </Stack>
              </CardContainer>
            );
          })}
        </Stack>
      )}
    </Stack>
  );
};

export default DaySummaryEntries;
