"use client";
import { FormEvent, useCallback, useEffect, useMemo, useState } from "react";
import type { DealerIdentity } from "../../../lib/enterprise-types";
import GoldInventorySection from "./gold-inventory-section";
import DealerPreferences from "./dealer-preferences";
type SubmittedOffer = {
    id: string;
    status: string;
    stock_number: string | null;
    vin: string | null;
    vehicle_price_cents: number;
    mandatory_fees_cents: number;
    unconditional_discount_cents: number;
    comparable_price_cents: number;
    taxes_included: boolean;
    availability_confirmed: boolean;
    conditions_text: string | null;
    valid_until: string;
    submitted_at: string;
    given_to_customer: boolean;
    customer_delivery_at: string | null;
    customer_visited: boolean | null;
    vehicle_purchased: boolean | null;
    outcome_updated_at: string | null;
};
type Opportunity = Record<string, string | number | boolean | null> & {
    submitted_offers: SubmittedOffer[];
};
type Dashboard = {
    identity: DealerIdentity;
    preferences: { manufacturer: string | null; quote_outside_inventory: boolean };
    subscription: null | {
        tier: string;
        status: string;
        monthly_price_cents: number;
        opportunities_used: number;
        current_period_end: string;
        cancel_at_period_end: boolean;
    };
    opportunities: Opportunity[];
    inventory: Array<Record<string, string | number | boolean | null>>;
};
const money = (cents: number) => new Intl.NumberFormat("en-CA", { style: "currency", currency: "CAD" }).format(cents / 100);
const date = (value: unknown) => value ? new Intl.DateTimeFormat("en-CA", { dateStyle: "medium", timeZone: "America/Toronto" }).format(new Date(String(value))) : "—";
const deadlineDate = (value: unknown) => value ? new Intl.DateTimeFormat("en-CA", { dateStyle: "medium", timeStyle: "short", timeZone: "America/Toronto" }).format(new Date(String(value))) : "—";
const cents = (value: string) => { const parsed = Number(value.replace(/[$,\s]/g, "")); return Number.isFinite(parsed) ? Math.round(parsed * 100) : 0; };
const formatDollars = (value: string) => money(cents(value));
function OfferForm({ assignmentId, busy, onSubmit }: {
    assignmentId: string;
    busy: boolean;
    onSubmit: (event: FormEvent<HTMLFormElement>, id: string) => Promise<void>;
}) {
    const [vehiclePrice, setVehiclePrice] = useState("");
    const [mandatoryFees, setMandatoryFees] = useState("0");
    const [discount, setDiscount] = useState("0");
    const [taxesIncluded, setTaxesIncluded] = useState(false);
    const total = Math.max(0, cents(vehiclePrice) + cents(mandatoryFees) - cents(discount));
    return <form className="dealer-offer-form" onSubmit={(event) => void onSubmit(event, assignmentId)}>
    <div className="field-grid three">
<label>
<span>Vehicle selling price</span>
<input name="vehiclePrice" inputMode="decimal" placeholder="$45,000.00" required value={vehiclePrice} onFocus={() => setVehiclePrice(vehiclePrice.replace(/[$,\sA-Z]/gi, ""))} onBlur={() => setVehiclePrice(formatDollars(vehiclePrice))} onChange={(event) => setVehiclePrice(event.target.value)}/>
</label>
<label>
<span>All mandatory fees</span>
<input name="mandatoryFees" inputMode="decimal" required value={mandatoryFees} onFocus={() => setMandatoryFees(mandatoryFees.replace(/[$,\sA-Z]/gi, ""))} onBlur={() => setMandatoryFees(formatDollars(mandatoryFees))} onChange={(event) => setMandatoryFees(event.target.value)}/>
</label>
<label>
<span>Unconditional discount</span>
<input name="unconditionalDiscount" inputMode="decimal" required value={discount} onFocus={() => setDiscount(discount.replace(/[$,\sA-Z]/gi, ""))} onBlur={() => setDiscount(formatDollars(discount))} onChange={(event) => setDiscount(event.target.value)}/>
</label>
</div>
    <section className="live-offer-total" aria-live="polite">
<div>
<span>Vehicle price</span>
<strong>{money(cents(vehiclePrice))}</strong>
</div>
<div>
<span>+ Mandatory fees</span>
<strong>{money(cents(mandatoryFees))}</strong>
</div>
<div>
<span>− Unconditional discount</span>
<strong>{money(cents(discount))}</strong>
</div>
<div className="live-offer-grand-total">
<span>Price that will be submitted</span>
<strong>{money(total)}</strong>
</div>
<p>{taxesIncluded ? "You indicated this submitted price includes applicable taxes." : "All-in dealer price before HST and government licensing/registration charges."}</p>
</section>
    <div className="field-grid three">
<label>
<span>Stock number</span>
<input name="stockNumber"/>
</label>
<label>
<span>VIN</span>
<input name="vin"/>
</label>
<label>
<span>Valid until</span>
<input name="validUntil" type="date" required/>
</label>
</div>
    <label className="full-field">
<span>Conditions and inclusions</span>
<textarea name="conditionsText" placeholder="State every fee, rebate requirement, financing condition and availability detail."/>
</label>
    <div className="offer-confirmations">
<label>
<input type="checkbox" name="availabilityConfirmed" required/> Vehicle availability is confirmed</label>
<label>
<input type="checkbox" name="taxesIncluded" checked={taxesIncluded} onChange={(event) => setTaxesIncluded(event.target.checked)}/> Entered price includes applicable taxes</label>
</div>
    <div className="offer-submit-confirmation">
<strong>You are submitting {money(total)}</strong>
<span>Review the calculation above. Submitted offers remain visible in this opportunity.</span>
</div>
    <button className="button" disabled={busy || total <= 0}>{busy ? "Submitting…" : `Submit ${money(total)} offer`}</button>
  </form>;
}
function SubmittedOffers({ offers, busy, onSaveOutcome }: {
    offers: SubmittedOffer[];
    busy: boolean;
    onSaveOutcome: (offerId: string, customerVisited: boolean | null, vehiclePurchased: boolean | null) => Promise<void>;
}) {
    if (!offers.length)
        return null;
    return <section className="submitted-offers">
<div className="submitted-offers-title">
<div>
<span className="eyebrow-text">Your quote history</span>
<h3>Submitted pricing</h3>
</div>
<strong>{offers.length} {offers.length === 1 ? "offer" : "offers"}</strong>
</div>{offers.map((offer, index) => <article key={offer.id} className="submitted-offer">
<header>
<div>
<span>{index === 0 ? "Current submission" : `Previous submission ${offers.length - index}`}</span>
<strong>{money(offer.comparable_price_cents)}</strong>
</div>
<small>{offer.status} · Submitted {date(offer.submitted_at)}</small>
</header>
<div className={`customer-delivery-status ${offer.given_to_customer ? "delivered" : "pending"}`}>
<strong>{offer.given_to_customer ? "✓ Quote given to customer" : "Not yet given to customer"}</strong>
<span>{offer.given_to_customer ? `Included in a customer report sent ${date(offer.customer_delivery_at)}.` : "Your quote remains recorded for independent review."}</span>
</div>
<dl>
<div>
<dt>Vehicle price</dt>
<dd>{money(offer.vehicle_price_cents)}</dd>
</div>
<div>
<dt>Mandatory fees</dt>
<dd>+ {money(offer.mandatory_fees_cents)}</dd>
</div>
<div>
<dt>Discount</dt>
<dd>− {money(offer.unconditional_discount_cents)}</dd>
</div>
<div className="submitted-total">
<dt>Submitted price</dt>
<dd>{money(offer.comparable_price_cents)}</dd>
</div>
</dl>
<p>{offer.taxes_included ? "Includes applicable taxes" : "Before HST and licensing"} · Valid until {date(offer.valid_until)}{offer.stock_number ? ` · Stock ${offer.stock_number}` : ""}</p>{offer.conditions_text && <blockquote>{offer.conditions_text}</blockquote>}
<QuoteOutcomeForm offer={offer} busy={busy} onSave={onSaveOutcome}/>
</article>)}</section>;
}

function QuoteOutcomeForm({ offer, busy, onSave }: { offer: SubmittedOffer; busy: boolean; onSave: (offerId: string, customerVisited: boolean | null, vehiclePurchased: boolean | null) => Promise<void> }) {
    const [visited, setVisited] = useState<"" | "yes" | "no">(offer.customer_visited === true ? "yes" : offer.customer_visited === false ? "no" : "");
    const [purchased, setPurchased] = useState<"" | "yes" | "no">(offer.vehicle_purchased === true ? "yes" : offer.vehicle_purchased === false ? "no" : "");
    const value = (answer: "" | "yes" | "no") => answer === "yes" ? true : answer === "no" ? false : null;
    const choices: Array<["" | "yes" | "no", string]> = [["", "Not confirmed"], ["yes", "Yes"], ["no", "No"]];
    return <form className="quote-outcome-form" onSubmit={(event) => { event.preventDefault(); void onSave(offer.id, value(visited), value(purchased)); }}>
      <div><strong>Customer outcome</strong><span>Optional. Update this when you learn what happened after your quote.</span></div>
      <fieldset><legend>Did the customer visit?</legend>{choices.map(([answer, label]) => <label key={answer || "unknown"}><input type="radio" name={`visited-${offer.id}`} checked={visited === answer} onChange={() => setVisited(answer)}/>{label}</label>)}</fieldset>
      <fieldset><legend>Did the customer buy the vehicle?</legend>{choices.map(([answer, label]) => <label key={answer || "unknown"}><input type="radio" name={`purchased-${offer.id}`} checked={purchased === answer} onChange={() => setPurchased(answer)}/>{label}</label>)}</fieldset>
      <button className="button-secondary" disabled={busy}>Save outcome</button>
      {offer.outcome_updated_at && <small>Last updated {date(offer.outcome_updated_at)}</small>}
    </form>;
}
export default function DealerDashboardClient({ initialIdentity }: {
    initialIdentity: DealerIdentity;
}) {
    const [data, setData] = useState<Dashboard | null>(null);
    const [section, setSection] = useState<"opportunities" | "inventory" | "account">("opportunities");
    const [message, setMessage] = useState("");
    const [busy, setBusy] = useState(false);
    const load = useCallback(async () => { const response = await fetch("/api/dealer/dashboard", { cache: "no-store" }); if (response.status === 401)
        return window.location.href = "/dealer"; setData(await response.json()); }, []);
    useEffect(() => { void load(); }, [load]);
    const allowance = useMemo(() => { if (!data?.subscription)
        return "No active membership"; if (data.subscription.tier === "gold")
        return "All matching opportunities"; const limit = data.subscription.tier === "bronze" ? 5 : 10; return `${data.subscription.opportunities_used} of ${limit} opportunities used`; }, [data]);
    async function logout() { await fetch("/api/dealer/auth/logout", { method: "POST" }); window.location.href = "/dealer"; }
    async function openBillingPortal(action: "payment_method_update" | "subscription_cancel") {
        setBusy(true);
        setMessage(action === "subscription_cancel" ? "Opening secure cancellation options…" : "Opening secure payment details…");
        const response = await fetch("/api/dealer/billing-portal", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ action }),
        });
        const result = await response.json();
        if (response.status === 401) return window.location.href = "/dealer";
        if (!response.ok || !result.url) {
            setBusy(false);
            setMessage(result.error || "Billing management could not be opened.");
            return;
        }
        window.location.href = result.url;
    }
    async function submitOffer(event: FormEvent<HTMLFormElement>, assignmentId: string) { event.preventDefault(); const formElement = event.currentTarget; setBusy(true); setMessage("Submitting offer…"); const form = new FormData(formElement); const body = { ...Object.fromEntries(form.entries()), assignmentId, availabilityConfirmed: form.get("availabilityConfirmed") === "on", taxesIncluded: form.get("taxesIncluded") === "on" }; const response = await fetch("/api/dealer/offers", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); const result = await response.json(); setBusy(false); setMessage(response.ok ? `Offer ${money(Number(result.offer.comparable_price_cents))} submitted. The refreshed quote history appears below.` : result.error || "Offer failed."); if (response.ok)
        await load(); }
    async function saveOutcome(offerId: string, customerVisited: boolean | null, vehiclePurchased: boolean | null) { setBusy(true); setMessage("Saving customer outcome…"); const response = await fetch("/api/dealer/offers", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ offerId, customerVisited, vehiclePurchased }) }); const result = await response.json(); setBusy(false); setMessage(response.ok ? "Customer outcome saved." : result.error || "Outcome could not be saved."); if (response.ok) await load(); }
    async function uploadInventory(event: FormEvent<HTMLFormElement>) { event.preventDefault(); setBusy(true); setMessage("Validating and importing inventory…"); const response = await fetch("/api/dealer/inventory", { method: "POST", body: new FormData(event.currentTarget) }); const result = await response.json(); setBusy(false); setMessage(response.ok ? `Imported ${result.accepted} rows; rejected ${result.rejected}.` : result.error || "Upload failed."); if (response.ok)
        await load(); }
    return <main className="dealer-dashboard-page">
<header className="dealer-dashboard-header">
<img src="/logo-reversed.svg" alt="Beat My Car Quote"/>
<div>
<span>{data?.identity.dealershipName || initialIdentity.dealershipName}</span>
<button onClick={logout}>Sign out</button>
</div>
</header>
<section className="dealer-dashboard-shell">
<div className="dealer-dashboard-welcome">
<div>
<p className="eyebrow-text">Dealer workspace</p>
<h1>Welcome, {data?.identity.fullName.split(" ")[0] || initialIdentity.fullName.split(" ")[0]}</h1>
<p>Quote only the opportunities assigned to your dealership.</p>
</div>
<article>
<span>{data?.subscription?.tier || "Pending"} membership</span>
<strong>{allowance}</strong>
<small>{data?.subscription ? `Renews ${date(data.subscription.current_period_end)}` : "Complete checkout to activate access"}</small>
</article>
</div>
{data && <section className="dealer-summary-grid" aria-label="Quote activity summary">
<article><span>Deals pending</span><strong>{data.opportunities.filter((item) => item.opportunity_status === "open" && item.assignment_status !== "expired" && new Date(String(item.response_deadline)).getTime() >= Date.now() && !(item.submitted_offers || []).length).length}</strong><small>Awaiting your price</small></article>
<article><span>Total received</span><strong>{data.opportunities.length}</strong><small>All assigned opportunities</small></article>
<article><span>Total submitted</span><strong>{data.opportunities.filter((item) => (item.submitted_offers || []).length > 0).length}</strong><small>Opportunities quoted</small></article>
</section>}
<nav className="dealer-dashboard-tabs">
<button className={section === "opportunities" ? "active" : ""} onClick={() => setSection("opportunities")}>Opportunities</button>
<button className={section === "inventory" ? "active" : ""} onClick={() => setSection("inventory")}>Gold inventory</button>
<button className={section === "account" ? "active" : ""} onClick={() => setSection("account")}>Account</button>
</nav>{message && <p className="portal-message" role="status">{message}</p>}{!data ? <div className="tracker-empty">Loading secure dealership data…</div> : section === "opportunities" ? <section className="dealer-opportunity-grid">{data.opportunities.length === 0 ? <div className="tracker-empty">
<strong>No assigned opportunities</strong>
<p>New matching requests will appear here when available within your membership.</p>
</div> : data.opportunities.map((item) => <article className="dealer-opportunity-card" key={String(item.assignment_id)}>
<div className="dealer-opportunity-heading">
<div>
<span>{item.condition} · {item.buyer_market}</span>
<h2>{[item.model_year, item.make, item.model, item.trim].filter(Boolean).join(" ")}</h2>
<p>{item.exterior_color_flexible ? `${item.exterior_color ? `${item.exterior_color} preferred · ` : ""}Any exterior colour accepted` : [item.exterior_color, item.interior_color].filter(Boolean).join(" / ") || "Colour not specified"}</p>
</div>
<div>
<span>Respond by</span>
<strong>{deadlineDate(item.response_deadline)}</strong>
</div>
</div>
<dl>
<div>
<dt>Must-have options</dt>
<dd>{item.must_have_options || "None specified"}</dd>
</div>
<div>
<dt>Year and mileage range</dt>
<dd>{item.min_model_year || item.max_model_year ? `${item.min_model_year || "Any"}–${item.max_model_year || "Any"}` : item.model_year || "Any year"} · {item.minimum_mileage || item.maximum_mileage ? `${Number(item.minimum_mileage || 0).toLocaleString("en-CA")}–${item.maximum_mileage ? Number(item.maximum_mileage).toLocaleString("en-CA") : "Any"} km` : "Mileage not specified"}</dd>
</div>
<div>
<dt>Status</dt>
<dd>{item.offer_id ? `${item.offer_status} · ${money(Number(item.comparable_price_cents))}` : item.assignment_status}</dd>
</div>
</dl>
<SubmittedOffers offers={item.submitted_offers || []} busy={busy} onSaveOutcome={saveOutcome}/>
{item.opportunity_status === "open" && item.assignment_status !== "expired" && new Date(String(item.response_deadline)).getTime() >= Date.now() ? <details>
<summary>{item.offer_id ? "Submit revised offer" : "Enter offer"}</summary>
<OfferForm assignmentId={String(item.assignment_id)} busy={busy} onSubmit={submitOffer}/>
</details> : <div className="portal-warning">{item.assignment_status === "expired" ? "Your one-business-day response window expired. This opportunity remains counted toward the Bronze or Silver monthly allowance." : "This customer report has been completed. Additional pricing is closed and eligible completed opportunities no longer count toward your monthly allowance."}</div>}
</article>)}</section> : section === "inventory" ? <GoldInventorySection tier={data.subscription?.tier} inventory={data.inventory} busy={busy} onUpload={uploadInventory} onReload={load} onMessage={setMessage} /> : <section className="dealer-account-card">
<p className="eyebrow-text">Membership</p>
<h2>{data.identity.dealershipName}</h2>
<dl>
<div>
<dt>Plan</dt>
<dd>{data.subscription?.tier || "Pending"}</dd>
</div>
<div>
<dt>Status</dt>
<dd>{data.subscription?.cancel_at_period_end ? `Cancellation scheduled for ${date(data.subscription.current_period_end)}` : data.subscription?.status || "Awaiting Stripe confirmation"}</dd>
</div>
<div>
<dt>Opportunity allowance</dt>
<dd>{allowance}</dd>
</div>
<div>
<dt>Account owner</dt>
<dd>{data.identity.fullName} · {data.identity.email}</dd>
</div>
</dl>
<section className="dealer-billing-actions" aria-labelledby="dealer-billing-heading">
<div>
<h3 id="dealer-billing-heading">Billing and subscription</h3>
<p>Payment details and cancellations are completed securely on Stripe. Beat My Car Quote never receives or stores your card number.</p>
</div>
{data.subscription ? <div className="dealer-billing-buttons">
<button type="button" className="button-secondary" disabled={busy || !(["owner", "manager"] as string[]).includes(data.identity.role)} onClick={() => void openBillingPortal("payment_method_update")}>Update credit card</button>
<button type="button" className="button-danger-outline" disabled={busy || data.subscription?.cancel_at_period_end || !(["owner", "manager"] as string[]).includes(data.identity.role)} onClick={() => void openBillingPortal("subscription_cancel")}>{data.subscription.cancel_at_period_end ? "Cancellation scheduled" : "Cancel subscription"}</button>
</div> : <p className="portal-warning">Billing controls will appear after Stripe confirms the membership.</p>}
{data.identity.role === "member" && <small>Ask a dealership owner or manager to make billing changes.</small>}
{data.subscription?.cancel_at_period_end && <p className="billing-cancellation-note">Your membership remains available through {date(data.subscription.current_period_end)}. Stripe will not renew it after that date.</p>}
</section>
<p>Your verified business email is your account name. Use the “forgot password” link on the sign-in page to securely replace your password.</p>
<DealerPreferences key={`${data.preferences.manufacturer}-${data.preferences.quote_outside_inventory}`} initial={data.preferences} onSaved={load} />
</section>}</section>
</main>;
}
