import { useState } from 'react';
import { format, isToday, parseISO } from 'date-fns';

import { IconChevronDown } from '@material-hu/icons/tabler';
import Box from '@material-hu/mui/Box';
import Collapse from '@material-hu/mui/Collapse';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';
import { useTheme } from '@material-hu/mui/styles';
import Pills from '@material-hu/components/design-system/Pills';

import { useAuth } from 'src/contexts/JWTContext';
import { getCurrentLocale } from 'src/utils/locale';
import { type DaySummary } from 'src/types/timeTracking';
import {
  displayHoursAndMinutes,
  formatCompleteDecimalHours,
  parseDayScheduleStatus,
} from 'src/utils/timeTracking';
import { useLokaliseTranslation } from 'src/utils/i18n';

import DayBadge from './DayBadge';
import DaySummaryEntries from './DaySummaryEntries';
import {
  truncateTimeToHHMM,
  getTimeOffPillLabel,
  isPeriodTimeOff,
} from '../../constants';
import { getSubtitle } from '../../utils/daySummary';

type DaySummaryRowProps = {
  day: DaySummary;
  isFirst: boolean;
  isLast: boolean;
  isClockRunning: boolean;
};

const DaySummaryRow = ({
  day,
  isFirst,
  isLast,
  isClockRunning,
}: DaySummaryRowProps) => {
  const [isExpanded, setIsExpanded] = useState(false);
  const { palette } = useTheme();
  const { user } = useAuth();
  const { t } = useLokaliseTranslation([
    'time_tracking_common',
    'time_tracker',
  ]);
  const locale = getCurrentLocale(user);
  const date = parseISO(day.date);
  const weekdayLabel = format(date, 'EEE', { locale })
    .toUpperCase()
    .slice(0, 3);
  const dayNumber = format(date, 'd');

  const dayStatus = parseDayScheduleStatus({
    holidays: day.holidays,
    timeOffRequests: day.timeOffRequests,
    isWorkday: day.isWorkday,
    scheduleSource: day.scheduleSource,
  });

  const firstTimeSlot = day.timeSlots?.[0];
  const showSchedulePill =
    firstTimeSlot && (!dayStatus.isScheduledDayOff || !!dayStatus.holiday);
  const schedule = showSchedulePill
    ? `${truncateTimeToHHMM(firstTimeSlot.startTime ?? '')} - ${truncateTimeToHHMM(firstTimeSlot.endTime ?? '')}`
    : undefined;

  const subtitle = getSubtitle(day, dayStatus, t);

  const isNonWorkingDay =
    dayStatus.isScheduledDayOff || (dayStatus.holiday && !day.isWorkday);
  const isTodayDate = isToday(date);
  const showClockIndicator = isTodayDate && isClockRunning;

  const getDayStatusPills = () => {
    const pills: { type: 'info'; label: string }[] = [];
    const timeOff = day.timeOffRequests?.[0];
    if (timeOff) {
      pills.push({
        type: 'info',
        label: getTimeOffPillLabel(
          timeOff,
          !!isPeriodTimeOff(timeOff),
          t,
          locale,
        ),
      });
    }
    if (day.holidays?.length > 0) {
      pills.push({
        type: 'info',
        label: t('vacations_holidays'),
      });
    }
    return pills;
  };
  const dayStatusPills = getDayStatusPills();

  const rowPadding = isFirst ? { pb: 2 } : { py: 2 };
  const chevronRotation = isExpanded ? 'rotate(180deg)' : 'rotate(0deg)';
  const hasExpandedContent = !!(
    day.timeTrackingEntries?.length ||
    day.holidays?.length ||
    day.timeOffRequests?.length
  );

  return (
    <Stack>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          cursor: 'pointer',
          ...rowPadding,
        }}
        onClick={() => setIsExpanded(prev => !prev)}
      >
        <DayBadge
          weekday={weekdayLabel}
          day={dayNumber}
          isToday={isTodayDate}
        />

        <Stack sx={{ flex: 1 }}>
          <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 0.5 }}>
            {showClockIndicator && (
              <Box
                sx={{
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  backgroundColor: palette.success.main,
                  flexShrink: 0,
                }}
              />
            )}
            <Typography
              variant="globalS"
              sx={{
                fontWeight: 'fontWeightBold',
                ...(isNonWorkingDay &&
                  day.workedHours === 0 && {
                    color: palette.new.text.neutral.lighter,
                  }),
              }}
            >
              {formatCompleteDecimalHours(day.workedHours)}
            </Typography>
            {day.extraHours > 0 && (
              <Typography
                variant="globalXXS"
                sx={{ color: palette.new.text.neutral.brand }}
              >
                {`+${displayHoursAndMinutes(day.extraHours)}`}
              </Typography>
            )}
          </Stack>
          {subtitle && (
            <Typography
              variant="globalXXS"
              sx={{ color: palette.new.text.neutral.lighter }}
            >
              {subtitle}
            </Typography>
          )}
        </Stack>

        <Stack sx={{ flexDirection: 'row', alignItems: 'center', gap: 1 }}>
          {dayStatusPills.map((pill, index) => (
            <Pills
              key={index}
              type={pill.type}
              label={pill.label}
              size="small"
              hasIcon
            />
          ))}
          {schedule && (
            <Pills
              type="neutral"
              label={schedule}
              size="small"
              hasIcon={false}
            />
          )}
          <IconButton
            size="small"
            aria-label={
              isExpanded
                ? t('time_tracker:collapse_row')
                : t('time_tracker:expand_row')
            }
            onClick={e => {
              e.stopPropagation();
              setIsExpanded(prev => !prev);
            }}
            sx={{
              transition: 'transform 0.2s',
              transform: chevronRotation,
            }}
          >
            <IconChevronDown size={16} />
          </IconButton>
        </Stack>
      </Stack>

      <Collapse in={isExpanded}>
        <Box
          sx={{
            mb: 1,
            ...(hasExpandedContent && {
              backgroundColor: palette.new.background.layout.default,
              borderRadius: theme => theme.shape.borderRadiusL,
              p: 2,
            }),
          }}
        >
          <DaySummaryEntries day={day} />
        </Box>
      </Collapse>

      {!isLast && <Divider />}
    </Stack>
  );
};

export default DaySummaryRow;
