import { useCallback, useState } from 'react';

import { IconChevronDown } from '@material-hu/icons/tabler';
import ButtonBase from '@material-hu/mui/ButtonBase';
import Collapse from '@material-hu/mui/Collapse';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuTable from '@material-hu/components/design-system/Table';
import HuTableBody from '@material-hu/components/design-system/Table/components/TableBody';
import HuTableCell from '@material-hu/components/design-system/Table/components/TableCell';
import HuTableContainer from '@material-hu/components/design-system/Table/components/TableContainer';
import HuTableHead from '@material-hu/components/design-system/Table/components/TableHead';
import HuTableRow from '@material-hu/components/design-system/Table/components/TableRow';

import { useLokaliseTranslation } from 'src/utils/i18n';

import { type Periodicity } from '../../types';
import { formatCurrencyDecimal } from '../../utils/formatters';
import { periodicityKey } from '../../utils/periodicity';

import { type ConfirmScheduleRow } from './confirmStepTypes';

// Header row (~60px) + two body rows (~48px each): the collapsed preview
// cuts the table after the second payment row.
const SCHEDULE_COLLAPSED_HEIGHT_PX = 156;

const ScheduleTableBody = ({
  rows,
  dimAfterFirst = false,
}: {
  rows: readonly ConfirmScheduleRow[];
  dimAfterFirst?: boolean;
}) => {
  const { t } = useLokaliseTranslation('loans');
  return (
    <HuTableContainer>
      <HuTable
        sx={
          dimAfterFirst
            ? {
                '& tbody tr:not(:first-of-type) .MuiTypography-root': {
                  color: theme => theme.palette.new.text.neutral.disabled,
                },
              }
            : undefined
        }
      >
        <HuTableHead>
          <HuTableRow headerRow>
            <HuTableCell headerCell>{t('confirm.schedule_week')}</HuTableCell>
            <HuTableCell headerCell>{t('confirm.schedule_date')}</HuTableCell>
            <HuTableCell
              headerCell
              align="right"
            >
              {t('confirm.schedule_payment')}
            </HuTableCell>
          </HuTableRow>
        </HuTableHead>
        <HuTableBody>
          {rows.map(item => (
            <HuTableRow key={item.week}>
              <HuTableCell>{item.week}</HuTableCell>
              <HuTableCell>{item.dateLabel}</HuTableCell>
              <HuTableCell align="right">
                {formatCurrencyDecimal(item.paymentMxn)}
              </HuTableCell>
            </HuTableRow>
          ))}
        </HuTableBody>
      </HuTable>
    </HuTableContainer>
  );
};

export type ConfirmStepSchedulePanelProps = {
  schedule: readonly ConfirmScheduleRow[];
  selectedWeeks: number;
  periodicity: Periodicity;
};

export const ConfirmStepSchedulePanel = ({
  schedule,
  selectedWeeks,
  periodicity,
}: ConfirmStepSchedulePanelProps) => {
  const { t } = useLokaliseTranslation('loans');
  const isCollapsible = schedule.length > 2;
  const [scheduleExpanded, setScheduleExpanded] = useState(!isCollapsible);

  const openSchedulePreview = useCallback(() => {
    setScheduleExpanded(true);
  }, []);

  return (
    <HuCardContainer
      fullWidth
      padding={0}
      sx={{ minWidth: 0, overflow: 'hidden', position: 'relative' }}
    >
      {!scheduleExpanded && (
        <ButtonBase
          aria-label={String(t('confirm.schedule_preview_aria'))}
          onClick={openSchedulePreview}
          sx={{
            position: 'absolute',
            inset: 0,
            zIndex: 1,
            cursor: 'pointer',
          }}
        />
      )}
      <Stack
        sx={{
          width: '100%',
          gap: 1.5,
          p: 2,
          pb: scheduleExpanded ? 2 : 0,
        }}
      >
        <Stack
          component="button"
          type="button"
          onClick={() => setScheduleExpanded(prev => !prev)}
          aria-expanded={scheduleExpanded}
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 1,
            width: '100%',
            p: 0,
            border: 'none',
            cursor: 'pointer',
            font: 'inherit',
            textAlign: 'left',
            bgcolor: 'transparent',
            color: 'inherit',
          }}
        >
          <Stack sx={{ minWidth: 0, gap: 0.25 }}>
            <Typography
              variant="globalM"
              sx={{
                fontWeight: 'fontWeightBold',
                color: theme => theme.palette.new.text.neutral.default,
              }}
            >
              {t('confirm.installments_section_title')}
            </Typography>
            <Typography
              variant="globalS"
              sx={{
                color: theme => theme.palette.new.text.neutral.lighter,
              }}
            >
              {t(periodicityKey('confirm.payment_installments', periodicity), {
                count: selectedWeeks,
              })}
            </Typography>
          </Stack>
          <Stack
            component="span"
            sx={{
              display: 'inline-flex',
              color: theme => theme.palette.new.text.neutral.lighter,
              transition: theme => theme.transitions.create('transform'),
              transform: scheduleExpanded ? 'rotate(180deg)' : 'none',
            }}
          >
            <IconChevronDown
              size={22}
              stroke={2}
              aria-hidden
            />
          </Stack>
        </Stack>
        <Collapse
          in={scheduleExpanded}
          collapsedSize={SCHEDULE_COLLAPSED_HEIGHT_PX}
        >
          <ScheduleTableBody
            rows={schedule}
            dimAfterFirst={!scheduleExpanded}
          />
        </Collapse>
      </Stack>
    </HuCardContainer>
  );
};
