'use client';
import { Suspense } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { Alert, Box, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AppButton, AppLoading } from '@/components';
import {
  AdminEmptyState,
  AdminErrorState,
  AdminPageHeader,
  AdminPager,
  PartnerSettlementRow,
} from '@/components/admin';
import { useAdminListState } from '@/hooks';
import { formatIrrToToman, formatShamsiDate, toCsv } from '@/utils';
import { PARTNER_PAGE_SIZE } from '@/services/partnerCenter/constants';
import type { CenterInvoice } from '@/services/partnerCenter/types';
import { useMyPartnerCenter, useMySettlement } from '@/services/partnerCenter';

const NO_FILTERS: Record<string, never> = {};

/**
 * Partner portal — settlement & invoices (f15). **Merchant-of-record drives the whole view**: a non-MoR
 * center settles through Balinyaar and issues no commission invoices, so it sees only the
 * `settlement_not_mor` state (no table). A MoR center sees its per-booking commission invoices
 * (`PartnerSettlementRow`, VAT-on-commission-only breakdown) with the masked settlement IBAN and a
 * signed-URL PDF that opens in a new tab, plus a client-side CSV export of the currently loaded page. Read-
 * only. `useSearchParams` (inside `useAdminListState`) needs a `<Suspense>` boundary.
 */
export default function PartnerSettlementPage() {
  return (
    <Suspense fallback={<AppLoading />}>
      <PartnerSettlementScreen />
    </Suspense>
  );
}

/** Already-translated CSV column headers, keyed to the row shape `exportInvoicesCsv` builds below. */
interface InvoiceCsvHeaders {
  invoiceNumber: string;
  bookingId: string;
  gross: string;
  commission: string;
  vat: string;
  total: string;
  issuedAt: string;
}

/** Builds + triggers the download of a CSV of the currently loaded invoices page (no new fetch). */
function exportInvoicesCsv(invoices: CenterInvoice[], locale: string, headers: InvoiceCsvHeaders): void {
  const csv = toCsv(
    invoices.map((inv) => ({
      invoiceNumber: inv.invoiceNumber,
      bookingId: inv.bookingId,
      gross: formatIrrToToman(inv.grossIrr, locale),
      commission: formatIrrToToman(inv.platformCommissionIrr, locale),
      vat: formatIrrToToman(inv.vatIrr, locale),
      total: formatIrrToToman(inv.totalIrr, locale),
      issuedAt: formatShamsiDate(inv.issuedAt, locale),
    })),
    [
      { key: 'invoiceNumber', label: headers.invoiceNumber },
      { key: 'bookingId', label: headers.bookingId },
      { key: 'gross', label: headers.gross },
      { key: 'commission', label: headers.commission },
      { key: 'vat', label: headers.vat },
      { key: 'total', label: headers.total },
      { key: 'issuedAt', label: headers.issuedAt },
    ],
  );
  // UTF-8 BOM so Excel renders Persian text correctly.
  const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'settlement.csv';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

function PartnerSettlementScreen() {
  const t = useTranslations('partner');
  const ta = useTranslations('admin');
  const locale = useLocale();
  const center = useMyPartnerCenter();
  // Page-only URL sync (no filters on this list) — survives refresh/back like the other portal worklists.
  const { page, goToPage } = useAdminListState<Record<string, never>>({
    parse: () => NO_FILTERS,
    serialize: () => ({}),
    empty: NO_FILTERS,
  });
  // Called unconditionally (rules of hooks); only rendered for a merchant-of-record center.
  const settlement = useMySettlement(page);

  if (center.isLoading) {
    return (
      <Stack sx={{ gap: 3 }}>
        <Skeleton variant="rounded" height={72} />
        <Skeleton variant="rounded" height={200} />
      </Stack>
    );
  }

  if (center.isError || !center.data) {
    return <AdminErrorState message={ta('error_generic')} retryLabel={ta('retry')} onRetry={() => center.refetch()} />;
  }

  const c = center.data;

  if (!c.isMerchantOfRecord) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
        <AdminPageHeader title={t('settlement_title')} />
        <Alert severity="info" sx={{ borderRadius: 'var(--bal-radius-md)' }}>
          {t('settlement_not_mor')}
        </Alert>
      </Box>
    );
  }

  const invoices = settlement.data?.items ?? [];
  const pageCount = Math.max(1, Math.ceil((settlement.data?.total ?? 0) / PARTNER_PAGE_SIZE));

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
      <AdminPageHeader
        title={t('settlement_title')}
        actions={
          <AppButton
            variant="outlined"
            color="primary"
            startIcon="download"
            disabled={settlement.isLoading || invoices.length === 0}
            onClick={() =>
              exportInvoicesCsv(invoices, locale, {
                invoiceNumber: t('csv_col_invoice_number'),
                bookingId: t('csv_col_booking_id'),
                gross: t('csv_col_gross'),
                commission: t('csv_col_commission'),
                vat: t('csv_col_vat'),
                total: t('csv_col_total'),
                issuedAt: t('csv_col_issued_at'),
              })
            }
          >
            {t('settlement_export_csv')}
          </AppButton>
        }
      />

      <Paper elevation={0} sx={{ p: 2, borderRadius: 'var(--bal-radius-md)', border: '1px solid', borderColor: 'divider' }}>
        <Stack direction="row" sx={{ gap: 2, alignItems: 'baseline', justifyContent: 'space-between', flexWrap: 'wrap' }}>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('settlement_iban')}
          </Typography>
          <Typography component="span" dir="ltr" variant="body2" sx={{ fontWeight: 500, fontFamily: 'monospace' }}>
            {c.settlementIbanMasked ?? '—'}
          </Typography>
        </Stack>
      </Paper>

      {settlement.isLoading ? (
        <Stack sx={{ gap: 2 }}>
          {[0, 1].map((k) => (
            <Skeleton key={k} variant="rounded" height={200} />
          ))}
        </Stack>
      ) : settlement.isError ? (
        <AdminErrorState message={ta('error_generic')} retryLabel={ta('retry')} onRetry={() => settlement.refetch()} />
      ) : invoices.length === 0 ? (
        <AdminEmptyState icon="payment" title={t('settlement_empty')} />
      ) : (
        <Stack sx={{ gap: 2 }}>
          {invoices.map((inv) => (
            <PartnerSettlementRow
              key={inv.id}
              invoice={inv}
              onDownloadPdf={(i) => {
                if (i.pdfUrl) window.open(i.pdfUrl, '_blank', 'noopener');
              }}
            />
          ))}
        </Stack>
      )}

      <AdminPager
        page={page}
        pageCount={pageCount}
        onPrev={() => goToPage(Math.max(1, page - 1))}
        onNext={() => goToPage(Math.min(pageCount, page + 1))}
        prevLabel={ta('prev_page')}
        nextLabel={ta('next_page')}
        indicator={ta('page_indicator', { page, total: pageCount })}
      />
    </Box>
  );
}
