"use client";

import { useCallback, useEffect, useMemo, useState } from "react";

type Dealer = { id: string; display_name: string; city: string; profile_status: string; tier: string | null; subscription_status: string | null; opportunities_used: number | null; current_period_end: string | null; owner_name: string | null; owner_email: string | null; manufacturers: string | null; quote_outside_inventory: boolean; quotes_sent: number; quotes_submitted: number };
type Offer = { id: string; dealership_id: string; dealership_name: string; status: string; vehicle_price_cents: number; mandatory_fees_cents: number; unconditional_discount_cents: number; comparable_price_cents: number; stock_number: string | null; availability_confirmed: boolean; submitted_at: string | null; valid_until: string; given_to_customer: boolean; customer_visited: boolean | null; vehicle_purchased: boolean | null };
type Assignment = { id: string; dealership_id: string; dealership_name: string; status: string; assignment_source: string; assigned_at: string; first_viewed_at: string | null; responded_at: string | null; offer_submitted: boolean };
type CustomerRequest = { id: string; public_reference: string; customer_name: string; customer_email: string; status: string; condition: string; model_year: number | null; min_model_year?: number | null; max_model_year?: number | null; make: string; model: string; trim: string; exterior_color: string; exterior_color_flexible: boolean; created_at: string; due_at: string; delivered_at: string | null; opportunity_id: string; opportunity_status: string; assignment_count: number; outstanding_dealer_count: number; eligible_offer_count: number; report_id: string | null; version_number: number | null; report_status: string | null; approved_at: string | null; assignments: Assignment[]; offers: Offer[] };
type Data = { health: { healthy: boolean; message: string; latencyMs?: number }; dealerships: Dealer[]; requests: CustomerRequest[] };
const date = (value: string | null) => value ? new Intl.DateTimeFormat("en-CA", { dateStyle: "medium", timeZone: "America/Toronto" }).format(new Date(value)) : "—";
const dateTime = (value: string | null) => value ? new Intl.DateTimeFormat("en-CA", { dateStyle: "medium", timeStyle: "short", timeZone: "America/Toronto" }).format(new Date(value)) : "—";
const money = (cents: number) => new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD", minimumFractionDigits: 2 }).format(cents / 100);
const vehicleLabel = (request: CustomerRequest) => [[request.min_model_year, request.max_model_year].filter(Boolean).join("–") || request.model_year, request.make, request.model, request.trim].filter(Boolean).join(" ");
const sourceLabel = (source: string) => source === "gold_automatic" ? "Automatic Gold match" : source === "admin" ? "Assigned by admin" : "Dealer selected";
const hoursWithDealer = (assignment: Assignment, deliveredAt: string | null) => {
  const start = new Date(assignment.assigned_at).getTime();
  const end = new Date(assignment.responded_at || deliveredAt || Date.now()).getTime();
  const hours = Math.max(0, (end - start) / 3_600_000);
  return `${hours < 0.1 ? "<0.1" : hours.toFixed(1)} hours${assignment.responded_at ? " to response" : deliveredAt ? " before closing" : " and counting"}`;
};
function requestStage(request: CustomerRequest) {
  if (request.status === "delivered" || request.report_status === "sent") return { icon: "✓", label: "Delivered", className: "delivered" };
  if (request.report_status === "approved") return { icon: "✓", label: "Approved", className: "approved" };
  if (request.report_status === "review_ready") return { icon: "◆", label: "Awaiting approval", className: "review" };
  if (request.eligible_offer_count > 0) return { icon: "$", label: "Pricing received", className: "pricing" };
  if (request.assignment_count > 0) return { icon: "→", label: "With dealers", className: "assigned" };
  return { icon: "○", label: "New request", className: "new" };
}

function DealerAssignments({ assignments, deliveredAt }: { assignments: Assignment[]; deliveredAt: string | null }) {
  return <section className="enterprise-assignments">
    <div className="enterprise-section-heading">
      <div><p className="eyebrow-text">Dealer outreach</p><h3>Where this request was sent</h3></div>
      <strong>{assignments.length} dealer{assignments.length === 1 ? "" : "s"}</strong>
    </div>
    {assignments.length ? <div className="table-scroll"><table className="directory-table enterprise-assignment-table">
      <thead><tr><th>Dealership</th><th>Original sent time</th><th>Time since original send</th><th>Progress</th></tr></thead>
      <tbody>{assignments.map((assignment) => <tr key={assignment.id}>
        <td><strong>{assignment.dealership_name}</strong><span>{sourceLabel(assignment.assignment_source)}</span></td>
        <td>{dateTime(assignment.assigned_at)}</td>
        <td><strong>{hoursWithDealer(assignment, deliveredAt)}</strong></td>
        <td><span className={`offer-admin-status ${assignment.offer_submitted ? "delivered" : ""}`}>{assignment.offer_submitted ? "Price submitted" : assignment.status}</span>{assignment.first_viewed_at && <span>Viewed {dateTime(assignment.first_viewed_at)}</span>}</td>
      </tr>)}</tbody>
    </table></div> : <div className="tracker-empty compact"><strong>Not sent to a dealer yet</strong><p>Assign a dealership below or process the matching queue.</p></div>}
  </section>;
}

function DealerPricing({ offers }: { offers: Offer[] }) {
  return <section className="enterprise-offers">
<div className="enterprise-section-heading">
<div>
<p className="eyebrow-text">Dealer responses</p>
<h3>Pricing submitted for this customer</h3>
</div>
<strong>{offers.length} total</strong>
</div>{offers.length ? <div className="table-scroll">
<table className="directory-table enterprise-offer-table">
<thead>
<tr>
<th>Dealership</th>
<th>Vehicle price</th>
<th>Fees</th>
<th>Discount</th>
<th>All-in price</th>
<th>Customer outcome</th>
<th>Status</th>
</tr>
</thead>
<tbody>{offers.map((offer) => <tr key={offer.id}>
<td>
<strong>{offer.dealership_name}</strong>
<span>{offer.stock_number ? `Stock ${offer.stock_number}` : "No stock number"}</span>
</td>
<td>{money(offer.vehicle_price_cents)}</td>
<td>+ {money(offer.mandatory_fees_cents)}</td>
<td>− {money(offer.unconditional_discount_cents)}</td>
<td>
<strong>{money(offer.comparable_price_cents)}</strong>
<span>{offer.availability_confirmed ? "Availability confirmed" : "Unconfirmed"}</span>
</td>
<td><strong>{offer.vehicle_purchased === true ? "Purchased" : offer.customer_visited === true ? "Visited" : "Not confirmed"}</strong><span>{offer.vehicle_purchased === false ? "Purchase: No" : offer.vehicle_purchased === true ? "Purchase: Yes" : "Purchase not reported"}</span></td>
<td>
<span className={`offer-admin-status ${offer.given_to_customer ? "delivered" : ""}`}>{offer.given_to_customer ? "Given to customer" : offer.status}</span>
<small>{date(offer.submitted_at)}</small>
</td>
</tr>)}</tbody>
</table>
</div> : <div className="tracker-empty compact">
<strong>No dealer pricing yet</strong>
<p>Assign this opportunity to an active dealership or process Gold matching.</p>
</div>}</section>;
}

export default function EnterpriseAdminClient() {
  const [data, setData] = useState<Data | null>(null); const [selectedId, setSelectedId] = useState(""); const [recommendation, setRecommendation] = useState(""); const [dealerId, setDealerId] = useState(""); const [message, setMessage] = useState(""); const [busy, setBusy] = useState(false);
  const load = useCallback(async () => { const response = await fetch("/api/admin/enterprise", { cache: "no-store" }); if (response.status === 401) return window.location.href = "/admin"; const result = await response.json(); setData(result); setSelectedId((current) => current || result.requests?.[0]?.id || ""); }, []);
  useEffect(() => { void load(); }, [load]);
  const selected = useMemo(() => data?.requests.find((request) => request.id === selectedId) || data?.requests[0], [data, selectedId]);
  async function action(actionName: string, extra: Record<string, unknown> = {}) { setBusy(true); setMessage("Working…"); const response = await fetch("/api/admin/enterprise", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: actionName, ...extra }) }); const result = await response.json(); setBusy(false); const matching = result.result as { jobs?: number; assignments?: number; offers?: number } | undefined; setMessage(response.ok ? actionName === "processMatching" ? `New-request matching complete: ${matching?.jobs || 0} queued requests, ${matching?.assignments || 0} dealer assignments and ${matching?.offers || 0} automatic inventory prices processed.` : "Completed successfully." : result.error || "Operation failed."); if (response.ok) await load(); return response.ok ? result : null; }
  function preview() { if (selected?.report_id) window.open(`/api/admin/enterprise-report?id=${encodeURIComponent(selected.report_id)}`, "_blank"); }
  async function send() { if (!selected?.report_id || !window.confirm(`Send approved report version ${selected.version_number} to ${selected.customer_email}?`)) return; setBusy(true); setMessage("Sending approved report…"); const response = await fetch("/api/admin/enterprise-report", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: selected.report_id }) }); const result = await response.json(); setBusy(false); setMessage(response.ok ? "Approved report sent; request marked Delivered." : result.error || "Send failed."); if (response.ok) await load(); }
  return <main className="enterprise-admin-page">
<header className="tracker-header">
<img src="/logo-reversed.svg" alt="Beat My Car Quote" />
<div>
<span>Enterprise staging</span>
<a href="/admin">Legacy tracker</a>
</div>
</header>
<section className="enterprise-admin-shell">
<div className="enterprise-admin-title">
<div>
<p className="eyebrow-text">Marketplace operations</p>
<h1>Dealer marketplace</h1>
<p>Memberships, metered opportunities, offers and approved customer reports.</p>
</div>
<div className={`database-health ${data?.health.healthy ? "healthy" : "unhealthy"}`}>
<span>System status</span>
<strong>{data?.health.message || "Checking…"}</strong>
<small>{data?.health.latencyMs ? `${data.health.latencyMs} ms` : ""}</small>
</div>
</div>
<nav className="enterprise-quick-actions">
<a className="button-secondary" href="/api/admin/sales-export">Export completed sales CSV</a>
<button className="button-secondary" onClick={() => void load()}>Refresh</button>
<button className="button" disabled={busy || !data?.health.healthy} onClick={() => void action("processMatching")}>Process new matching requests</button>
</nav>{message && <p className="portal-message" role="status">{message}</p>}{!data?.health.healthy ? <div className="tracker-empty">
<strong>Operations data is not ready</strong>
<p>The customer and dealer workspace is temporarily unavailable. Check the staging configuration and try again.</p>
</div> : <>
<div className="enterprise-metrics">
<article>
<span>Dealerships</span>
<strong>{data.dealerships.length}</strong>
</article>
<article>
<span>Active subscriptions</span>
<strong>{data.dealerships.filter((dealer) => ["active", "trialing"].includes(dealer.subscription_status || "")).length}</strong>
</article>
<article>
<span>Open requests</span>
<strong>{data.requests.filter((request) => request.status !== "delivered").length}</strong>
</article>
<article>
<span>Awaiting approval</span>
<strong>{data.requests.filter((request) => request.report_status === "review_ready").length}</strong>
</article>
</div>
<section className="enterprise-admin-grid">
<aside className="enterprise-request-list">{data.requests.map((request) => { const stage = requestStage(request); return <button key={request.id} className={request.id === selected?.id ? "active" : ""} onClick={() => setSelectedId(request.id)} aria-label={`${request.customer_name}: ${stage.label}`}>
<span className={`request-stage-icon stage-${stage.className}`} title={stage.label} aria-hidden="true">{stage.icon}</span>
<span className="request-list-copy"><span>{request.customer_name} · {stage.label}</span><strong>{vehicleLabel(request)}</strong><small>{request.offers.length} prices · {request.outstanding_dealer_count} awaiting · {request.report_status || "No report"}</small></span>
</button>; })}</aside>{selected ? <article className="enterprise-review-card">
<div className="enterprise-review-heading">
<div>
<span>{selected.public_reference}</span>
<h2>{vehicleLabel(selected)}</h2>
<p>{selected.customer_name} · {selected.customer_email}</p>
<p>{selected.exterior_color_flexible ? `${selected.exterior_color ? `${selected.exterior_color} preferred · ` : ""}Any exterior colour accepted` : `Exterior colour: ${selected.exterior_color || "Not specified"}`}</p>
</div>
<span className={`status-pill status-${selected.status}`}>{selected.status}</span>
</div>
<div className="enterprise-review-stats">
<div>
<span>Due</span>
<strong>{date(selected.due_at)}</strong>
</div>
<div>
<span>Dealer assignments</span>
<strong>{selected.assignment_count}</strong>
</div>
<div>
<span>Eligible offers</span>
<strong>{selected.eligible_offer_count}</strong>
</div>
<div className={selected.outstanding_dealer_count ? "outstanding-flag" : "complete-flag"}>
<span>Dealers yet to submit</span>
<strong>{selected.outstanding_dealer_count}</strong>
</div>
</div>
<DealerAssignments assignments={selected.assignments || []} deliveredAt={selected.delivered_at} />
<DealerPricing offers={selected.offers || []} />
<section className="enterprise-assignment">
<h3>Send opportunity to a dealership</h3>
<div>
<select value={dealerId} onChange={(event) => setDealerId(event.target.value)}>
<option value="">Select active dealership</option>{data.dealerships.filter((dealer) => ["active", "trialing"].includes(dealer.subscription_status || "")).map((dealer) => <option key={dealer.id} value={dealer.id}>{dealer.display_name} · {dealer.tier} · {dealer.opportunities_used || 0} used</option>)}</select>
<button className="button-secondary" disabled={!dealerId || busy} onClick={() => void action("assignOpportunity", { opportunityId: selected.opportunity_id, dealershipId: dealerId })}>Assign opportunity</button>
</div>
</section>
<section className="enterprise-report-workflow">
<h3>Customer report approval</h3>
<label>
<span>Personalized recommendation</span>
<textarea value={recommendation} onChange={(event) => setRecommendation(event.target.value)} placeholder="Add request-specific guidance after the standard buyer recommendations." />
</label>
<div className="report-version-status">
<span>Current version</span>
<strong>{selected.report_id ? `Version ${selected.version_number} · ${selected.report_status}` : "Not created"}</strong>{selected.approved_at && <small>Approved {date(selected.approved_at)}</small>}</div>
<div className="enterprise-report-actions">
<button className="button-secondary" disabled={busy || selected.eligible_offer_count < 1} onClick={() => void action("createReport", { customerRequestId: selected.id, recommendation })}>Create review version</button>
<button className="button-secondary" disabled={!selected.report_id} onClick={preview}>Preview exact PDF</button>
<button className="button-secondary" disabled={busy || selected.report_status !== "review_ready"} onClick={() => void action("approveReport", { reportId: selected.report_id })}>Approve version</button>
<button className="button" disabled={busy || selected.report_status !== "approved"} onClick={() => void send()}>Send approved report</button>
</div>
<p className="directory-source-note">Creating a new report supersedes any earlier unsent approval. Only the exact approved version can be emailed.</p>
</section>
</article> : <div className="tracker-empty">No customer requests yet.</div>}</section>
<section className="directory-card directory-table-card enterprise-dealer-table">
<div>
<p className="eyebrow-text">Membership directory</p>
<h2>Dealership subscriptions</h2>
</div>
<div className="table-scroll">
<table className="directory-table">
<thead>
<tr>
<th>Dealership</th>
<th>Owner</th>
<th>Manufacturer</th>
<th>Membership</th>
<th>Quotes sent</th>
<th>Quotes submitted</th>
<th>Current usage</th>
<th>Status</th>
</tr>
</thead>
<tbody>{data.dealerships.map((dealer) => <tr key={dealer.id}>
<td>
<strong>{dealer.display_name}</strong>
<span>{dealer.city}</span>
</td>
<td>{dealer.owner_name}<span>{dealer.owner_email}</span>
</td>
<td>{dealer.manufacturers || "—"}<span>{dealer.quote_outside_inventory ? "Accepts same-brand opportunities" : "Inventory only"}</span></td>
<td>{dealer.tier || "Pending"}</td>
<td>{dealer.quotes_sent}</td>
<td>{dealer.quotes_submitted}</td>
<td>{dealer.tier === "gold" ? "Unlimited" : dealer.opportunities_used ?? 0}</td>
<td>{dealer.subscription_status || dealer.profile_status}</td>
</tr>)}</tbody>
</table>
</div>
</section>
</>}</section>
</main>;
}
