'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Skeleton, Stack, Typography } from '@mui/material';
import { AppLink, EmptyState, ErrorState, Money, PaymentStatusBadge, SurfaceCard } from '@/components';
import { ROUTES } from '@/constants';
import { formatShamsiDateTime } from '@/utils';
import { useWalletHistoryRows } from './useWalletHistoryRows';

/**
 * The wallet «پرداخت‌ها» section — every card + BNPL payment (down-payment) the customer made, newest
 * first, with a deep-link to the booking. For a card-paying customer (the default path) this is what
 * finally fills the previously permanently-empty Wallet tab.
 */
const WalletPaymentHistory: FunctionComponent = () => {
  const t = useTranslations('bnpl');
  const tc = useTranslations('common');
  const locale = useLocale();
  const { rows, isLoading, bothErrored, refetch } = useWalletHistoryRows();

  if (isLoading) {
    return (
      <Stack sx={{ gap: 1.5 }}>
        <Skeleton variant="rounded" height={72} />
        <Skeleton variant="rounded" height={72} />
      </Stack>
    );
  }
  if (bothErrored) {
    return <ErrorState message={t('wallet_error_body')} retryLabel={tc('retry')} onRetry={refetch} />;
  }
  if (rows.length === 0) {
    return <EmptyState icon="payment" title={t('history_empty_title')} body={t('history_empty_body')} />;
  }

  return (
    <Stack sx={{ gap: 1.5 }}>
      {rows.map((row) => (
        <SurfaceCard key={row.key} padding="sm">
          <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', gap: 2 }}>
            <Stack sx={{ gap: 0.25 }}>
              <Money amountIrr={row.amountIrr} tone="emphasis" size="sm" sx={{ fontWeight: 700 }} />
              <Typography variant="caption" sx={{ color: 'text.secondary' }}>
                {formatShamsiDateTime(row.createdAt, locale)}
              </Typography>
            </Stack>
            <Stack sx={{ alignItems: 'flex-end', gap: 0.5 }}>
              <PaymentStatusBadge status={row.status} />
              {row.bookingId != null ? (
                <AppLink to={`/${locale}${ROUTES.BOOKINGS}/${row.bookingId}`} sx={{ fontSize: '0.75rem' }}>
                  {t('history_view_booking')}
                </AppLink>
              ) : null}
            </Stack>
          </Stack>
        </SurfaceCard>
      ))}
    </Stack>
  );
};

export default WalletPaymentHistory;
