import { useEffect, useRef } from 'react';

import {
  IconArrowLeft,
  IconArrowRight,
  IconBolt,
  IconLock,
  IconStopwatch,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import Skeleton from '@material-hu/mui/Skeleton';
import Stack from '@material-hu/mui/Stack';
import Typography from '@material-hu/mui/Typography';

import HuAlert from '@material-hu/components/design-system/Alert';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuRadioButton from '@material-hu/components/design-system/RadioButton/RadioButton';

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

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

import { BenefitRow } from './BenefitRow';
import { RequestOfferActions } from './RequestOfferActions';

export type PlanStepProps = {
  selectedWeeks: number;
  onSelectWeeks: (weeks: number) => void;
  onBack: () => void;
  onContinue: () => void;
  showBack?: boolean;
  showContinueButton?: boolean;

  paymentPlanOptions: readonly LoanPaymentPlanOption[];
  isPaymentPlanLoading?: boolean;
  periodicity: Periodicity;
};

const DEFAULT_PLAN_SKELETON_COUNT = 3;
// Matches the rendered height of a plan option card, borders included.
const PLAN_SKELETON_HEIGHT = 78;

const PlanOptionsSkeleton = ({ count }: { count: number }) => (
  <>
    {Array.from({ length: count }, (_, index) => (
      <Skeleton
        key={`plan-skeleton-${index}`}
        variant="rounded"
        height={PLAN_SKELETON_HEIGHT}
        sx={{ width: '100%', boxSizing: 'border-box', borderRadius: 2 }}
      />
    ))}
  </>
);

export const PlanStep = ({
  selectedWeeks,
  onSelectWeeks,
  onBack,
  onContinue,
  showBack = true,
  showContinueButton = true,
  paymentPlanOptions,
  isPaymentPlanLoading = false,
  periodicity,
}: PlanStepProps) => {
  const { t } = useLokaliseTranslation('loans');
  const resolvedPlanRows: readonly LoanPaymentPlanOption[] = paymentPlanOptions;
  const lastOptionsCountRef = useRef(0);

  useEffect(() => {
    if (resolvedPlanRows.length) {
      lastOptionsCountRef.current = resolvedPlanRows.length;
    }
  }, [resolvedPlanRows.length]);

  const skeletonCount =
    resolvedPlanRows.length ||
    lastOptionsCountRef.current ||
    DEFAULT_PLAN_SKELETON_COUNT;

  return (
    <Stack sx={{ gap: 2.5, width: '100%' }}>
      {showBack && (
        <Stack
          onClick={onBack}
          onKeyDown={event => {
            if (event.key === 'Enter' || event.key === ' ') {
              event.preventDefault();
              onBack();
            }
          }}
          role="button"
          tabIndex={0}
          sx={{
            flexDirection: 'row',
            alignItems: 'center',
            gap: 0.5,
            alignSelf: 'flex-start',
            color: theme => theme.palette.new.text.neutral.brand,
            cursor: 'pointer',
          }}
        >
          <IconArrowLeft
            size={16}
            stroke={2}
          />
          <Typography
            variant="globalS"
            sx={{ fontWeight: 'fontWeightSemiBold' }}
          >
            {t('back')}
          </Typography>
        </Stack>
      )}

      <Stack sx={{ gap: 0.5 }}>
        <Typography
          component="h2"
          variant="globalM"
          sx={{
            fontWeight: 'fontWeightBold',
            color: theme => theme.palette.new.text.neutral.default,
          }}
        >
          {t(periodicityKey('plan.title', periodicity))}
        </Typography>
      </Stack>

      <Stack sx={{ gap: 1.5 }}>
        {isPaymentPlanLoading && <PlanOptionsSkeleton count={skeletonCount} />}
        {!isPaymentPlanLoading &&
          resolvedPlanRows.map(option => {
            const isSelected = option.weeks === selectedWeeks;

            return (
              <HuCardContainer
                key={option.weeks}
                fullWidth
                padding={16}
                onClick={() => onSelectWeeks(option.weeks)}
              >
                <HuRadioButton
                  isActive={isSelected}
                  value={option.weeks}
                  label={t(
                    periodicityKey('plan.installments_option', periodicity),
                    {
                      count: option.weeks,
                      amount: formatCurrencyDecimal(option.weeklyPaymentMxn),
                    },
                  )}
                  labelProps={{
                    sx: { fontWeight: 'fontWeightSemiBold' },
                  }}
                  description={`${t('plan.total_label')}: ${formatCurrencyDecimal(
                    option.totalPaymentMxn,
                  )}`}
                />
              </HuCardContainer>
            );
          })}
      </Stack>

      <HuAlert
        severity="info"
        title={t('plan.first_discount_title')}
      />

      <HuCardContainer
        fullWidth
        padding={16}
      >
        <Stack sx={{ gap: 1.5 }}>
          <BenefitRow
            Icon={IconBolt}
            title={t('plan.instant_approval')}
            subtitle={t('plan.instant_approval_desc')}
          />
          <Divider />
          <BenefitRow
            Icon={IconLock}
            title={t('plan.secure')}
            subtitle={t('plan.secure_desc')}
          />
          <Divider />
          <BenefitRow
            Icon={IconStopwatch}
            title={t('plan.speed')}
            subtitle={t('plan.speed_desc')}
          />
        </Stack>
      </HuCardContainer>

      {showContinueButton && (
        <RequestOfferActions
          layout="column"
          actions={[
            {
              label: t('continue'),
              variant: 'primary',
              fullWidth: true,
              onClick: onContinue,
              endIcon: (
                <IconArrowRight
                  size={18}
                  stroke={2}
                />
              ),
            },
          ]}
        />
      )}
    </Stack>
  );
};
