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

/**
 * The wallet «رسیدها» section — no receipts endpoint exists; every succeeded, booking-linked payment
 * (card or BNPL down-payment) derives its invoice deep-link client-side (a UI join over the same rows the
 * «پرداخت‌ها» tab renders, filtered to `succeeded` + a known `bookingId` — no money math).
 */
const WalletReceipts: FunctionComponent = () => {
  const t = useTranslations('bnpl');
  const tp = useTranslations('payment');
  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} />
      </Stack>
    );
  }
  if (bothErrored) {
    return <ErrorState message={t('wallet_error_body')} retryLabel={tc('retry')} onRetry={refetch} />;
  }

  const receipts = rows.filter((row) => row.status === 'succeeded' && row.bookingId != null);

  if (receipts.length === 0) {
    return <EmptyState icon="document" title={t('receipts_empty_title')} body={t('receipts_empty_body')} />;
  }

  return (
    <Stack sx={{ gap: 1.5 }}>
      {receipts.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>
            <AppButton
              variant="outlined"
              color="primary"
              size="small"
              startIcon="document"
              to={`/${locale}${bookingInvoicePath(row.bookingId as number)}`}
            >
              {tp('view_invoice_cta')}
            </AppButton>
          </Stack>
        </SurfaceCard>
      ))}
    </Stack>
  );
};

export default WalletReceipts;
