"use client";

import { FormEvent, useCallback, useEffect, useMemo, useState } from "react";
import type { Dealer, DealerContact } from "../../lib/dealer-store";
import type { RequestStatus, TrackerRecord } from "../../lib/tracker-store";
import DealerDirectoryPanel from "./dealer-directory";

const statuses: RequestStatus[] = ["New", "Researching", "Ready", "Delivered"];

function formatDate(value: string, includeTime = false) {
  if (!value) return "—";
  const date = includeTime ? new Date(value) : new Date(`${value}T12:00:00`);
  return new Intl.DateTimeFormat("en-CA", {
    dateStyle: "medium",
    ...(includeTime ? { timeStyle: "short" } : {}),
    timeZone: "America/Toronto",
  }).format(date);
}

function vehicle(record: TrackerRecord) {
  return [record.year, record.make, record.model, record.trim].filter(Boolean).join(" ");
}

function overdue(record: TrackerRecord) {
  return record.status !== "Delivered" && record.dueDate < new Date().toISOString().slice(0, 10);
}

export default function AdminTracker({ initiallyAuthenticated }: { initiallyAuthenticated: boolean }) {
  const [authenticated, setAuthenticated] = useState(initiallyAuthenticated);
  const [password, setPassword] = useState("");
  const [records, setRecords] = useState<TrackerRecord[]>([]);
  const [dealers, setDealers] = useState<Dealer[]>([]);
  const [contacts, setContacts] = useState<DealerContact[]>([]);
  const [section, setSection] = useState<"requests" | "directory">("requests");
  const [selectedId, setSelectedId] = useState("");
  const [query, setQuery] = useState("");
  const [status, setStatus] = useState("Active");
  const [message, setMessage] = useState("");
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    const [response, directoryResponse] = await Promise.all([
      fetch("/api/admin/requests", { cache: "no-store" }),
      fetch("/api/admin/dealers", { cache: "no-store" }),
    ]);
    if (response.status === 401) {
      setAuthenticated(false);
      setLoading(false);
      return;
    }
    const data = await response.json();
    const directory = directoryResponse.ok ? await directoryResponse.json() : { dealers: [], contacts: [] };
    setRecords(data.requests || []);
    setDealers(directory.dealers || []);
    setContacts(directory.contacts || []);
    setSelectedId((current) => current || data.requests?.[0]?.id || "");
    setLoading(false);
  }, []);

  useEffect(() => {
    if (authenticated) void load();
  }, [authenticated, load]);

  async function login(event: FormEvent) {
    event.preventDefault();
    setLoading(true);
    setMessage("");
    const response = await fetch("/api/admin/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ password }),
    });
    const data = await response.json();
    setLoading(false);
    if (!response.ok) return setMessage(data.error || "Unable to sign in.");
    setPassword("");
    setAuthenticated(true);
  }

  async function logout() {
    await fetch("/api/admin/logout", { method: "POST" });
    setAuthenticated(false);
    setRecords([]);
  }

  const filtered = useMemo(() => records.filter((record) => {
    const matchesStatus = status === "All" || (status === "Active" ? record.status !== "Delivered" : record.status === status);
    const haystack = `${record.customerName} ${record.customerEmail} ${vehicle(record)} ${record.id}`.toLowerCase();
    return matchesStatus && haystack.includes(query.trim().toLowerCase());
  }), [records, query, status]);

  const selected = records.find((record) => record.id === selectedId) || filtered[0];
  const counts = useMemo(() => ({
    active: records.filter((record) => record.status !== "Delivered").length,
    dueSoon: records.filter((record) => record.status !== "Delivered" && record.dueDate <= new Date(Date.now() + 86400000).toISOString().slice(0, 10)).length,
    ready: records.filter((record) => record.status === "Ready").length,
    delivered: records.filter((record) => record.status === "Delivered").length,
  }), [records]);

  async function save(patch: Record<string, string>): Promise<TrackerRecord | null> {
    if (!selected) return null;
    setMessage("Saving…");
    const response = await fetch("/api/admin/requests", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: selected.id, patch }),
    });
    const data = await response.json();
    if (!response.ok) {
      setMessage(data.error || "Could not save changes.");
      return null;
    }
    setRecords((current) => current.map((record) => record.id === selected.id ? data.request : record));
    setMessage("Saved");
    window.setTimeout(() => setMessage(""), 1800);
    return data.request;
  }

  function replaceRecord(updated: TrackerRecord) {
    setRecords((current) => current.map((record) => record.id === updated.id ? updated : record));
  }

  if (!authenticated) {
    return (
      <main className="tracker-login-page">
        <section className="tracker-login-card">
          <img src="/logo.svg" alt="Beat My Car Quote" />
          <p className="eyebrow-text">Private workspace</p>
          <h1>Request tracker</h1>
          <p>Sign in to view paid customer requests and manage research.</p>
          <form onSubmit={login}>
            <label><span>Admin password</span><input type="password" autoComplete="current-password" value={password} onChange={(event) => setPassword(event.target.value)} required /></label>
            {message && <p className="tracker-error" role="alert">{message}</p>}
            <button className="button" disabled={loading}>{loading ? "Signing in…" : "Sign in"}</button>
          </form>
        </section>
      </main>
    );
  }

  return (
    <main className="tracker-page">
      <header className="tracker-header">
        <img src="/logo-reversed.svg" alt="Beat My Car Quote" />
        <div><span>Internal workspace</span><button onClick={logout}>Sign out</button></div>
      </header>
      <section className="tracker-shell">
        <nav className="admin-section-tabs" aria-label="Admin workspace">
          <button className={section === "requests" ? "active" : ""} onClick={() => setSection("requests")}>Customer requests</button>
          <button className={section === "directory" ? "active" : ""} onClick={() => setSection("directory")}>Dealer directory</button>
          <a href="/admin/enterprise">Enterprise marketplace</a>
        </nav>
        <div className="tracker-title-row">
          {section === "requests" ? <div><p className="eyebrow-text">Operations</p><h1>Customer requests</h1><p>Paid requests, deadlines and dealer research in one place.</p></div> : <div><p className="eyebrow-text">Sourcing</p><h1>Dealer directory</h1><p>Ontario dealerships, contacts and quote-request preparation.</p></div>}
          {section === "requests" && <a className="button button-small" href="/api/admin/export">Export CSV</a>}
        </div>

        {section === "directory" ? <DealerDirectoryPanel dealers={dealers} contacts={contacts} requests={records} onReload={load} /> : <><div className="tracker-metrics">
          <article><span>Active</span><strong>{counts.active}</strong></article>
          <article><span>Due or overdue</span><strong>{counts.dueSoon}</strong></article>
          <article><span>Ready</span><strong>{counts.ready}</strong></article>
          <article><span>Delivered</span><strong>{counts.delivered}</strong></article>
        </div>

        <div className="tracker-toolbar">
          <input type="search" placeholder="Search customer, vehicle or request ID" value={query} onChange={(event) => setQuery(event.target.value)} />
          <select value={status} onChange={(event) => setStatus(event.target.value)}>
            <option>Active</option><option>All</option>{statuses.map((item) => <option key={item}>{item}</option>)}
          </select>
          <button className="button-secondary" onClick={() => void load()}>{loading ? "Refreshing…" : "Refresh"}</button>
        </div>

        {records.length === 0 && !loading ? (
          <div className="tracker-empty"><strong>No paid requests yet</strong><p>New records will appear after Stripe confirms a successful payment.</p></div>
        ) : (
          <div className="tracker-workspace">
            <aside className="tracker-list" aria-label="Customer requests">
              {filtered.map((record) => (
                <button className={record.id === selected?.id ? "active" : ""} key={record.id} onClick={() => setSelectedId(record.id)}>
                  <div><strong>{record.customerName || "Customer"}</strong><span className={`status-pill status-${record.status.toLowerCase()}`}>{record.status}</span></div>
                  <p>{vehicle(record)}</p>
                  <small className={overdue(record) ? "overdue" : ""}>Due {formatDate(record.dueDate)}</small>
                </button>
              ))}
              {filtered.length === 0 && <p className="tracker-no-results">No matching requests.</p>}
            </aside>
            {selected && <RequestEditor key={selected.id} record={selected} dealers={dealers} message={message} onSave={save} onRecordUpdate={replaceRecord} onMessage={setMessage} />}
          </div>
        )}
        </>}
      </section>
    </main>
  );
}

function RequestEditor({ record, dealers, message, onSave, onRecordUpdate, onMessage }: { record: TrackerRecord; dealers: Dealer[]; message: string; onSave: (patch: Record<string, string>) => Promise<TrackerRecord | null>; onRecordUpdate: (record: TrackerRecord) => void; onMessage: (message: string) => void }) {
  const [draft, setDraft] = useState(record);
  const [sending, setSending] = useState(false);
  const dealerSuggestions = useMemo(() => {
    const needle = draft.dealerName.toLowerCase().trim();
    return dealers.filter((dealer) => dealer.active && (!needle || `${dealer.name} ${dealer.city}`.toLowerCase().includes(needle))).slice(0, 60);
  }, [dealers, draft.dealerName]);
  const update = (field: keyof TrackerRecord, value: string) => setDraft((current) => ({ ...current, [field]: value }));
  function selectDealer(value: string) {
    const selectedDealer = dealers.find((dealer) => `${dealer.name} — ${dealer.city}` === value || dealer.name === value);
    if (!selectedDealer) return update("dealerName", value);
    setDraft((current) => ({
      ...current,
      dealerName: selectedDealer.name,
      dealerLocation: [selectedDealer.address, selectedDealer.city, selectedDealer.province, selectedDealer.postalCode].filter(Boolean).join(", "),
      dealerContactPhone: current.dealerContactPhone || selectedDealer.phone,
    }));
  }
  const patch = () => ({
    status: draft.status,
    dueDate: draft.dueDate,
    assignedTo: draft.assignedTo,
    dealerName: draft.dealerName,
    dealerLocation: draft.dealerLocation,
    dealerContactName: draft.dealerContactName,
    dealerContactEmail: draft.dealerContactEmail,
    dealerContactPhone: draft.dealerContactPhone,
    bestPrice: draft.bestPrice,
    quoteDate: draft.quoteDate,
    quoteValidUntil: draft.quoteValidUntil,
    priceConditions: draft.priceConditions,
    dealerQuotes: draft.dealerQuotes,
    recommendation: draft.recommendation,
    internalNotes: draft.internalNotes,
    deliveredAt: draft.status === "Delivered" ? (draft.deliveredAt || new Date().toISOString()) : "",
  });
  const save = () => onSave(patch());

  async function previewReport() {
    const preview = window.open("", "_blank");
    const saved = await save();
    if (!saved) return preview?.close();
    if (preview) preview.location.href = `/api/admin/report?id=${encodeURIComponent(saved.id)}`;
    else window.location.href = `/api/admin/report?id=${encodeURIComponent(saved.id)}`;
  }

  async function sendReport() {
    if (!window.confirm(`Email the completed report to ${draft.customerEmail}?`)) return;
    setSending(true);
    const saved = await save();
    if (!saved) return setSending(false);
    onMessage("Sending report…");
    const response = await fetch("/api/admin/report", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: saved.id }),
    });
    const data = await response.json();
    setSending(false);
    if (!response.ok) return onMessage(data.error || "The report could not be sent.");
    setDraft(data.request);
    onRecordUpdate(data.request);
    onMessage(`Report sent to ${data.request.reportSentTo}`);
  }

  return (
    <article className="tracker-detail">
      <div className="tracker-detail-heading">
        <div><span>Request {record.id.slice(0, 8).toUpperCase()}</span><h2>{vehicle(record)}</h2><p>Submitted {formatDate(record.submittedAt, true)}</p></div>
        <span className={`status-pill status-${draft.status.toLowerCase()}`}>{draft.status}</span>
      </div>

      <div className="tracker-detail-grid">
        <section><h3>Customer</h3><dl><div><dt>Name</dt><dd>{record.customerName || "—"}</dd></div><div><dt>Email</dt><dd><a href={`mailto:${record.customerEmail}`}>{record.customerEmail || "—"}</a></dd></div><div><dt>Phone</dt><dd>{record.customerPhone || "—"}</dd></div><div><dt>Location</dt><dd>{[record.buyerLocation, record.postalCode].filter(Boolean).join(" · ") || "—"}</dd></div></dl></section>
        <section><h3>Vehicle brief</h3><dl><div><dt>Condition</dt><dd>{record.condition || "—"}</dd></div><div><dt>Colours</dt><dd>{[record.exteriorColor, record.interiorColor].filter(Boolean).join(" / ") || "—"}</dd></div><div><dt>Options</dt><dd>{record.mustHaveOptions || "—"}</dd></div><div><dt>Mileage</dt><dd>{record.maxMileage || "—"}</dd></div><div><dt>Budget</dt><dd>{record.targetBudget || "—"}</dd></div><div><dt>Flexibility</dt><dd>{record.flexibility || "—"}</dd></div></dl></section>
      </div>
      {record.customerNotes && <section className="tracker-customer-note"><h3>Customer notes</h3><p>{record.customerNotes}</p></section>}

      <section className="tracker-edit-form">
        <h3>Research workflow</h3>
        <div className="field-grid three">
          <label><span>Status</span><select value={draft.status} onChange={(event) => update("status", event.target.value)}>{statuses.map((item) => <option key={item}>{item}</option>)}</select></label>
          <label><span>Due date</span><input type="date" value={draft.dueDate} onChange={(event) => update("dueDate", event.target.value)} /></label>
          <label><span>Assigned to</span><input value={draft.assignedTo} onChange={(event) => update("assignedTo", event.target.value)} placeholder="Researcher name" /></label>
        </div>
        <div className="field-grid three">
          <label><span>Recommended dealer</span><input list="dealer-directory-options" value={draft.dealerName} onChange={(event) => selectDealer(event.target.value)} placeholder="Type to search dealerships" /><datalist id="dealer-directory-options">{dealerSuggestions.map((dealer) => <option key={dealer.id} value={`${dealer.name} — ${dealer.city}`} />)}</datalist></label>
          <label><span>Dealer location</span><input value={draft.dealerLocation} onChange={(event) => update("dealerLocation", event.target.value)} /></label>
          <label><span>Best price</span><input value={draft.bestPrice} onChange={(event) => update("bestPrice", event.target.value)} placeholder="$" /></label>
        </div>
        <div className="field-grid three">
          <label><span>Dealer contact name</span><input value={draft.dealerContactName} onChange={(event) => update("dealerContactName", event.target.value)} placeholder="Contact name" /></label>
          <label><span>Dealer contact email</span><input type="email" value={draft.dealerContactEmail} onChange={(event) => update("dealerContactEmail", event.target.value)} /></label>
          <label><span>Dealer contact phone</span><input type="tel" value={draft.dealerContactPhone} onChange={(event) => update("dealerContactPhone", event.target.value)} /></label>
        </div>
        <div className="field-grid three">
          <label><span>Quote date</span><input type="date" value={draft.quoteDate} onChange={(event) => update("quoteDate", event.target.value)} /></label>
          <label><span>Price valid until</span><input type="date" value={draft.quoteValidUntil} onChange={(event) => update("quoteValidUntil", event.target.value)} /></label>
        </div>
        <label className="full-field"><span>Price conditions and included fees</span><textarea value={draft.priceConditions} onChange={(event) => update("priceConditions", event.target.value)} placeholder="State what the price includes or excludes, availability, financing conditions and any dealer fees…" /></label>
        <label className="full-field"><span>Dealer quotes researched</span><textarea value={draft.dealerQuotes} onChange={(event) => update("dealerQuotes", event.target.value)} placeholder="Dealer, contact, quoted price, fees and date…" /></label>
        <label className="full-field"><span>Personalized customer recommendation</span><textarea value={draft.recommendation} onChange={(event) => update("recommendation", event.target.value)} placeholder="Add the request-specific advice that will appear after the standard buyer guidance…" /></label>
        <label className="full-field"><span>Internal notes</span><textarea value={draft.internalNotes} onChange={(event) => update("internalNotes", event.target.value)} /></label>
        {draft.deliveredAt && <div className="report-delivery-status"><strong>Report sent</strong><span>{formatDate(draft.deliveredAt, true)} to {draft.reportSentTo || draft.customerEmail}</span></div>}
        <div className="tracker-save-row">
          <span aria-live="polite">{message}</span>
          <div className="report-actions">
            <button className="button-secondary" onClick={() => void previewReport()} disabled={sending}>Preview PDF</button>
            <button className="button-secondary" onClick={() => void save()} disabled={sending}>Save request</button>
            <button className="button" onClick={() => void sendReport()} disabled={sending}>{sending ? "Sending…" : "Email report"}</button>
          </div>
        </div>
      </section>
    </article>
  );
}
