'use client';
import { useState } from 'react';
import { useTranslations } from 'next-intl';
import { Alert, Box, Paper, Skeleton, Stack, Typography } from '@mui/material';
import {
  AdminEmptyState,
  AdminErrorState,
  AdminPageHeader,
  AdminPager,
  PartnerSettlementRow,
} from '@/components/admin';
import { PARTNER_PAGE_SIZE } from '@/services/partnerCenter/constants';
import { useMyPartnerCenter, useMySettlement } from '@/services/partnerCenter';

/**
 * 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. Read-only.
 */
export default function PartnerSettlementPage() {
  const t = useTranslations('partner');
  const ta = useTranslations('admin');
  const center = useMyPartnerCenter();
  const [page, setPage] = useState(1);
  // 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: 2 }}>
          {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')} />

      <Paper elevation={0} sx={{ p: 2, borderRadius: 2, 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={() => setPage((p) => Math.max(1, p - 1))}
        onNext={() => setPage((p) => Math.min(pageCount, p + 1))}
        prevLabel={ta('prev_page')}
        nextLabel={ta('next_page')}
        indicator={ta('page_indicator', { page })}
      />
    </Box>
  );
}
