'use client';
import { FunctionComponent } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Box, Chip, Paper, Stack, Typography } from '@mui/material';
import { formatShamsiDate } from '@/utils';
import type { CenterInvoice } from '@/services/partnerCenter/types';
import AppButton from '../common/AppButton';
import Money from '../common/Money';
import PriceBreakdown, { type PriceBreakdownRow } from '../PriceBreakdown';

export interface PartnerSettlementRowProps {
  invoice: CenterInvoice;
  onDownloadPdf?: (invoice: CenterInvoice) => void;
  downloadError?: boolean;
  onRetryDownload?: (invoice: CenterInvoice) => void;
}

/**
 * One per-booking commission-invoice row in a merchant-of-record center's settlement view. The reconciling
 * breakdown is **platform commission + BNPL commission + VAT = total** (VAT on the commission line only,
 * never the gross service fee — `grossIrr` is shown as context, not summed). Money is served IRR
 * digit-strings formatted to Toman via the shared util. The سامانه مودیان reference + a signed-URL PDF
 * download round it out. Enum/label copy comes from the `partner` namespace.
 * @component PartnerSettlementRow
 */
const PartnerSettlementRow: FunctionComponent<PartnerSettlementRowProps> = ({ invoice, onDownloadPdf, downloadError, onRetryDownload }) => {
  const t = useTranslations('partner');
  const locale = useLocale();

  const rows: PriceBreakdownRow[] = [
    { key: 'commission', label: t('invoice_row_commission'), amountIrr: invoice.platformCommissionIrr },
  ];
  if (invoice.bnplCommissionIrr) {
    rows.push({ key: 'bnpl_commission', label: t('invoice_row_bnpl_commission'), amountIrr: invoice.bnplCommissionIrr });
  }
  rows.push({ key: 'vat', label: t('invoice_row_vat'), amountIrr: invoice.vatIrr });

  return (
    <Paper
      elevation={0}
      data-invoice-id={invoice.id}
      sx={{ p: 2, borderRadius: 2, border: '1px solid', borderColor: 'divider' }}
    >
      <Stack direction="row" sx={{ gap: 2, alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', mb: 1.5 }}>
        <Box>
          <Typography variant="subtitle2" sx={{ fontWeight: 800 }}>
            {t('invoice_number', { number: invoice.invoiceNumber })}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('settlement_col_booking')} #{invoice.bookingId} · {formatShamsiDate(invoice.issuedAt, locale)}
          </Typography>
        </Box>
        <Stack sx={{ alignItems: 'flex-end' }}>
          <Typography variant="caption" sx={{ color: 'text.secondary' }}>
            {t('invoice_row_gross')}
          </Typography>
          <Money amountIrr={invoice.grossIrr} size="sm" sx={{ fontWeight: 700 }} />
        </Stack>
      </Stack>

      <PriceBreakdown rows={rows} totalLabel={t('invoice_row_total')} totalAmountIrr={invoice.totalIrr} />

      <Stack direction="row" sx={{ gap: 1, alignItems: 'center', justifyContent: 'space-between', mt: 1.5, flexWrap: 'wrap' }}>
        <Chip
          size="small"
          variant="outlined"
          label={
            invoice.moadianReferenceNumber
              ? `${t('settlement_moadian_ref')}: ${invoice.moadianReferenceNumber}`
              : t('settlement_moadian_pending')
          }
        />
        {invoice.pdfUrl ? (
          downloadError ? (
            <AppButton variant="outlined" color="error" startIcon="refresh" onClick={() => onRetryDownload?.(invoice)}>
              {t('invoice_pdf_error')}
            </AppButton>
          ) : (
            <AppButton variant="outlined" color="primary" startIcon="download" onClick={() => onDownloadPdf?.(invoice)}>
              {t('invoice_download')}
            </AppButton>
          )
        ) : null}
      </Stack>
    </Paper>
  );
};

export default PartnerSettlementRow;
