'use client';
import { useLocale, useTranslations } from 'next-intl';
import { useParams, useRouter } from 'next/navigation';
import { Divider, GlobalStyles, Paper, Skeleton, Stack, Typography } from '@mui/material';
import { AppButton, AppIcon, PriceBreakdown, StatusChip, type StatusKind } from '@/components';
import { ROUTES } from '@/constants';
import { ApiError } from '@/lib/api/errors';
import { formatShamsiDate, localeTag, parseIrr } from '@/utils';
import { useInvoice } from '@/services/payment';
import type { MoadianStatus } from '@/services/payment/types';

/** The printable region — everything else is hidden by the print rules below. */
const PRINT_AREA_CLASS = 'invoice-print-area';

// مودیان registration is a backend concern — surfaced strictly read-only (contract exposes the state).
const MOADIAN_KIND: Record<MoadianStatus, StatusKind> = {
  pending: 'pending',
  submitted: 'info',
  registered: 'verified',
  failed: 'rejected',
};

/**
 * The booking's commission invoice (b11 `GET invoices/{bookingId}`): header (`invoiceNumber`, Shamsi
 * issue date), the reconciling lines with the **VAT-on-commission** line explicitly labelled (product
 * rule: VAT is on Balinyaar's commission — the taxable supply — never the nurse's earnings), and the
 * مودیان state read-only. Downloads the served `pdfUrl` when present; otherwise prints a clean receipt
 * (`window.print()` + a print-scoped visibility rule). Every figure via the money util — no float math;
 * the service line is the exact integer remainder of served amounts (gross − commission − VAT).
 */
export default function BookingInvoicePage() {
  const t = useTranslations('payment');
  const tc = useTranslations('common');
  const locale = useLocale();
  const router = useRouter();
  const params = useParams<{ id: string }>();
  const bookingId = Number(params.id);
  const validId = Number.isInteger(bookingId) && bookingId > 0;

  const { data: invoice, isLoading, error, refetch } = useInvoice(validId ? bookingId : undefined);

  // A malformed id can never load — navigation, not a retry (a manual refetch() bypasses `enabled`).
  if (!validId) {
    return (
      <Paper elevation={0} sx={{ p: 4, textAlign: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
        <Stack sx={{ gap: 1.5, alignItems: 'center' }}>
          <AppIcon icon="error" size={44} color="var(--bal-error)" />
          <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
            {t('error_title')}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {t('invalid_link_body')}
          </Typography>
          <AppButton variant="contained" onClick={() => router.push(`/${locale}${ROUTES.BOOKINGS}`)}>
            {t('view_booking')}
          </AppButton>
        </Stack>
      </Paper>
    );
  }

  if (isLoading) {
    return (
      <Stack sx={{ gap: 2 }}>
        <Skeleton variant="text" width="40%" height={36} />
        <Skeleton variant="rounded" height={120} />
        <Skeleton variant="rounded" height={200} />
      </Stack>
    );
  }

  if (!invoice) {
    const notIssued = error instanceof ApiError && error.status === 404;
    return (
      <Paper elevation={0} sx={{ p: 4, textAlign: 'center', border: '1px solid', borderColor: 'divider', borderRadius: 2 }}>
        <Stack sx={{ gap: 1.5, alignItems: 'center' }}>
          <AppIcon icon={notIssued ? 'document' : 'error'} size={44} color={notIssued ? 'var(--bal-warning)' : 'var(--bal-error)'} />
          <Typography variant="subtitle1" sx={{ fontWeight: 700 }}>
            {notIssued ? t('invoice_not_issued_title') : t('error_title')}
          </Typography>
          <Typography variant="body2" sx={{ color: 'text.secondary' }}>
            {notIssued ? t('invoice_not_issued_body') : t('error_body')}
          </Typography>
          {notIssued ? (
            <AppButton variant="contained" onClick={() => router.push(`/${locale}${ROUTES.BOOKINGS}/${bookingId}`)}>
              {t('view_booking')}
            </AppButton>
          ) : (
            <AppButton variant="contained" onClick={() => refetch()}>
              {tc('retry')}
            </AppButton>
          )}
        </Stack>
      </Paper>
    );
  }

  // The receipt must print on paper colors: the tokens are attribute-driven, so a dark-scheme user
  // would otherwise print cream-on-dark. Flip to the light tokens for the print dialog and restore
  // after it closes (afterprint) — no hard-coded colors, the same token system does the work.
  const handlePrint = () => {
    const root = document.documentElement;
    const previous = root.getAttribute('data-mui-color-scheme');
    if (previous === 'dark') {
      const restore = () => {
        root.setAttribute('data-mui-color-scheme', previous);
        window.removeEventListener('afterprint', restore);
      };
      window.addEventListener('afterprint', restore);
      root.setAttribute('data-mui-color-scheme', 'light');
    }
    window.print();
  };

  // Display rows from served amounts only, integer-safe: the service line is the exact remainder, so
  // service + commission + VAT reconciles to the gross total by construction.
  const serviceIrr = (
    parseIrr(invoice.grossIrr) - parseIrr(invoice.platformCommissionIrr) - parseIrr(invoice.vatIrr)
  ).toString();
  // maximumFractionDigits: the default (0) would silently round a fractional served rate (e.g. 9.5%).
  const vatPercent = new Intl.NumberFormat(localeTag(locale), {
    style: 'percent',
    maximumFractionDigits: 2,
  }).format(invoice.vatRate);

  return (
    <Stack sx={{ gap: 2 }}>
      <GlobalStyles
        styles={{
          '@media print': {
            'body *': { visibility: 'hidden' },
            [`.${PRINT_AREA_CLASS}, .${PRINT_AREA_CLASS} *`]: { visibility: 'visible' },
            [`.${PRINT_AREA_CLASS}`]: { position: 'absolute', top: 0, insetInlineStart: 0, width: '100%' },
          },
        }}
      />

      <Paper
        elevation={0}
        className={PRINT_AREA_CLASS}
        sx={{ p: 3, border: '1px solid', borderColor: 'divider', borderRadius: 2 }}
      >
        <Stack sx={{ gap: 2 }}>
          <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', gap: 2 }}>
            <Typography variant="h6" component="h1">
              {t('invoice_title')}
            </Typography>
            {/* The issuer line uses the product spelling «بالین‌یار» — fa `common.brand` currently reads
                «بلینیار» (the auth wordmark); a fiscal document must match the product/docs spelling. */}
            <Typography variant="subtitle2" sx={{ color: 'var(--bal-primary)', fontWeight: 700 }}>
              {t('issuer_platform')}
            </Typography>
          </Stack>
          <Divider />

          <Stack sx={{ gap: 0.75 }}>
            <MetaRow label={t('invoice_number_label')} value={invoice.invoiceNumber} ltr />
            <MetaRow label={t('invoice_issued_at')} value={formatShamsiDate(invoice.issuedAt, locale)} />
          </Stack>

          <PriceBreakdown
            rows={[
              { key: 'service_cost', label: t('row_service_cost'), amountIrr: serviceIrr },
              { key: 'commission', label: t('row_commission'), amountIrr: invoice.platformCommissionIrr },
              {
                key: 'vat',
                label: `${t('invoice_vat_on_commission')} (${vatPercent})`,
                amountIrr: invoice.vatIrr,
              },
            ]}
            totalLabel={t('row_total')}
            totalAmountIrr={invoice.grossIrr}
          />

          {invoice.moadianStatus ? (
            <Stack direction="row" sx={{ justifyContent: 'space-between', alignItems: 'center', gap: 2 }}>
              <Typography variant="body2" sx={{ color: 'text.secondary' }}>
                {t('moadian_label')}
              </Typography>
              <StatusChip status={MOADIAN_KIND[invoice.moadianStatus]} label={t(`moadian_${invoice.moadianStatus}`)} />
            </Stack>
          ) : null}
        </Stack>
      </Paper>

      <Stack sx={{ gap: 1 }}>
        {invoice.pdfUrl ? (
          <AppButton color="primary" variant="contained" startIcon="document" href={invoice.pdfUrl} openInNewTab>
            {t('download_invoice')}
          </AppButton>
        ) : (
          <AppButton color="primary" variant="contained" startIcon="document" onClick={handlePrint}>
            {t('print_invoice')}
          </AppButton>
        )}
        <AppButton variant="text" onClick={() => router.push(`/${locale}${ROUTES.BOOKINGS}/${bookingId}`)}>
          {t('view_booking')}
        </AppButton>
      </Stack>
    </Stack>
  );
}

function MetaRow({ label, value, ltr }: { label: string; value: string; ltr?: boolean }) {
  return (
    <Stack direction="row" sx={{ justifyContent: 'space-between', gap: 2 }}>
      <Typography variant="body2" sx={{ color: 'text.secondary' }}>
        {label}
      </Typography>
      <Typography variant="body2" sx={{ fontWeight: 500 }} dir={ltr ? 'ltr' : undefined}>
        {value}
      </Typography>
    </Stack>
  );
}
