import { type ReactNode, useEffect } from 'react';

import { IconInfoCircle, IconX } from '@material-hu/icons/tabler';
import IconButton from '@material-hu/mui/IconButton';
import Modal from '@material-hu/mui/Modal';
import Stack from '@material-hu/mui/Stack';
import { alpha } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import Avatar from '@material-hu/components/design-system/Avatar';
import Button from '@material-hu/components/design-system/Buttons/Button';
import HuCardContainer from '@material-hu/components/design-system/CardContainer';

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

import { trackLoanOpenInfoDetail } from '../../track';
import { type Periodicity } from '../../types';
import { periodicityKey } from '../../utils/periodicity';
import { CurrencyAmount } from '../CurrencyAmount';
import { DEFAULT_MICROLOAN_TNA_PERCENT } from '../LegalNote';

function formatRatePercent(value: number): string {
  return new Intl.NumberFormat('es-MX', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
}

export type CreditDetailsModalProps = {
  open: boolean;
  onClose: () => void;
  currency?: string;
  principal: number;
  totalInterests: number;
  totalToPay: number;
  catPercent?: number;
  tnaPercent?: number;
  installmentsCount: number;
  periodicity: Periodicity;
};

type DetailRowProps = {
  label: string;
  value: ReactNode;
};

const DetailRow = ({ label, value }: DetailRowProps) => (
  <Stack
    sx={{
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      gap: 2,
      py: 0.75,
    }}
  >
    <Typography
      variant="globalM"
      sx={{ color: theme => theme.palette.new.text.neutral.lighter }}
    >
      {label}
    </Typography>
    <Typography
      component="div"
      variant="globalM"
      sx={{
        fontWeight: 'fontWeightSemiBold',
        color: theme => theme.palette.new.text.neutral.default,
      }}
    >
      {value}
    </Typography>
  </Stack>
);

type SectionPanelProps = {
  sectionTitle: string;
  children: ReactNode;
};

const SectionPanel = ({ sectionTitle, children }: SectionPanelProps) => (
  <Stack>
    <Typography
      variant="globalXXS"
      sx={{
        letterSpacing: 1.2,
        fontWeight: 'fontWeightSemiBold',
        textTransform: 'uppercase',
        color: theme => theme.palette.new.text.neutral.default,
        opacity: 0.72,
        mb: 0.5,
      }}
    >
      {sectionTitle}
    </Typography>
    <Stack
      sx={{
        borderRadius: 2,
        p: 2,
        gap: 0.25,
        backgroundColor: theme => theme.palette.new.background.elements.grey,
      }}
    >
      {children}
    </Stack>
  </Stack>
);

export const CreditDetailsModal = ({
  open,
  onClose,
  currency = 'MXN',
  principal,
  totalInterests,
  totalToPay,
  catPercent,
  tnaPercent,
  installmentsCount,
  periodicity,
}: CreditDetailsModalProps) => {
  const { t } = useLokaliseTranslation('loans');

  useEffect(() => {
    if (open) {
      trackLoanOpenInfoDetail();
    }
  }, [open]);

  const tna =
    tnaPercent != null && Number.isFinite(tnaPercent)
      ? tnaPercent
      : DEFAULT_MICROLOAN_TNA_PERCENT;

  const frequencyValue = t(
    periodicityKey('confirm.credit_details_frequency', periodicity),
    { count: installmentsCount },
  );

  return (
    <Modal
      open={open}
      onClose={onClose}
      aria-labelledby="microloans-credit-details-title"
      slotProps={{
        backdrop: {
          sx: theme => ({
            backgroundColor: alpha(theme.palette.common.black, 0.5),
          }),
        },
      }}
    >
      <Stack
        role="dialog"
        aria-modal="true"
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 'calc(100% - 32px)',
          maxWidth: 480,
          maxHeight: 'min(90vh, 720px)',
          outline: 'none',
        }}
      >
        <HuCardContainer
          fullWidth
          padding={0}
          sx={{
            display: 'flex',
            flexDirection: 'column',
            maxHeight: '100%',
            overflow: 'hidden',
            '& > .MuiCardContent-root': {
              p: 0,
              display: 'flex',
              flexDirection: 'column',
              flex: 1,
              minHeight: 0,
              overflow: 'hidden',
            },
          }}
        >
          <Stack
            sx={{
              flexDirection: 'row',
              alignItems: 'flex-start',
              justifyContent: 'space-between',
              gap: 1,
              flexShrink: 0,
              px: 2,
              py: 2,
              borderBottom: 1,
              borderColor: theme => theme.palette.new.border.neutral.divider,
            }}
          >
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'flex-start',
                gap: 1,
                flex: 1,
                minWidth: 0,
              }}
            >
              <Avatar
                color="primary"
                Icon={IconInfoCircle}
              />

              <Stack sx={{ minWidth: 0, gap: 0.25 }}>
                <Typography
                  id="microloans-credit-details-title"
                  component="h2"
                  variant="globalM"
                  sx={{
                    fontWeight: 'fontWeightBold',
                    color: theme => theme.palette.new.text.neutral.default,
                  }}
                >
                  {t('confirm.credit_details_modal_title')}
                </Typography>
                <Typography
                  variant="globalXS"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                    lineHeight: 1.45,
                  }}
                >
                  {t('confirm.credit_details_modal_subtitle')}
                </Typography>
              </Stack>
            </Stack>
            <IconButton
              type="button"
              aria-label={t('legal.close_modal_aria')}
              onClick={onClose}
              size="small"
              sx={{
                color: theme => theme.palette.new.text.neutral.lighter,
                flexShrink: 0,
              }}
            >
              <IconX
                size={20}
                stroke={2}
              />
            </IconButton>
          </Stack>

          <Stack
            sx={{
              flex: 1,
              minHeight: 0,
              overflowY: 'auto',
              px: 2,
              py: 2,
              gap: 2,
            }}
          >
            <SectionPanel
              sectionTitle={t('confirm.credit_details_loan_summary_section')}
            >
              <DetailRow
                label={t('confirm.credit_details_requested_amount')}
                value={
                  <CurrencyAmount
                    value={principal}
                    currency={currency}
                    variant="globalM"
                    sx={{
                      fontWeight: 'fontWeightBold',
                      color: theme => theme.palette.new.text.neutral.brand,
                    }}
                  />
                }
              />
              <DetailRow
                label={t('confirm.total_interests_row')}
                value={
                  <CurrencyAmount
                    value={totalInterests}
                    currency={currency}
                    variant="globalM"
                    sx={{
                      fontWeight: 'fontWeightBold',
                      color: theme => theme.palette.new.text.neutral.brand,
                    }}
                  />
                }
              />
            </SectionPanel>

            <Stack
              sx={{
                borderRadius: 2,
                p: 2,
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: 2,
                mb: 2,
                backgroundColor: theme =>
                  theme.palette.new.background.layout.brand,
                border: 1,
                borderColor: theme =>
                  alpha(theme.palette.new.text.neutral.brand, 0.22),
              }}
            >
              <Typography
                variant="globalM"
                sx={{
                  fontWeight: 'fontWeightBold',
                  color: theme => theme.palette.new.text.neutral.brand,
                }}
              >
                {t('confirm.credit_details_total_to_pay')}
              </Typography>
              <CurrencyAmount
                value={totalToPay}
                currency={currency}
                variant="globalL"
                sx={{
                  fontWeight: 'fontWeightBold',
                  color: theme => theme.palette.new.text.neutral.brand,
                }}
              />
            </Stack>

            <SectionPanel
              sectionTitle={t('confirm.credit_details_rates_section')}
            >
              <DetailRow
                label={t('confirm.credit_details_tna_label')}
                value={`${formatRatePercent(tna)}%`}
              />
              {catPercent != null && Number.isFinite(catPercent) && (
                <DetailRow
                  label={t('confirm.credit_details_cat_label')}
                  value={`${formatRatePercent(catPercent)}%`}
                />
              )}
              <DetailRow
                label={t('confirm.credit_details_payment_frequency_label')}
                value={frequencyValue}
              />
            </SectionPanel>

            <Typography
              variant="globalXS"
              sx={{
                color: theme => theme.palette.new.text.neutral.disabled,
                lineHeight: 1.5,
              }}
            >
              {t('confirm.credit_details_footer_disclaimer')}
            </Typography>
          </Stack>

          <Stack
            sx={{
              flexShrink: 0,
              p: 2,
              pt: 1,
              borderTop: 1,
              borderColor: theme => theme.palette.new.border.neutral.divider,
            }}
          >
            <Button
              variant="primary"
              fullWidth
              onClick={onClose}
            >
              {t('confirm.credit_details_understood')}
            </Button>
          </Stack>
        </HuCardContainer>
      </Stack>
    </Modal>
  );
};
