import { useQuery } from '@tanstack/react-query';
import { api } from '../lib/api';
import type { ApiResponse } from '../lib/api';
import Modal from './ui/Modal';
import { formatDate, formatRial } from '../lib/utils';

interface InvoiceItem { uuid: string; title: string; quantity: number; total_rials: number; patient_rials: number }
interface Invoice {
  uuid: string; status: string; issued_at: number; total_rials: number;
  base_insurance_rials: number; supplementary_rials: number; patient_rials: number;
  items: InvoiceItem[];
}

const STATUS_LABEL: Record<string, string> = { paid: 'پرداخت شده', finalized: 'بدهکار', draft: 'پیش‌نویس', void: 'باطل' };

/** A titled table block — mirrors tauri InvoiceSummary `SectionTable`. */
function SectionTable({ title, cols, rows }: { title: string; cols: string[]; rows: React.ReactNode[][] }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--text)', marginBottom: 12 }}>{title}</div>
      <div style={{ border: '1px solid var(--border)', borderRadius: 8, overflow: 'hidden' }}>
        <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
          <thead>
            <tr>
              {cols.map((c, i) => (
                <th key={i} style={{ textAlign: 'center', fontWeight: 600, padding: '12px 16px', background: 'var(--info-bg, #ebf5ff)', borderBottom: '1px solid var(--border)', color: 'var(--text-2)' }}>{c}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((row, i) => (
              <tr key={i} style={{ background: i % 2 === 1 ? 'var(--surface-2)' : 'transparent' }}>
                {row.map((cell, j) => (
                  <td key={j} style={{ textAlign: 'center', padding: '12px 16px', borderBottom: i === rows.length - 1 ? 'none' : '1px solid var(--border)', color: 'var(--text)' }}>{cell}</td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/** خلاصه فاکتور — invoice summary, ported pixel-for-pixel from tauri InvoiceSummary. */
export default function InvoiceSummaryModal({ invoiceUuid, onClose }: { invoiceUuid: string | null; onClose: () => void }) {
  const { data, isLoading } = useQuery<ApiResponse<any>>({
    queryKey: ['invoice', invoiceUuid],
    queryFn: () => api.get(`/api/v1/billing/invoices/${invoiceUuid}`),
    enabled: !!invoiceUuid,
  });
  // billing show wraps as { data: { data: invoice } }
  const inv = ((data?.data as any)?.data ?? data?.data ?? null) as Invoice | null;

  const paid = inv?.status === 'paid';
  const remaining = inv ? (paid ? 0 : inv.patient_rials) : 0;
  const paidAmount = inv ? inv.total_rials - remaining : 0;

  return (
    <Modal open={!!invoiceUuid} onClose={onClose} title="خلاصه فاکتور" size="xl">
      {isLoading || !inv ? (
        <div style={{ padding: 24, textAlign: 'center', color: 'var(--text-3)' }}>در حال بارگذاری…</div>
      ) : (
        <div dir="rtl">
          <SectionTable
            title="اطلاعات فاکتور"
            cols={['تاریخ سرویس', 'تاریخ پرداخت', 'وضعیت پرداخت']}
            rows={[[formatDate(inv.issued_at), paid ? formatDate(inv.issued_at) : '—', STATUS_LABEL[inv.status] ?? inv.status]]}
          />
          <SectionTable
            title="اطلاعات سرویس"
            cols={['سرویس', 'تعداد', 'مبلغ']}
            rows={inv.items.length ? inv.items.map((it) => [it.title, it.quantity, formatRial(it.total_rials)]) : [['—', '—', '—']]}
          />
          <SectionTable
            title="خلاصه مالی"
            cols={['جمع مبلغ سرویس', 'سهم بیمه پایه', 'سهم بیمه تکمیلی', 'سهم بیمار', 'مبلغ کل']}
            rows={[[
              formatRial(inv.total_rials), formatRial(inv.base_insurance_rials),
              formatRial(inv.supplementary_rials), formatRial(inv.patient_rials), formatRial(inv.total_rials),
            ]]}
          />
          <SectionTable
            title="وضعیت"
            cols={['مبلغ کل پرداخت شده', 'مبلغ باقی مانده']}
            rows={[[
              formatRial(paidAmount),
              <span style={{ color: remaining > 0 ? '#d32f2f' : '#388e3c', fontWeight: 600 }}>{formatRial(remaining)}</span>,
            ]]}
          />
        </div>
      )}
    </Modal>
  );
}
