import { useEffect } from 'react';

import Divider from '@material-hu/mui/Divider';
import Stack from '@material-hu/mui/Stack';
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 { useAuth } from 'src/contexts/JWTContext';
import { type LokaliseTFunction, useLokaliseTranslation } from 'src/utils/i18n';
import { getCurrentLocale } from 'src/utils/locale';

import {
  FINISHED_LOAN_STATUS_LABEL_KEYS,
  FINISHED_LOAN_STATUS_PILL_TYPE,
} from '../constants';
import { useCollaboratorFinishedLoans } from '../hooks/useCollaboratorFinishedLoans';
import { useCollaboratorStatus } from '../hooks/useCollaboratorStatus';
import { trackLoanHistoryViewed } from '../track';
import { formatCloseDate } from '../utils/formatters';
import { periodicityKey } from '../utils/periodicity';

import { CurrencyAmount } from './CurrencyAmount';
import { ExclusiveBenefitPill } from './ExclusiveBenefitPill';
import StatusLoadingState from './status/StatusLoadingState';

type TableHeaderProps = {
  t: LokaliseTFunction;
};

const TableHeaderRow = ({ t }: TableHeaderProps) => (
  <Stack
    sx={{
      flexDirection: 'row',
      px: 2,
      py: 1.25,
      backgroundColor: theme => theme.palette.new.background.elements.grey,
    }}
  >
    <Typography
      variant="globalXXS"
      sx={{
        width: '22%',
        textTransform: 'uppercase',
        letterSpacing: 1.6,
        color: theme => theme.palette.new.text.neutral.lighter,
      }}
    >
      {t('history.column_amount')}
    </Typography>
    <Typography
      variant="globalXXS"
      sx={{
        width: '18%',
        textTransform: 'uppercase',
        letterSpacing: 1.6,
        color: theme => theme.palette.new.text.neutral.lighter,
      }}
    >
      {t('history.column_payments')}
    </Typography>
    <Typography
      variant="globalXXS"
      sx={{
        width: '32%',
        textTransform: 'uppercase',
        letterSpacing: 1.6,
        color: theme => theme.palette.new.text.neutral.lighter,
      }}
    >
      {t('history.column_close_date')}
    </Typography>
    <Typography
      variant="globalXXS"
      sx={{
        width: '28%',
        textAlign: 'right',
        textTransform: 'uppercase',
        letterSpacing: 1.6,
        color: theme => theme.palette.new.text.neutral.lighter,
      }}
    >
      {t('history.column_status')}
    </Typography>
  </Stack>
);

const History = () => {
  const { t } = useLokaliseTranslation('loans');
  const { user } = useAuth();
  // useFormatDate() is bypassed because formatPaymentDateMX renders short-month dates pinned to America/Mexico_City, which the hook does not expose.
  const locale = getCurrentLocale(user);
  const {
    hasOffer,
    hasPayments,
    isReady: isStatusReady,
  } = useCollaboratorStatus();
  const hasOfferOrPayments = hasOffer || hasPayments;
  const {
    data: finishedLoans,
    isLoading: finishedLoansLoading,
    isError: finishedLoansError,
  } = useCollaboratorFinishedLoans();

  useEffect(() => {
    trackLoanHistoryViewed();
  }, []);

  if (!isStatusReady || finishedLoansLoading) {
    return <StatusLoadingState />;
  }

  const simpleHeaderNode = hasOfferOrPayments && (
    <Stack sx={{ gap: 2 }}>
      <ExclusiveBenefitPill />
      <Typography
        variant="globalXL"
        sx={{
          fontWeight: 'fontWeightBold',
          color: theme => theme.palette.new.text.neutral.default,
        }}
      >
        {t('history.title')}
      </Typography>
    </Stack>
  );

  const noOfferHeaderNode = !hasOfferOrPayments && (
    <Stack sx={{ gap: 0.5 }}>
      <Typography
        variant="globalXL"
        sx={{
          fontWeight: 'fontWeightBold',
          color: theme => theme.palette.new.text.neutral.default,
        }}
      >
        {t('history.no_offer_title')}
      </Typography>
      <Typography
        variant="globalS"
        sx={{ color: theme => theme.palette.new.text.neutral.lighter }}
      >
        {t('history.no_offer_subtitle')}
      </Typography>
    </Stack>
  );

  const rows = finishedLoans ?? [];

  return (
    <Stack sx={{ width: '100%', gap: 3 }}>
      {simpleHeaderNode}
      {noOfferHeaderNode}

      <Stack sx={{ gap: 1.5 }}>
        {!hasOfferOrPayments && (
          <Typography
            variant="globalM"
            sx={{
              fontWeight: 'fontWeightBold',
              color: theme => theme.palette.new.text.neutral.default,
            }}
          >
            {t('history.table_title')}
          </Typography>
        )}

        <HuCardContainer
          fullWidth
          padding={0}
          sx={{
            minWidth: 0,
            overflow: 'hidden',
            '& > .MuiCardContent-root': { p: 0 },
          }}
        >
          <Stack sx={{ width: '100%', overflow: 'hidden' }}>
            <TableHeaderRow t={t} />

            {finishedLoansError && (
              <Stack sx={{ px: 2, py: 3 }}>
                <Typography
                  variant="globalM"
                  sx={{ color: theme => theme.palette.new.text.feedback.error }}
                >
                  {t('history.load_error')}
                </Typography>
              </Stack>
            )}

            {!finishedLoansError && rows.length === 0 && (
              <Stack sx={{ px: 2, py: 3 }}>
                <Typography
                  variant="globalM"
                  sx={{
                    color: theme => theme.palette.new.text.neutral.lighter,
                  }}
                >
                  {t('history.empty')}
                </Typography>
              </Stack>
            )}

            {!finishedLoansError &&
              rows.map((row, index) => (
                <Stack key={row.id}>
                  {index > 0 && (
                    <Divider
                      sx={{
                        borderColor: theme =>
                          theme.palette.new.border.neutral.divider,
                      }}
                    />
                  )}
                  <Stack
                    sx={{
                      flexDirection: 'row',
                      alignItems: 'center',
                      px: 2,
                      py: 1.5,
                    }}
                  >
                    <Stack sx={{ width: '22%' }}>
                      <CurrencyAmount
                        value={row.amount}
                        variant="globalS"
                        sx={{
                          color: theme =>
                            theme.palette.new.text.neutral.default,
                          fontWeight: 'fontWeightBold',
                        }}
                      />
                    </Stack>
                    <Typography
                      variant="globalS"
                      sx={{
                        width: '18%',
                        color: theme => theme.palette.new.text.neutral.default,
                      }}
                    >
                      {t(
                        periodicityKey(
                          'history.payments_count',
                          row.periodicity,
                        ),
                        { count: row.weeks },
                      )}
                    </Typography>
                    <Typography
                      variant="globalS"
                      sx={{
                        width: '32%',
                        color: theme => theme.palette.new.text.neutral.default,
                      }}
                    >
                      {formatCloseDate(row.closeDate, locale)}
                    </Typography>
                    <Stack
                      sx={{
                        width: '28%',
                        alignItems: 'flex-end',
                      }}
                    >
                      <HuPills
                        hasIcon={false}
                        size="small"
                        type={FINISHED_LOAN_STATUS_PILL_TYPE[row.status]}
                        label={t(FINISHED_LOAN_STATUS_LABEL_KEYS[row.status])}
                      />
                    </Stack>
                  </Stack>
                </Stack>
              ))}
          </Stack>
        </HuCardContainer>
      </Stack>
    </Stack>
  );
};

export default History;
