import { useState } from 'react';

import {
  IconCalendarEvent,
  IconCash,
  IconCheck,
  IconInfoCircle,
} from '@material-hu/icons/tabler';
import Divider from '@material-hu/mui/Divider';
import IconButton from '@material-hu/mui/IconButton';
import Stack from '@material-hu/mui/Stack';
import { alpha, type Theme } from '@material-hu/mui/styles';
import Typography from '@material-hu/mui/Typography';

import HuCardContainer from '@material-hu/components/design-system/CardContainer';
import HuPills from '@material-hu/components/design-system/Pills';
import { type PillsProps } from '@material-hu/components/design-system/Pills/types';

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

import {
  formatMicroloanOverdueMessage,
  type MicroloanPlanStatus,
  type MicroloansStatusViewModel,
  type ScheduleTone,
} from '../../utils/buildMicroloansStatusViewModel';
import { periodicityKey } from '../../utils/periodicity';
import { CurrencyAmount } from '../CurrencyAmount';
import HistoryLink from '../HistoryLink';
import { microloanCardBorderSx } from '../cardSurfaceSx';
import LegalNote from '../LegalNote';
import { CreditDetailsModal } from '../requestOffer/CreditDetailsModal';

type ActivePlanVm = MicroloansStatusViewModel;

type PlanStatusStyle = {
  progressFill: (theme: Theme) => string;
};

const PLAN_STATUS_PILL_TYPE: Record<MicroloanPlanStatus, PillsProps['type']> = {
  ON_TRACK: 'success',
  OVERDUE: 'error',
  PAUSED: 'neutral',
  PENDING_DISBURSEMENT: 'warning',
};

type ActivePlanStatusContentProps = {
  planStatusLabel: string;
  vm: ActivePlanVm;
  planStyles: PlanStatusStyle;
};

const SUMMARY_ICON_BY_KIND = {
  balance: IconCash,
  paidRatio: IconCheck,
  nextDue: IconCalendarEvent,
} as const;

const SUMMARY_CARD_SX_BY_GRID_SPAN: Record<
  1 | 2,
  { gridColumn?: { xs: string; sm: string } }
> = {
  1: {},
  2: {
    gridColumn: {
      xs: 'span 1',
      sm: 'span 2',
    },
  },
};

const SCHEDULE_TONE_STYLES: Record<
  ScheduleTone,
  {
    circle: (theme: Theme) => { backgroundColor: string; color: string };
    pill: (theme: Theme) => { backgroundColor: string; color: string };
    rowHighlight: (theme: Theme) => { backgroundColor?: string };
  }
> = {
  success: {
    circle: theme => ({
      backgroundColor: theme.palette.new.background.feedback.success,
      color: theme.palette.new.text.feedback.success,
    }),
    pill: theme => ({
      backgroundColor: theme.palette.new.background.feedback.success,
      color: theme.palette.new.text.feedback.success,
    }),
    rowHighlight: () => ({}),
  },
  brand: {
    circle: theme => ({
      backgroundColor: theme.palette.new.background.elements.grey,
      color: theme.palette.new.text.neutral.lighter,
    }),
    pill: theme => ({
      backgroundColor: alpha(theme.palette.new.background.layout.brand, 0.15),
      color: theme.palette.new.text.neutral.brand,
    }),
    rowHighlight: theme => ({
      backgroundColor: alpha(theme.palette.new.background.layout.brand, 0.08),
    }),
  },
  error: {
    circle: theme => ({
      backgroundColor: theme.palette.new.background.feedback.error,
      color: theme.palette.new.text.feedback.error,
    }),
    pill: theme => ({
      backgroundColor: alpha(theme.palette.new.background.feedback.error, 0.35),
      color: theme.palette.new.text.feedback.error,
    }),
    rowHighlight: theme => ({
      backgroundColor: alpha(theme.palette.new.background.feedback.error, 0.1),
    }),
  },
  muted: {
    circle: theme => ({
      backgroundColor: theme.palette.new.background.layout.brand,
      color: theme.palette.new.action.button.text.primary.default,
    }),
    pill: theme => ({
      backgroundColor: theme.palette.new.background.elements.grey,
      color: theme.palette.new.text.neutral.lighter,
    }),
    rowHighlight: () => ({}),
  },
};

const ActivePlanStatusContent = ({
  vm,
  planStyles,
  planStatusLabel,
}: ActivePlanStatusContentProps) => {
  const { t } = useLokaliseTranslation('loans');
  const [creditDetailsOpen, setCreditDetailsOpen] = useState(false);

  return (
    <Stack sx={{ gap: 3, pb: 2 }}>
      <Stack
        sx={{
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          gap: 2,
        }}
      >
        <Stack sx={{ gap: 0.5 }}>
          <Typography
            variant="globalXL"
            sx={{
              fontWeight: 'fontWeightBold',
              color: theme => theme.palette.new.text.neutral.default,
            }}
          >
            {t('status.title')}
          </Typography>
          <Typography
            variant="globalS"
            sx={{ color: theme => theme.palette.new.text.neutral.lighter }}
          >
            {t('status.subtitle_line1')}
          </Typography>
        </Stack>
        <HuPills
          hasIcon={false}
          size="medium"
          label={planStatusLabel}
          type={PLAN_STATUS_PILL_TYPE[vm.planStatus]}
          sx={{ flexShrink: 0 }}
        />
      </Stack>

      <Stack
        sx={{
          display: 'grid',
          gridTemplateColumns: {
            xs: '1fr',
            sm: 'repeat(2, minmax(0, 1fr))',
            lg: 'repeat(4, minmax(0, 1fr))',
          },
          gap: 1.75,
        }}
      >
        {vm.summaryCards.map(card => {
          const Icon = SUMMARY_ICON_BY_KIND[card.kind];
          const gridSpan = 'gridColumnSpan' in card ? card.gridColumnSpan : 1;
          return (
            <HuCardContainer
              key={card.kind}
              fullWidth
              padding={0}
              sx={{
                minWidth: 0,
                height: '100%',
                ...SUMMARY_CARD_SX_BY_GRID_SPAN[gridSpan],
              }}
            >
              <Stack sx={{ p: 2, gap: 0.75 }}>
                <Stack
                  sx={{
                    display: 'inline-flex',
                    color: theme => theme.palette.new.text.neutral.lighter,
                  }}
                >
                  <Icon
                    size={20}
                    stroke={1.8}
                  />
                </Stack>
                <Typography
                  variant="globalXXS"
                  sx={{
                    textTransform: 'uppercase',
                    letterSpacing: 1.6,
                    color: theme => theme.palette.new.text.neutral.lighter,
                    fontWeight: 'fontWeightSemiBold',
                  }}
                >
                  {card.label}
                </Typography>
                {card.kind === 'balance' ? (
                  <CurrencyAmount
                    value={card.balance}
                    variant="globalL"
                    sx={{
                      color: theme => theme.palette.new.text.neutral.default,
                      fontWeight: 'fontWeightBold',
                      lineHeight: 1.1,
                    }}
                  />
                ) : (
                  <Typography
                    variant="globalL"
                    sx={{
                      color: theme => theme.palette.new.text.neutral.default,
                      fontWeight: 'fontWeightBold',
                      lineHeight: 1.1,
                    }}
                  >
                    {card.value}
                  </Typography>
                )}
                <Typography
                  variant="globalS"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                  }}
                >
                  {card.caption}
                </Typography>
              </Stack>
            </HuCardContainer>
          );
        })}
      </Stack>

      <Stack
        sx={{
          display: 'grid',
          gridTemplateColumns: {
            xs: '1fr',
            lg: 'minmax(280px, 1fr) minmax(0, 1.75fr)',
          },
          gap: 2,
        }}
      >
        <Stack sx={{ gap: 2 }}>
          <Stack
            sx={{
              p: 2.5,
              borderRadius: 2.5,
              gap: 2,
              backgroundColor: theme =>
                theme.palette.new.action.button.background.primary.default,
              color: theme =>
                theme.palette.new.action.button.text.primary.default,
              ...microloanCardBorderSx,
            }}
          >
            <Stack sx={{ gap: 0.5 }}>
              <Typography
                variant="globalXXS"
                sx={{
                  textTransform: 'uppercase',
                  letterSpacing: 2,
                  opacity: 0.92,
                  color: theme =>
                    theme.palette.new.action.button.text.primary.default,
                }}
              >
                {t('status.plan_start')}
              </Typography>
              <CurrencyAmount
                value={vm.capitalCredited}
                variant="globalXXL"
                sx={{
                  fontWeight: 'fontWeightBold',
                  lineHeight: 1,
                  color: theme =>
                    theme.palette.new.action.button.text.primary.default,
                }}
              />
            </Stack>
            <Divider
              sx={{
                borderColor: theme => theme.palette.new.border.neutral.brand,
              }}
            />
            <Typography
              variant="globalS"
              sx={{
                color: theme =>
                  theme.palette.new.action.button.text.primary.default,
              }}
            >
              {t('status.plan_start_credited_prefix')}{' '}
              <Typography
                component="span"
                variant="globalS"
                sx={{
                  fontWeight: 'fontWeightBold',
                  color: theme =>
                    theme.palette.new.action.button.text.primary.default,
                }}
              >
                {vm.planStartDateDisplay}
              </Typography>
            </Typography>
          </Stack>

          <HuCardContainer
            fullWidth
            padding={0}
            sx={{ minWidth: 0 }}
          >
            <Stack sx={{ p: 2, gap: 1.75 }}>
              <Typography
                variant="globalM"
                sx={{
                  fontWeight: 'fontWeightBold',
                  color: theme => theme.palette.new.text.neutral.default,
                }}
              >
                {t('status.progress_title')}
              </Typography>
              {vm.planStatus === 'OVERDUE' && vm.overduePaymentsCount > 0 && (
                <Typography
                  variant="globalS"
                  sx={{
                    fontWeight: 'fontWeightSemiBold',
                    color: theme => theme.palette.new.text.feedback.error,
                  }}
                >
                  {formatMicroloanOverdueMessage(
                    t,
                    vm.overduePaymentsCount,
                    Math.max(1, vm.overdueDaysAgo),
                  )}
                </Typography>
              )}
              <Stack sx={{ gap: 0.75 }}>
                <Stack
                  sx={{
                    width: '100%',
                    height: 24,
                    borderRadius: 1.2,
                    backgroundColor: theme =>
                      theme.palette.new.background.elements.grey,
                    border: 1,
                    borderColor: theme =>
                      theme.palette.new.border.neutral.default,
                    overflow: 'hidden',
                  }}
                >
                  <Stack
                    sx={{
                      width: `${vm.progressPercent}%`,
                      height: '100%',
                      backgroundColor: planStyles.progressFill,
                    }}
                  />
                </Stack>
                <Stack
                  sx={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                  }}
                >
                  <Typography
                    variant="globalXS"
                    sx={{
                      color: theme => theme.palette.new.text.neutral.brand,
                    }}
                  >
                    {vm.progressPaidLabel}
                  </Typography>
                  <Typography
                    variant="globalXS"
                    sx={{
                      color: theme => theme.palette.new.text.neutral.lighter,
                    }}
                  >
                    {vm.progressRemainingLabel}
                  </Typography>
                </Stack>
              </Stack>

              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 1,
                  p: 1.25,
                  borderRadius: 1.75,
                  backgroundColor: theme =>
                    theme.palette.new.background.elements.grey,
                }}
              >
                <IconCalendarEvent
                  size={24}
                  stroke={1.8}
                />
                <Typography
                  variant="globalXS"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.default,
                  }}
                >
                  {t(periodicityKey('status.progress_note', vm.periodicity))}
                </Typography>
              </Stack>
            </Stack>
          </HuCardContainer>

          <HistoryLink source="status" />
        </Stack>

        <HuCardContainer
          fullWidth
          padding={0}
          sx={{
            minWidth: 0,
            overflow: 'hidden',
            '& > .MuiCardContent-root': { p: 0 },
          }}
        >
          <Stack sx={{ width: '100%', overflow: 'hidden' }}>
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                p: 2,
              }}
            >
              <Typography
                variant="globalM"
                sx={{
                  fontWeight: 'fontWeightBold',
                  color: theme => theme.palette.new.text.neutral.default,
                }}
              >
                {t('status.schedule_title')}
              </Typography>
              <Typography
                variant="globalS"
                sx={{
                  color: theme => theme.palette.new.text.neutral.brand,
                  fontWeight: 'fontWeightSemiBold',
                }}
              >
                {vm.scheduleTitleSuffix}
              </Typography>
            </Stack>

            <Stack
              sx={{
                flexDirection: 'row',
                px: 2,
                py: 1.25,
                backgroundColor: theme =>
                  theme.palette.new.background.elements.grey,
              }}
            >
              <Typography
                variant="globalXXS"
                sx={{
                  width: '20%',
                  color: theme => theme.palette.new.text.neutral.lighter,
                }}
              >
                {t('status.schedule_week')}
              </Typography>
              <Typography
                variant="globalXXS"
                sx={{
                  width: '38%',
                  color: theme => theme.palette.new.text.neutral.lighter,
                }}
              >
                {t('status.schedule_date')}
              </Typography>
              <Typography
                variant="globalXXS"
                sx={{
                  width: '22%',
                  color: theme => theme.palette.new.text.neutral.lighter,
                }}
              >
                {t('status.schedule_amount')}
              </Typography>
              <Typography
                variant="globalXXS"
                sx={{
                  width: '20%',
                  textAlign: 'right',
                  color: theme => theme.palette.new.text.neutral.lighter,
                }}
              >
                {t('status.schedule_status')}
              </Typography>
            </Stack>

            {vm.scheduleRows.length === 0 && (
              <Stack sx={{ px: 2, py: 3 }}>
                <Typography
                  variant="globalM"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                  }}
                >
                  {t('status.schedule_empty')}
                </Typography>
              </Stack>
            )}
            {vm.scheduleRows.length > 0 &&
              vm.scheduleRows.map((row, index) => (
                <Stack key={row.fee}>
                  {index > 0 && (
                    <Divider
                      sx={{
                        borderColor: theme =>
                          theme.palette.new.border.neutral.divider,
                      }}
                    />
                  )}
                  <Stack
                    sx={theme => ({
                      flexDirection: 'row',
                      alignItems: 'center',
                      px: 2,
                      py: 1.45,
                      ...SCHEDULE_TONE_STYLES[row.tone].rowHighlight(theme),
                    })}
                  >
                    <Stack sx={{ width: '20%' }}>
                      <Stack
                        sx={theme => ({
                          width: 24,
                          height: 24,
                          borderRadius: '50%',
                          display: 'inline-flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          typography: 'globalXS',
                          fontWeight: 'fontWeightBold',
                          ...SCHEDULE_TONE_STYLES[row.tone].circle(theme),
                        })}
                      >
                        {row.fee}
                      </Stack>
                    </Stack>
                    <Typography
                      variant="globalS"
                      sx={{
                        width: '38%',
                        color: theme => theme.palette.new.text.neutral.default,
                      }}
                    >
                      {row.date}
                    </Typography>
                    <Stack
                      sx={{
                        width: '22%',
                        justifyContent: 'flex-start',
                      }}
                    >
                      <CurrencyAmount
                        value={row.amount}
                        variant="globalS"
                        sx={{
                          color: theme =>
                            theme.palette.new.text.neutral.default,
                          fontWeight: 'fontWeightBold',
                        }}
                      />
                    </Stack>
                    <Stack sx={{ width: '20%', textAlign: 'right' }}>
                      <Stack
                        sx={theme => ({
                          display: 'inline-flex',
                          alignItems: 'center',
                          px: 1,
                          py: 0.3,
                          borderRadius: 999,
                          typography: 'globalXS',
                          fontWeight: 'fontWeightSemiBold',
                          ...SCHEDULE_TONE_STYLES[row.tone].pill(theme),
                        })}
                      >
                        {row.status}
                      </Stack>
                    </Stack>
                  </Stack>
                </Stack>
              ))}

            <Divider
              sx={{
                borderColor: theme => theme.palette.new.border.neutral.divider,
              }}
            />
            <Stack
              sx={{
                flexDirection: 'row',
                alignItems: 'center',
                justifyContent: 'space-between',
                gap: 2,
                px: 2,
                py: 1.5,
              }}
            >
              <Stack
                sx={{
                  flexDirection: 'row',
                  alignItems: 'center',
                  gap: 0.25,
                  minWidth: 0,
                  flex: 1,
                }}
              >
                <Typography
                  variant="globalM"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                  }}
                >
                  {t('status.schedule_total')}
                </Typography>
                <IconButton
                  type="button"
                  size="small"
                  aria-label={t('confirm.credit_details_info_aria')}
                  onClick={() => setCreditDetailsOpen(true)}
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                    p: 0.25,
                    flexShrink: 0,
                  }}
                >
                  <IconInfoCircle
                    size={18}
                    stroke={2}
                  />
                </IconButton>
              </Stack>
              <CurrencyAmount
                value={vm.scheduleFooterTotal}
                variant="globalL"
                sx={{
                  color: theme => theme.palette.new.text.neutral.default,
                  fontWeight: 'fontWeightBold',
                  flexShrink: 0,
                }}
              />
            </Stack>
          </Stack>
        </HuCardContainer>
      </Stack>

      <CreditDetailsModal
        open={creditDetailsOpen}
        onClose={() => setCreditDetailsOpen(false)}
        principal={vm.creditDetailsPrincipal}
        totalInterests={vm.creditDetailsTotalInterests}
        totalToPay={vm.creditDetailsTotalToPay}
        catPercent={vm.disclosureCatPercent}
        tnaPercent={vm.disclosureTnaPercent}
        installmentsCount={vm.creditDetailsInstallmentsCount}
        periodicity={vm.periodicity}
      />

      <LegalNote
        sx={{ pt: 2, pb: 1 }}
        termsStrategy="status"
      />
    </Stack>
  );
};

export default ActivePlanStatusContent;
