import { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchInvoicePdfBlob, fetchInvoicePreview, openPdfBlobInNewTab } from '../../api/invoices'

/**
 * Browser layout matching CI FPDF `pdf_template.php` (print-friendly).
 * Server PDF remains authoritative; this page is for preview/print from JSON.
 */
export function InvoicePdfTemplatePage() {
  const { invoiceId = '' } = useParams()
  const [payload, setPayload] = useState<unknown>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [pdfBusy, setPdfBusy] = useState(false)

  useEffect(() => {
    if (!invoiceId) {
      setLoading(false)
      return
    }
    let c = false
    setLoading(true)
    fetchInvoicePreview(invoiceId)
      .then((p) => {
        if (!c) {
          setPayload(p)
          setError(null)
        }
      })
      .catch((e: unknown) => {
        if (!c)
          setError(e instanceof ApiHttpError ? e.message : 'Unable to load invoice preview.')
      })
      .finally(() => {
        if (!c) setLoading(false)
      })
    return () => {
      c = true
    }
  }, [invoiceId])

  async function onDownloadPdf() {
    if (!invoiceId) return
    setPdfBusy(true)
    try {
      const blob = await fetchInvoicePdfBlob(invoiceId)
      openPdfBlobInNewTab(blob)
    } catch {
      setError('Could not open PDF. Check that the API exposes GET /invoices/:id/pdf with auth.')
    } finally {
      setPdfBusy(false)
    }
  }

  const data = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
  const parent = (data.parent ?? data) as Record<string, unknown>
  const students = (Array.isArray(data.students) ? data.students : []) as Record<string, unknown>[]
  const invoice = (data.invoice ?? data) as Record<string, unknown>

  const fn = String(
    parent.firstparent_firstname ?? parent.first_name ?? parent.firstname ?? '',
  )
  const ln = String(parent.firstparent_lastname ?? parent.last_name ?? parent.lastname ?? '')
  const em = String(parent.firstparent_email ?? parent.email ?? '')
  const ph = String(parent.firstparent_phone ?? parent.phone ?? '')

  const total = Number(invoice.total_amount ?? 0)
  const refund = Number(invoice.refund_amount ?? 0)
  const net = Number(
    invoice.total_amountAfter_refund ?? invoice.net_amount ?? total - refund,
  )
  const status = String(invoice.status ?? '—')

  return (
    <div className="container py-4 invoice-pdf-preview">
      <style>{`
        @media print {
          .no-print { display: none !important; }
          .invoice-pdf-preview { font-size: 12pt; }
        }
      `}</style>

      <div className="no-print d-flex flex-wrap gap-2 mb-3">
        <Link className="btn btn-outline-secondary btn-sm" to="/app/administrator/invoice-payment">
          Back to Invoice Management
        </Link>
        <button type="button" className="btn btn-primary btn-sm" onClick={() => window.print()}>
          Print
        </button>
        <button
          type="button"
          className="btn btn-info btn-sm"
          disabled={pdfBusy || !invoiceId}
          onClick={() => void onDownloadPdf()}
        >
          {pdfBusy ? 'Opening…' : 'Open PDF file'}
        </button>
      </div>

      {error ? <div className="alert alert-warning">{error}</div> : null}
      {loading ? <p className="text-muted">Loading…</p> : null}

      {!loading && (
        <div className="card border-0 shadow-sm">
          <div className="card-body">
            <div className="d-flex align-items-start gap-3 mb-4">
              <img
                src="/images/logo.png"
                alt=""
                width={120}
                style={{ height: 'auto' }}
                className="d-none d-md-block"
              />
              <div className="flex-grow-1 text-center">
                <h1 className="h4 mb-0 fw-bold">Al Rahma Sunday School Invoice</h1>
              </div>
            </div>

            <h2 className="h5 fw-bold mb-2">Parent Details</h2>
            <table className="table table-sm table-borderless mb-4" style={{ maxWidth: 480 }}>
              <tbody>
                <tr>
                  <th className="w-25">First Name</th>
                  <td>{fn || '—'}</td>
                </tr>
                <tr>
                  <th>Last Name</th>
                  <td>{ln || '—'}</td>
                </tr>
                <tr>
                  <th>Email</th>
                  <td>{em || '—'}</td>
                </tr>
                <tr>
                  <th>Phone</th>
                  <td>{ph || '—'}</td>
                </tr>
              </tbody>
            </table>

            <h2 className="h5 fw-bold mb-2">Students Details</h2>
            <table className="table table-bordered w-100 mb-4">
              <thead className="table-light">
                <tr>
                  <th className="text-center" style={{ width: '33%' }}>
                    First Name
                  </th>
                  <th className="text-center" style={{ width: '33%' }}>
                    Last Name
                  </th>
                  <th className="text-center" style={{ width: '34%' }}>
                    Enrollment Status
                  </th>
                </tr>
              </thead>
              <tbody>
                {students.length === 0 ? (
                  <tr>
                    <td colSpan={3} className="text-center text-muted">
                      No students
                    </td>
                  </tr>
                ) : (
                  students.map((s, i) => {
                    const enrolled = Boolean(s.enrolled ?? s.enrollment_status === 'enrolled')
                    const sf = String(s.student_firstname ?? s.firstname ?? s.first_name ?? '')
                    const sl = String(s.student_lastname ?? s.lastname ?? s.last_name ?? '')
                    return (
                      <tr key={i}>
                        <td className="text-center">{sf}</td>
                        <td className="text-center">{sl}</td>
                        <td className="text-center">{enrolled ? 'enrolled' : 'withdrawn'}</td>
                      </tr>
                    )
                  })
                )}
              </tbody>
            </table>

            <h2 className="h5 fw-bold mb-2">Invoice Summary</h2>
            <table className="table table-bordered" style={{ maxWidth: 420 }}>
              <tbody>
                <tr>
                  <th>Total Amount</th>
                  <td className="text-end">
                    {total.toFixed(2)} USD
                  </td>
                </tr>
                <tr>
                  <th>Refund Amount</th>
                  <td className="text-end">{refund.toFixed(2)} USD</td>
                </tr>
                <tr>
                  <th>Net Amount</th>
                  <td className="text-end">{net.toFixed(2)} USD</td>
                </tr>
                <tr>
                  <th>Status</th>
                  <td className="text-end text-capitalize">{status}</td>
                </tr>
              </tbody>
            </table>

            <p className="text-muted small mt-4 text-center d-none d-print-block">Page 1</p>
          </div>
        </div>
      )}
    </div>
  )
}
