"""Hosted checkout pages (minimal HTML for Phase 1)."""

from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session

from ..config import settings
from ..db import get_db
from ..models import CheckoutSession

router = APIRouter(prefix="/checkout", tags=["checkout-page"])


def _page(title: str, body: str) -> HTMLResponse:
    """Render a minimal HTML document with shared checkout styling."""
    html = f"""<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8"/>
    <title>{title}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <style>
      :root {{
        --ink: #0f172a;
        --muted: #475569;
        --bg: #e7ecf2;
        --card: #ffffff;
        --accent: #1f3a8a;
        --accent-hover: #1e40af;
        --accent-2: #253454;
        --success: #15803d;
        --soft: #f1f5f9;
        --border: #e5e7eb;
      }}
      * {{ box-sizing: border-box; }}
      body {{
        font-family: "Georgia", "Times New Roman", serif;
        margin: 0;
        background: var(--bg);
        color: var(--ink);
      }}
      .wrap {{ max-width: 760px; margin: 48px auto; padding: 0 20px; }}
      .card {{
        background: var(--card);
        border: 1px solid #cfd6e0;
        border-radius: 18px;
        padding: 28px;
        box-shadow: 0 14px 34px rgba(16, 24, 39, 0.12);
      }}
      .header {{ display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; }}
      .brand {{ font-weight: 700; letter-spacing: 0.3px; }}
      .badge {{ font-size: 12px; padding: 6px 10px; border-radius: 999px; background: var(--accent-2); color: #fff; }}
      .muted {{ color: var(--muted); font-size: 14px; }}
      .summary {{
        display: grid;
        grid-template-columns: 1fr auto;
        gap: 12px;
        background: var(--soft);
        border: 1px solid var(--border);
        border-radius: 12px;
        padding: 14px;
        margin: 16px 0 22px;
      }}
      .summary .label {{ font-size: 13px; color: var(--muted); }}
      .summary .value {{ font-size: 18px; font-weight: 600; }}
      .actions {{ display: flex; gap: 12px; flex-wrap: wrap; margin-top: 16px; }}
      .btn {{
        display: inline-flex;
        align-items: center;
        justify-content: center;
        padding: 12px 18px;
        background: var(--accent-2);
        color: #fff;
        text-decoration: none;
        border-radius: 10px;
        font-weight: 600;
        box-shadow: 0 2px 8px rgba(31, 58, 138, 0.18);
      }}
      .btn:hover {{ background: var(--accent-hover); }}
      .btn-secondary {{ background: #e5e7eb; color: #111827; box-shadow: none; }}
      .fineprint {{ margin-top: 18px; font-size: 12px; color: var(--muted); }}
      .success {{ color: var(--success); font-weight: 700; }}
    </style>
  </head>
  <body>
    <div class="wrap">
      <div class="card">
        {body}
      </div>
    </div>
  </body>
</html>"""
    return HTMLResponse(content=html)


@router.get("/{session_id}", response_class=HTMLResponse)
def checkout_page(session_id: str, db: Session = Depends(get_db)):
    """Render the hosted checkout page for a session."""
    session = db.get(CheckoutSession, session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Checkout session not found")

    dev_note = ""
    if settings.app_env != "prod":
        dev_note = "<p class='muted'>Dev mode: use the webhook endpoint to mark as paid.</p>"

    body = f"""
      <div class="header">
        <div class="brand">LARI • Secure Checkout</div>
        <div class="badge">Card payment</div>
      </div>
      <h2>Complete your payment</h2>
      <p class="muted">You’re paying for a confirmed service. Your card details are never stored.</p>
      <div class="summary">
        <div>
          <div class="label">Order reference</div>
          <div class="value">{session.external_order_id}</div>
        </div>
        <div>
          <div class="label">Total</div>
          <div class="value">{session.amount} {session.currency}</div>
        </div>
      </div>
      <p>Status: <strong>{session.status}</strong></p>
      {dev_note}
      <div class="actions">
        <a class="btn" href="/checkout/{session.id}/success">Pay now</a>
        <a class="btn btn-secondary" href="/checkout/{session.id}/cancel">Cancel</a>
      </div>
      <div class="fineprint">
        By continuing, you agree to the provider’s terms and authorize a one‑time charge.
      </div>
    """
    return _page("Checkout", body)


@router.get("/{session_id}/success", response_class=HTMLResponse)
def checkout_success(session_id: str, db: Session = Depends(get_db)):
    """Render the checkout success page."""
    session = db.get(CheckoutSession, session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Checkout session not found")
    body = f"""
      <div class="header">
        <div class="brand">LARI • Secure Checkout</div>
        <div class="badge">Success</div>
      </div>
      <h2 class="success">Payment submitted</h2>
      <p>We are confirming your payment. You’ll receive confirmation shortly.</p>
      <p class="muted">Session: {session.id}</p>
    """
    return _page("Success", body)


@router.get("/{session_id}/cancel", response_class=HTMLResponse)
def checkout_cancel(session_id: str, db: Session = Depends(get_db)):
    """Render the checkout cancel page."""
    session = db.get(CheckoutSession, session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Checkout session not found")
    body = f"""
      <div class="header">
        <div class="brand">LARI • Secure Checkout</div>
        <div class="badge">Canceled</div>
      </div>
      <h2>Payment canceled</h2>
      <p>If this was a mistake, you can try again.</p>
      <p class="muted">Session: {session.id}</p>
    """
    return _page("Canceled", body)
