"use client";

import { FormEvent, useState } from "react";

type LeadRow = {
  id: string;
  kind: string;
  createdAt: string;
  name: string;
  phone: string;
  email: string;
  subject: string;
  message: string;
  date: string;
  time: string;
  garments: string;
  address: string;
  bookingRef: string;
  emailStatus: string;
  crmStatus: string;
};

export default function AdminLeadsPage() {
  const [key, setKey] = useState("");
  const [leads, setLeads] = useState<LeadRow[]>([]);
  const [error, setError] = useState("");
  const [loaded, setLoaded] = useState(false);

  async function load(e?: FormEvent) {
    e?.preventDefault();
    setError("");
    const res = await fetch("/api/leads", {
      headers: { "x-leads-key": key },
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok || !data.success) {
      setLoaded(false);
      setLeads([]);
      setError(data.error || "Could not load leads.");
      return;
    }
    setLeads(data.leads || []);
    setLoaded(true);
  }

  return (
    <main
      style={{
        minHeight: "100vh",
        padding: "110px 8vw 80px",
        background: "#1a1918",
        color: "#fff",
        fontFamily: "Jost, Helvetica, Arial, sans-serif",
      }}
    >
      <p style={{ color: "#C9A84C", letterSpacing: "0.2em", fontSize: 11, textTransform: "uppercase" }}>
        Internal
      </p>
      <h1 style={{ fontFamily: "Cormorant Garamond, Georgia, serif", fontWeight: 300, fontSize: 42, margin: "8px 0 24px" }}>
        Contact & pickup leads
      </h1>
      <form onSubmit={load} style={{ display: "flex", gap: 12, marginBottom: 28, flexWrap: "wrap" }}>
        <input
          type="password"
          value={key}
          onChange={(e) => setKey(e.target.value)}
          placeholder="Admin key"
          style={{
            background: "rgba(255,255,255,.06)",
            border: "1px solid rgba(255,255,255,.12)",
            color: "#fff",
            padding: "10px 14px",
            minWidth: 240,
          }}
        />
        <button
          type="submit"
          style={{
            background: "#C0415A",
            color: "#fff",
            border: 0,
            padding: "10px 18px",
            letterSpacing: "0.14em",
            textTransform: "uppercase",
            fontSize: 11,
            cursor: "pointer",
          }}
        >
          Load
        </button>
      </form>
      {error ? <p style={{ color: "#C0415A", marginBottom: 20 }}>{error}</p> : null}
      {loaded ? (
        <p style={{ color: "rgba(255,255,255,.55)", marginBottom: 16 }}>{leads.length} saved lead(s)</p>
      ) : null}
      <div style={{ display: "grid", gap: 14 }}>
        {leads.map((lead) => (
          <article
            key={lead.id}
            style={{
              border: "1px solid rgba(255,255,255,.1)",
              background: "rgba(255,255,255,.04)",
              padding: 18,
            }}
          >
            <p style={{ color: "#C9A84C", fontSize: 11, letterSpacing: "0.16em", textTransform: "uppercase" }}>
              {lead.kind} · {new Date(lead.createdAt).toLocaleString("en-IN")}
            </p>
            <h2 style={{ fontSize: 20, fontWeight: 400, margin: "6px 0 10px" }}>
              {lead.name || "Unnamed"} {lead.bookingRef ? `· ${lead.bookingRef}` : ""}
            </h2>
            <p style={{ color: "rgba(255,255,255,.75)", lineHeight: 1.7 }}>
              {lead.phone}
              {lead.email ? ` · ${lead.email}` : ""}
              {lead.subject ? ` · ${lead.subject}` : ""}
              {lead.date ? ` · ${lead.date} ${lead.time}` : ""}
              {lead.garments ? ` · ${lead.garments} garments` : ""}
            </p>
            {lead.address ? (
              <p style={{ color: "rgba(255,255,255,.6)", marginTop: 6 }}>{lead.address}</p>
            ) : null}
            {lead.message ? (
              <p style={{ color: "rgba(255,255,255,.82)", marginTop: 10, whiteSpace: "pre-wrap" }}>{lead.message}</p>
            ) : null}
            <p style={{ color: "rgba(255,255,255,.4)", marginTop: 10, fontSize: 12 }}>
              Email: {lead.emailStatus} · CRM: {lead.crmStatus} · {lead.id}
            </p>
          </article>
        ))}
      </div>
    </main>
  );
}
