"use client";

/** /admin/inquiries: everything sent from the website's forms, by source and status. */
import Link from "next/link";
import { useEffect, useState } from "react";
import { errorMessage } from "@/app/(admin)/_lib/api";
import { SOURCES, SOURCE_LABEL, STATUSES, exportInquiries, statusOf, type InquiryQuery } from "@/app/(admin)/_lib/inquiries";
import { useInquiries, useInquirySummary } from "@/app/(admin)/_lib/queries";
import { useStore } from "@/app/(admin)/_lib/store";
import { Icon } from "./Icon";
import { PageHeader } from "./ui";

const received = (iso: string) => new Date(iso).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" });

export function InquiriesList() {
  const { toast } = useStore();
  const [q, setQ] = useState<InquiryQuery>({ page: 1, limit: 20, status: "", source: "", search: "", from: "", to: "" });
  const [searchText, setSearchText] = useState("");
  useEffect(() => {
    const t = setTimeout(() => setQ((p) => (p.search === searchText ? p : { ...p, search: searchText, page: 1 })), 300);
    return () => clearTimeout(t);
  }, [searchText]);
  const set = (patch: Partial<InquiryQuery>) => setQ((p) => ({ ...p, ...patch, page: patch.page ?? 1 }));
  const { data, error, isPending, isFetching, refetch } = useInquiries(q);
  const { data: summary } = useInquirySummary();
  const rows = data?.data ?? [];
  const meta = data?.meta;
  const filtered = !!(q.status || q.source || q.search || q.from || q.to);
  const [exporting, setExporting] = useState(false);

  const doExport = async () => {
    setExporting(true);
    try {
      await exportInquiries(q);
    } catch (e) {
      toast(`Export failed: ${errorMessage(e)}`);
    } finally {
      setExporting(false);
    }
  };

  const count = (source: (typeof SOURCES)[number]["value"]) => (summary ? (source ? (summary.bySource[source] ?? 0) : summary.total) : null);

  return (
    <div className="page">
      <PageHeader
        crumb="People"
        title="Inquiries"
        desc={
          <>
            Everything sent from the website&apos;s forms: Contact page, Home page, Media &amp; Insights and product &quot;Request a quote&quot;. Nothing is emailed yet, so check here.
            {summary && summary.byStatus.new ? (
              <>
                {" "}
                <b>{summary.byStatus.new} new.</b>
              </>
            ) : null}
          </>
        }
      >
        <button type="button" className="btn btn-outline btn-sm" disabled={exporting} onClick={doExport} title="Download the inquiries shown with these filters (up to 5000)">
          {exporting ? <span className="spin dark" /> : <Icon name="file" size={14} />}
          Export CSV
        </button>
      </PageHeader>

      <div className="seg" role="tablist" aria-label="Source" style={{ marginBottom: 16, flexWrap: "wrap" }}>
        {SOURCES.map((s) => {
          const n = count(s.value);
          return (
            <button key={s.value || "all"} type="button" role="tab" aria-selected={q.source === s.value} className={q.source === s.value ? "on" : ""} onClick={() => set({ source: s.value })}>
              {s.label}
              {n != null && <span style={{ marginLeft: 6, opacity: 0.7 }}>{n}</span>}
            </button>
          );
        })}
      </div>

      <div className="card">
        <div className="toolbar" style={{ flexWrap: "wrap" }}>
          <div className="search">
            <Icon name="search" />
            <input placeholder="Search name, email, company, phone, product…" aria-label="Search inquiries" maxLength={100} value={searchText} onChange={(e) => setSearchText(e.target.value)} />
          </div>
          <select className="select" aria-label="Status" value={q.status} onChange={(e) => set({ status: e.target.value as InquiryQuery["status"] })}>
            <option value="">Any status</option>
            {STATUSES.map((s) => (
              <option key={s.value} value={s.value}>
                {s.label}
                {summary ? ` (${summary.byStatus[s.value] ?? 0})` : ""}
              </option>
            ))}
          </select>
          <label style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--muted)" }}>
            From
            <input type="date" className="input input-sm" style={{ width: "auto" }} value={q.from} max={q.to || undefined} onChange={(e) => set({ from: e.target.value })} />
          </label>
          <label style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--muted)" }}>
            To
            <input type="date" className="input input-sm" style={{ width: "auto" }} value={q.to} min={q.from || undefined} onChange={(e) => set({ to: e.target.value })} />
          </label>
          {filtered && (
            <button
              type="button"
              className="btn-plain"
              onClick={() => {
                setSearchText("");
                setQ((p) => ({ ...p, status: "", source: "", search: "", from: "", to: "", page: 1 }));
              }}
            >
              Clear filters
            </button>
          )}
          {isFetching && !isPending && <span className="spin dark" aria-label="Updating" />}
        </div>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Received</th>
                <th>From</th>
                <th>Company</th>
                <th>Source</th>
                <th>Inquiry</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {isPending ? (
                <tr>
                  <td className="empty" colSpan={6}>
                    <span className="spin dark" /> Loading inquiries…
                  </td>
                </tr>
              ) : error ? (
                <tr>
                  <td className="empty" colSpan={6}>
                    {errorMessage(error)}{" "}
                    <button type="button" className="link" onClick={() => refetch()}>
                      Retry
                    </button>
                  </td>
                </tr>
              ) : rows.length === 0 ? (
                <tr>
                  <td className="empty" colSpan={6}>
                    {filtered ? "No inquiries match." : "No inquiries yet. Submissions from the website's forms appear here."}
                  </td>
                </tr>
              ) : (
                rows.map((r) => {
                  const st = statusOf(r.status);
                  return (
                    <tr key={r.id} style={r.status === "new" ? { fontWeight: 500 } : undefined}>
                      <td style={{ color: "var(--muted)", whiteSpace: "nowrap" }}>{received(r.createdAt)}</td>
                      <td>
                        <Link href={`/admin/inquiries/${r.id}`} className="link">
                          <b>{r.name}</b>
                        </Link>
                        <div style={{ color: "var(--muted)", fontSize: 12 }}>{r.email}</div>
                      </td>
                      <td>{r.company || "—"}</td>
                      <td>{SOURCE_LABEL[r.source] ?? r.source}</td>
                      <td>
                        {r.product ? (
                          <>
                            Quote: {r.product.name}
                            {r.product.sku && <div style={{ color: "var(--muted)", fontSize: 12 }}>SKU {r.product.sku}</div>}
                          </>
                        ) : (
                          (r.inquiryType?.label ?? "—")
                        )}
                        {(r.hasMessage || r.notesCount > 0) && (
                          <div style={{ color: "var(--muted)", fontSize: 12 }}>
                            {[r.hasMessage && "Has a message", r.notesCount > 0 && `${r.notesCount} note${r.notesCount === 1 ? "" : "s"}`].filter(Boolean).join(" · ")}
                          </div>
                        )}
                      </td>
                      <td>
                        <span className={`tag ${st.tone}`}>{st.label}</span>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
        {meta && meta.totalPages > 1 && (
          <div className="pager">
            <span>
              {(meta.page - 1) * meta.limit + 1}–{Math.min(meta.page * meta.limit, meta.total)} of {meta.total}
            </span>
            <div>
              <button type="button" className="btn btn-outline btn-sm" disabled={meta.page <= 1} onClick={() => set({ page: meta.page - 1 })}>
                Previous
              </button>
              <button type="button" className="btn btn-outline btn-sm" disabled={meta.page >= meta.totalPages} onClick={() => set({ page: meta.page + 1 })}>
                Next
              </button>
            </div>
          </div>
        )}
      </div>
      <p className="note">
        Statuses: New → In progress (automatic when the first note is added) → Closed; mark junk as Spam. Inquiry types are edited in the Contact and Media &amp; Insights page content: keep a
        type&apos;s key when renaming its label so older inquiries stay filterable.
      </p>
    </div>
  );
}
