import { useState } from 'react';

import { IconChevronDown } from '@material-hu/icons/tabler';
import Accordion from '@material-hu/mui/Accordion';
import AccordionDetails from '@material-hu/mui/AccordionDetails';
import AccordionSummary from '@material-hu/mui/AccordionSummary';
import Chip from '@material-hu/mui/Chip';
import Stack from '@material-hu/mui/Stack';
import { type Theme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import {
  type DayDetailResponse,
  DayDetailScheduleSource,
  type TimeSlot,
} from 'src/types/timeTracking';
import { type LokaliseTFunction, useLokaliseTranslation } from 'src/utils/i18n';
import {
  calculateTimeSpanInHours,
  formatCompleteDecimalHours,
} from 'src/utils/timeTracking';

import ScheduleCard from './ScheduleCard';

type Props = {
  schedule: DayDetailResponse['schedule'];
  hours: DayDetailResponse['hours'];
  timeSlots: DayDetailResponse['timeSlots'];
};

const getProgrammedText = (totalHours: number, t: LokaliseTFunction): string =>
  t('programmed_time', {
    time: formatCompleteDecimalHours(totalHours),
  });

const ScheduleSection = ({ schedule, hours, timeSlots }: Props) => {
  const { t } = useLokaliseTranslation('time_tracker');
  const [expanded, setExpanded] = useState(true);

  if (schedule.source === DayDetailScheduleSource.NONE) {
    return null;
  }

  const shifts = schedule.shiftAssociations ?? [];
  const hasMultipleShifts = shifts.length > 1;

  if (hasMultipleShifts) {
    const allSlots = shifts.flatMap(s =>
      s.timeSlots.map(ts => ({ ...ts, shiftId: s.id })),
    );
    return (
      <Accordion
        expanded={expanded}
        onChange={(_, newExpanded) => setExpanded(newExpanded)}
        disableGutters
        sx={{
          borderRadius: 2,
          backgroundColor: ({ palette }) =>
            palette.new.background.layout.default,
          boxShadow: 'none',
          '&:before': { display: 'none' },
          '&.Mui-expanded': { margin: 0 },
        }}
      >
        <AccordionSummary
          expandIcon={<IconChevronDown />}
          sx={{
            px: 2,
            py: 3,
            minHeight: 'auto',
            '& .MuiAccordionSummary-content': {
              margin: 0,
              alignItems: 'center',
              gap: 1,
            },
          }}
        >
          <Typography
            variant="globalS"
            sx={{ fontWeight: 'bold', flexShrink: 0 }}
          >
            {t('schedules_section_title')}
          </Typography>
          {!expanded && (
            <Stack
              sx={{
                flexDirection: 'row',
                gap: 0.5,
                flexWrap: 'wrap',
                justifyContent: 'flex-end',
                flex: 1,
              }}
            >
              {allSlots.map(ts => (
                <Chip
                  key={`${ts.shiftId}-${ts.startTime}-${ts.endTime}`}
                  label={`${ts.startTime} - ${ts.endTime}`}
                  size="small"
                  sx={{
                    background: ({ palette }: Theme) =>
                      palette.new.background.layout.tertiary,
                    border: ({ palette }: Theme) =>
                      `1px solid ${palette.new.border.neutral.default}`,
                    typography: 'globalXXS',
                    fontWeight: 'semiBold',
                    color: ({ palette }: Theme) =>
                      palette.new.text.neutral.lighter,
                  }}
                />
              ))}
            </Stack>
          )}
        </AccordionSummary>
        <AccordionDetails sx={{ px: 2, pb: 2, pt: 0 }}>
          <Stack sx={{ gap: 1 }}>
            {shifts.map(shift => {
              const shiftHours = shift.timeSlots.reduce(
                (acc, ts) =>
                  acc + calculateTimeSpanInHours(ts.startTime, ts.endTime),
                0,
              );
              return (
                <ScheduleCard
                  key={shift.id}
                  name={shift.name}
                  programmedHoursText={getProgrammedText(shiftHours, t)}
                  timeSlots={shift.timeSlots}
                  nested
                />
              );
            })}
          </Stack>
        </AccordionDetails>
      </Accordion>
    );
  }

  const scheduleName = schedule.workSchedule?.name ?? shifts[0]?.name ?? '';

  const slotsFromSchedule: TimeSlot[] = schedule.workSchedule
    ? timeSlots.map(ts => ({
        startTime: ts.startTime,
        endTime: ts.endTime,
      }))
    : shifts.flatMap(s => s.timeSlots);

  return (
    <Stack sx={{ gap: 1 }}>
      <Typography
        variant="globalS"
        sx={{ fontWeight: 'bold' }}
      >
        {t('schedule_section_title')}
      </Typography>
      <ScheduleCard
        name={scheduleName}
        programmedHoursText={getProgrammedText(hours.scheduled, t)}
        timeSlots={slotsFromSchedule}
      />
    </Stack>
  );
};

export default ScheduleSection;
