"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState, type FormEvent } from "react";
import { api, attributionNow, fallbackMessage, hubspotIdentify } from "./api";
import { Field } from "./Field";
import { LimitedTextarea } from "./LimitedTextarea";

/* Applications, messages and account settings (/hub/account, inside the dashboard design). Data from GET /api/hub/dashboard; edits through /api/hub/account*.
   AdMedia publisher accounts (editable: false) get a note instead of the details and password forms. */

type User = { name: string; email: string; company: string | null; website: string | null; role: "PUBLISHER" | "ADMIN" };
type App = { id: string; leadType: string; status: string; property: string; goal: string; selectedProducts: string[]; createdAt: string };
type Msg = { id: string; topic: string; status: string; message: string; createdAt: string };
type Data = { user: User; editable?: boolean; applications: App[]; messages: Msg[]; summary: { applications: number; open: number; approved: number; properties: number; products: string[] } };

export const STATUS_LABEL: Record<string, string> = { NEW: "Received", REVIEWING: "In review", CONTACTED: "We contacted you", APPROVED: "Approved", DECLINED: "Not approved", SPAM: "Closed" };
const STATUS_TONE: Record<string, string> = { NEW: "validate", REVIEWING: "validate", CONTACTED: "proposed", APPROVED: "listed", DECLINED: "blocked", SPAM: "blocked" };
export const date = (s: string) => new Date(s).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" });

export function StatusBadge({ status, labels = STATUS_LABEL }: { status: string; labels?: Record<string, string> }) {
  return <span className={`pstat pstat--${STATUS_TONE[status] ?? "validate"}`}>{labels[status] ?? status}</span>;
}

export default function Dashboard({ welcome = false, embedded = false }: { welcome?: boolean; embedded?: boolean }) {
  const router = useRouter();
  const [data, setData] = useState<Data | null>(null);
  const [error, setError] = useState("");
  const [version, setVersion] = useState(0);
  const load = () => setVersion((v) => v + 1);

  useEffect(() => {
    let alive = true;
    api<Data>("/api/hub/dashboard").then((r) => {
      if (!alive) return;
      if (r.status === 401) return router.replace(`/hub-login?next=${embedded ? "/hub/account" : "/hub"}`);
      if (!r.ok) return setError(fallbackMessage(r));
      setData(r);
    });
    return () => { alive = false; };
  }, [router, version, embedded]);

  async function signOut() {
    await api("/api/auth/logout", "POST");
    router.replace("/hub-login");
    router.refresh();
  }

  const wrap = embedded ? "hub" : "mz-wrap hub";
  if (error) return <div className={wrap}><p className="form__err" role="alert">{error}</p></div>;
  if (!data) return <div className={wrap}><p className="hub-hint" role="status">Loading your dashboard…</p></div>;
  const { user, applications, messages, summary, editable = true } = data;

  return (
    <div className={wrap}>
      {embedded ? null : <div className="hub__head">
        <div>
          <p className="eyebrow eyebrow--caps">Monetize Hub</p>
          <h1>Hi, {user.name.split(/\s+/)[0]}</h1>
          <p className="hub-hint">{user.email}{user.company ? ` · ${user.company}` : ""}</p>
        </div>
        <div className="hub__actions">
          {user.role === "ADMIN" ? <Link className="mz-btn mz-btn--secondary" href="/admin">Staff dashboard</Link> : null}
          <Link className="mz-btn mz-btn--primary" href="/contact?cta=hub#apply" data-open-apply="" data-cta="hub">New application</Link>
          <button type="button" className="mz-btn mz-btn--secondary" onClick={signOut}>Sign out</button>
        </div>
      </div>}

      {welcome ? <p className="login__note hub__welcome" role="status">Your email is confirmed and you&rsquo;re signed in. Welcome to Monetize Hub.</p> : null}

      <ul className="hub-stats" aria-label="Summary">
        <li><b>{summary.applications}</b><span>Applications</span></li>
        <li><b>{summary.open}</b><span>In progress</span></li>
        <li><b>{summary.approved}</b><span>Approved</span></li>
        <li><b>{summary.properties}</b><span>Sites and apps</span></li>
      </ul>

      <section className="hub-card" aria-labelledby="apps-title">
        <div className="hub-card__head">
          <h2 id="apps-title">Your applications</h2>
          <Link className="mz-link" href="/contact?cta=hub#apply">Start another</Link>
        </div>
        {applications.length ? (
          <div className="hub-table" role="region" aria-label="Applications table" tabIndex={0}>
            <table>
              <thead><tr><th scope="col">Reference</th><th scope="col">Site or app</th><th scope="col">Products</th><th scope="col">Status</th><th scope="col">Sent</th></tr></thead>
              <tbody>
                {applications.map((a) => (
                  <tr key={a.id}>
                    <td className="hub-mono">{a.id}</td>
                    <td>{a.property}</td>
                    <td>{a.selectedProducts.length ? a.selectedProducts.join(", ") : <span className="hub-hint">None picked</span>}</td>
                    <td><StatusBadge status={a.status} /></td>
                    <td>{date(a.createdAt)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="hub-empty">No applications yet. <Link className="mz-link" href="/contact?cta=hub#apply">Start one</Link> and it will show up here, sent with {user.email}.</p>
        )}
      </section>

      <div className="hub-grid">
        <section className="hub-card" aria-labelledby="rep-title">
          <h2 id="rep-title">Reporting and payments</h2>
          <p className="hub-hint">Revenue reports and payouts stay in each product&rsquo;s own dashboard, so they aren&rsquo;t shown here yet.</p>
          <p><Link className="mz-link" href="/login">Find your product&rsquo;s login</Link></p>
          {summary.products.length ? (
            <>
              <h3 className="hub-sub">Products you picked</h3>
              <ul className="hub-tags">{summary.products.map((p) => <li key={p}>{p}</li>)}</ul>
            </>
          ) : null}
        </section>
        <Messages messages={messages} onSent={load} user={user} />
      </div>

      {editable ? (
        <div className="hub-grid">
          <Profile user={user} onSaved={load} />
          <Password />
        </div>
      ) : (
        <section className="hub-card" aria-labelledby="admedia-title">
          <h2 id="admedia-title">Your details and password</h2>
          <p className="hub-hint">You signed in with your AdMedia publisher account, so your details and password are managed there and work the same on AdMedia and Monetize.com.</p>
          <p>
            <a className="mz-link" href="https://members.admedia.com/" target="_blank" rel="noopener">Open your AdMedia account</a>
            {" · "}
            <Link className="mz-link" href="/contact?topic=support&product=Monetize.com%20Publisher%20Hub&cta=hub-account-details#message">Ask support to change them</Link>
          </p>
        </section>
      )}
    </div>
  );
}

function Messages({ messages, onSent, user }: { messages: Msg[]; onSent: () => void; user: User }) {
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [note, setNote] = useState("");
  const [busy, setBusy] = useState(false);
  async function send(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = e.currentTarget;
    const message = (f.elements.namedItem("message") as HTMLTextAreaElement).value.trim();
    if (message.length < 10) return setErrors({ message: "Write a little more so we can help (at least 10 characters)." });
    setBusy(true);
    const r = await api("/api/contact", "POST", { name: user.name, email: user.email, company: user.company ?? "", topic: "support", message, source: "/hub", attribution: attributionNow() });
    setBusy(false);
    if (!r.ok) return (setErrors(r.errors ?? {}), setNote(r.errors ? "" : fallbackMessage(r)));
    hubspotIdentify(user.email);
    f.reset();
    setErrors({});
    setNote("Sent. We'll reply by email.");
    onSent();
  }
  return (
    <section className="hub-card" aria-labelledby="msg-title">
      <h2 id="msg-title">Messages to our team</h2>
      {messages.length ? (
        <ul className="hub-list">
          {messages.slice(0, 5).map((m) => (
            <li key={m.id}><StatusBadge status={m.status} labels={{ NEW: "Sent", REVIEWING: "In progress", CONTACTED: "Answered", APPROVED: "Answered", DECLINED: "Closed", SPAM: "Closed" }} /> <span className="hub-hint">{date(m.createdAt)}</span><p>{m.message.length > 140 ? `${m.message.slice(0, 140)}…` : m.message}</p></li>
          ))}
        </ul>
      ) : <p className="hub-hint">No messages yet.</p>}
      <form className="login__form" onSubmit={send} noValidate>
        <div className={`field${errors.message ? " is-invalid" : ""}`}>
          <label htmlFor="hub-msg">Ask our team</label>
          <LimitedTextarea id="hub-msg" name="message" rows={3} max={5000} aria-invalid={errors.message ? true : undefined} aria-describedby="hub-msg-err" />
          <p className="field__err" id="hub-msg-err">{errors.message ?? ""}</p>
        </div>
        {note ? <p className={note.startsWith("Sent") ? "login__note" : "form__err"} role="status">{note}</p> : null}
        <button type="submit" className="mz-btn mz-btn--secondary" disabled={busy}>{busy ? "Sending…" : "Send message"}</button>
      </form>
    </section>
  );
}

function Profile({ user, onSaved }: { user: User; onSaved: () => void }) {
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [note, setNote] = useState("");
  async function save(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = e.currentTarget;
    const v = (n: string) => (f.elements.namedItem(n) as HTMLInputElement).value.trim();
    const r = await api("/api/hub/account", "PATCH", { name: v("name"), company: v("company"), website: v("website") });
    setErrors(r.errors ?? {});
    setNote(r.ok ? "Saved." : r.errors ? "" : fallbackMessage(r));
    if (r.ok) onSaved();
  }
  return (
    <section className="hub-card" aria-labelledby="prof-title">
      <h2 id="prof-title">Your details</h2>
      <form className="login__form" onSubmit={save} noValidate>
        <Field label="Name" name="name" defaultValue={user.name} autoComplete="name" error={errors.name} />
        <Field label="Email" name="email" defaultValue={user.email} readOnly hint="Contact us to change the email on your account." />
        <Field label="Company" name="company" defaultValue={user.company ?? ""} autoComplete="organization" error={errors.company} />
        <Field label="Website" name="website" defaultValue={user.website ?? ""} inputMode="url" error={errors.website} />
        {note ? <p className={note === "Saved." ? "login__note" : "form__err"} role="status">{note}</p> : null}
        <button type="submit" className="mz-btn mz-btn--secondary">Save details</button>
      </form>
    </section>
  );
}

function Password() {
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [note, setNote] = useState("");
  async function save(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = e.currentTarget;
    const v = (n: string) => (f.elements.namedItem(n) as HTMLInputElement).value;
    if (v("newPassword") !== v("confirm")) return setErrors({ confirm: "The passwords don't match." });
    const r = await api("/api/hub/account/password", "POST", { currentPassword: v("currentPassword"), newPassword: v("newPassword") });
    setErrors(r.errors ?? {});
    setNote(r.ok ? "Password changed. Other devices were signed out." : r.errors ? "" : fallbackMessage(r));
    if (r.ok) f.reset();
  }
  return (
    <section className="hub-card" aria-labelledby="pw-title">
      <h2 id="pw-title">Change password</h2>
      <form className="login__form" onSubmit={save} noValidate>
        <Field label="Current password" name="currentPassword" password autoComplete="current-password" error={errors.currentPassword} />
        <Field label="New password" name="newPassword" password autoComplete="new-password" error={errors.newPassword} hint="At least 10 characters, with letters and a number." />
        <Field label="Repeat the new password" name="confirm" password autoComplete="new-password" error={errors.confirm} />
        {note ? <p className={note.startsWith("Password changed") ? "login__note" : "form__err"} role="status">{note}</p> : null}
        <button type="submit" className="mz-btn mz-btn--secondary">Change password</button>
      </form>
    </section>
  );
}
