import { useEffect, useRef, useState } from 'react'
import { Link, useSearchParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchPaypalPaymentContext } from '../../api/paymentManagement'

declare global {
  interface Window {
    paypal?: {
      Buttons: (opts: {
        style?: { layout?: string; color?: string; shape?: string; label?: string }
        createOrder?: (
          data: unknown,
          actions: { order: { create: (arg: unknown) => Promise<string> } },
        ) => Promise<string>
        onApprove?: (
          data: unknown,
          actions: { order: { capture: () => Promise<{ payer?: { name?: { given_name?: string } } }> } },
        ) => Promise<void>
        onError?: (err: unknown) => void
      }) => { render: (sel: string) => void }
    }
  }
}

/**
 * PayPal checkout (legacy `payment/payment_redirect.php` used `register_layout`).
 * Set `VITE_PAYPAL_CLIENT_ID` for the JS SDK; amounts/context may still come from the API.
 */
export function PaymentRedirectPage() {
  const [searchParams] = useSearchParams()
  const invoiceId = searchParams.get('invoice_id') ?? searchParams.get('invoice') ?? ''
  const clientId =
    (import.meta.env.VITE_PAYPAL_CLIENT_ID as string | undefined)?.trim() || ''

  const [ctx, setCtx] = useState<{
    parentName?: string
    totalAmount?: string | number
    schoolId?: string | number
  } | null>(null)
  const [error, setError] = useState<string | null>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    fetchPaypalPaymentContext({ invoice_id: invoiceId || undefined })
      .then(setCtx)
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Could not load payment context.'),
      )
  }, [invoiceId])

  useEffect(() => {
    if (!clientId || !containerRef.current) return

    const totalAmount = String(ctx?.totalAmount ?? '0.00')
    const parentName = String(ctx?.parentName ?? '')
    const schoolId = String(ctx?.schoolId ?? '')

    const existing = document.getElementById('paypal-sdk-script')
    if (existing) existing.remove()

    const s = document.createElement('script')
    s.id = 'paypal-sdk-script'
    s.src = `https://www.paypal.com/sdk/js?client-id=${encodeURIComponent(clientId)}&currency=USD`
    s.async = true
    s.onload = () => {
      const el = containerRef.current
      if (!el || !window.paypal) return
      el.innerHTML = ''
      window.paypal
        .Buttons({
          style: { layout: 'vertical', color: 'blue', shape: 'rect', label: 'paypal' },
          createOrder: (_data, actions) =>
            actions.order.create({
              purchase_units: [
                {
                  amount: { value: totalAmount },
                  custom_id: schoolId,
                  description: `Payment by ${parentName}`,
                },
              ],
            }),
          onApprove: (_data, actions) =>
            actions.order.capture().then((details) => {
              const name = details.payer?.name?.given_name ?? ''
              alert(`Transaction completed by ${name} for ${parentName}`)
            }),
          onError: (err) => console.error(err),
        })
        .render('#paypal-button-container')
    }
    document.body.appendChild(s)

    return () => {
      s.remove()
      if (containerRef.current) containerRef.current.innerHTML = ''
    }
  }, [clientId, ctx])

  return (
    <div className="container d-flex justify-content-center align-items-start" style={{ minHeight: '100vh', paddingTop: 80 }}>
      <div
        className="registration-form text-center p-4 rounded-4 shadow"
        style={{ backgroundColor: 'white', maxWidth: 600, width: '100%' }}
      >
        <div className="mb-4">
          <Link to="/app/parent/home">
            <img src="/images/logo.png" alt="Alrahma Logo" style={{ width: 180, height: 'auto' }} />
          </Link>
        </div>

        <h3 className="text-success" style={{ fontFamily: 'Arial, sans-serif' }}>
          Payment
        </h3>
        <br />

        {!clientId ? (
          <div className="alert alert-warning">
            Configure <code>VITE_PAYPAL_CLIENT_ID</code> to enable PayPal buttons.
          </div>
        ) : null}
        {error ? <div className="alert alert-danger">{error}</div> : null}
        {invoiceId ? (
          <p className="small text-muted">Invoice reference: {invoiceId}</p>
        ) : (
          <p className="small text-muted">Optional: add <code>?invoice_id=</code> to the URL.</p>
        )}

        <div className="d-flex justify-content-center">
          <div id="paypal-button-container" ref={containerRef} />
        </div>

        <p className="text-success mt-3">
          <strong>
            Your payment information, including credit card and bank account details, is securely stored only by PayPal
            and Venmo.
          </strong>
        </p>
        <p className="text-danger">We do not collect or save any financial data on our website.</p>
      </div>
    </div>
  )
}
