"use client";

/** /admin/inquiries/<id>: one inquiry with its notes; change its status or delete it. */
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, type ReactNode } from "react";
import { ApiError, errorMessage } from "@/app/(admin)/_lib/api";
import { SOURCE_LABEL, STATUSES, inquiriesApi, statusOf, type Inquiry, type InquiryStatus } from "@/app/(admin)/_lib/inquiries";
import { qk, useInquiry } from "@/app/(admin)/_lib/queries";
import { useStore } from "@/app/(admin)/_lib/store";
import { Icon } from "./Icon";
import { ConfirmDialog } from "./Modal";
import { PageHeader } from "./ui";

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

/** "NL" → "Netherlands" (falls back to the code). */
function countryName(code: string) {
  try {
    return new Intl.DisplayNames(undefined, { type: "region" }).of(code) ?? code;
  } catch {
    return code;
  }
}
function languageName(code: string) {
  try {
    return new Intl.DisplayNames(undefined, { type: "language" }).of(code) ?? code;
  } catch {
    return code;
  }
}

function Row({ label, children }: { label: string; children: ReactNode }) {
  return (
    <>
      <dt>{label}</dt>
      <dd>{children}</dd>
    </>
  );
}

export function InquiryDetail({ id }: { id: string }) {
  const { data: inq, error, isPending, refetch } = useInquiry(id);

  if (isPending)
    return (
      <div className="page">
        <div className="card">
          <div className="card-b">
            <span className="spin dark" /> Loading the inquiry…
          </div>
        </div>
      </div>
    );
  if (error || !inq)
    return (
      <div className="page">
        <PageHeader crumb={<Link href="/admin/inquiries">Inquiries</Link>} title={error instanceof ApiError && error.status === 404 ? "Inquiry not found" : "Couldn't load the inquiry"} desc={errorMessage(error)}>
          {!(error instanceof ApiError && error.status === 404) && (
            <button type="button" className="btn btn-outline btn-sm" onClick={() => refetch()}>
              Retry
            </button>
          )}
        </PageHeader>
      </div>
    );
  return <Detail inq={inq} />;
}

function Detail({ inq }: { inq: Inquiry }) {
  const qc = useQueryClient();
  const router = useRouter();
  const { toast } = useStore();
  const [busy, setBusy] = useState<"status" | "note" | "delete" | null>(null);
  const [note, setNote] = useState("");
  const [noteErr, setNoteErr] = useState<string | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [deleteErr, setDeleteErr] = useState<string | null>(null);

  /** Store the answer as the inquiry and refresh the list and the counts. */
  const apply = (next: Inquiry) => {
    qc.setQueryData(qk.inquiry(next.id), next);
    void qc.invalidateQueries({ queryKey: qk.inquiries() });
    void qc.invalidateQueries({ queryKey: qk.inquirySummary });
  };

  const changeStatus = async (status: InquiryStatus) => {
    setBusy("status");
    try {
      apply(await inquiriesApi.setStatus(inq.id, status));
      toast(`Marked as ${statusOf(status).label.toLowerCase()}`);
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const addNote = async () => {
    const text = note.trim();
    if (!text) return setNoteErr("Write the note first.");
    setBusy("note");
    setNoteErr(null);
    try {
      apply(await inquiriesApi.addNote(inq.id, text));
      setNote("");
    } catch (e) {
      setNoteErr(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const remove = async () => {
    setBusy("delete");
    setDeleteErr(null);
    try {
      await inquiriesApi.remove(inq.id);
      qc.removeQueries({ queryKey: qk.inquiry(inq.id) });
      void qc.invalidateQueries({ queryKey: qk.inquiries() });
      void qc.invalidateQueries({ queryKey: qk.inquirySummary });
      toast(`Deleted the inquiry from ${inq.name}`);
      router.push("/admin/inquiries");
    } catch (e) {
      setDeleteErr(errorMessage(e));
      setBusy(null);
    }
  };

  const st = statusOf(inq.status);
  const meeting = [inq.meeting?.date, inq.meeting?.time].filter(Boolean).join(", ");
  const tel = inq.phone?.replace(/[^\d+]/g, "");

  return (
    <div className="page">
      <PageHeader
        crumb={<Link href="/admin/inquiries">Inquiries</Link>}
        title={inq.name}
        desc={
          <>
            {SOURCE_LABEL[inq.source] ?? inq.source} · received {at(inq.createdAt)} <span className={`tag ${st.tone}`}>{st.label}</span>
          </>
        }
      >
        <select className="select" aria-label="Status" value={inq.status} disabled={busy === "status"} onChange={(e) => changeStatus(e.target.value as InquiryStatus)}>
          {STATUSES.map((s) => (
            <option key={s.value} value={s.value}>
              {s.label}
            </option>
          ))}
        </select>
        <button
          type="button"
          className="btn btn-outline btn-sm"
          onClick={() => {
            setDeleteErr(null);
            setDeleting(true);
          }}
        >
          Delete
        </button>
      </PageHeader>

      <div className="grid-2">
        <div>
          <div className="card" style={{ marginBottom: 16 }}>
            <div className="card-h">
              <h3>Inquiry</h3>
            </div>
            <div className="card-b">
              <dl className="kv">
                {inq.product ? (
                  <>
                    <Row label="Product">
                      <a href={`/products/${inq.product.slug}`} target="_blank" rel="noreferrer" className="link">
                        {inq.product.name}
                      </a>
                    </Row>
                    {inq.product.sku && <Row label="SKU">{inq.product.sku}</Row>}
                    {inq.quantity && <Row label="Quantity">{`${inq.quantity.value} ${inq.quantity.unit === "mt" ? "MT" : inq.quantity.unit}`}</Row>}
                  </>
                ) : (
                  <Row label="Inquiry type">{inq.inquiryType?.label ?? "—"}</Row>
                )}
                {meeting && <Row label="Meeting">{meeting}</Row>}
                <Row label="Message">{inq.message ? <span style={{ whiteSpace: "pre-wrap" }}>{inq.message}</span> : <span style={{ color: "var(--muted)" }}>No message</span>}</Row>
              </dl>
            </div>
          </div>

          <div className="card">
            <div className="card-h">
              <h3>Notes</h3>
              <span className="sub">Internal: never shown to the visitor</span>
            </div>
            <div className="card-b">
              {inq.notes.length === 0 ? (
                <p className="note" style={{ marginTop: 0 }}>
                  No notes yet. The first note moves a new inquiry to In progress.
                </p>
              ) : (
                <ul style={{ display: "flex", flexDirection: "column", gap: 12, marginBottom: 16, listStyle: "none", padding: 0 }}>
                  {inq.notes.map((n) => (
                    <li key={n.id} style={{ borderLeft: "3px solid var(--line)", paddingLeft: 12 }}>
                      <div style={{ whiteSpace: "pre-wrap", fontSize: 13.5 }}>{n.text}</div>
                      <div style={{ color: "var(--muted)", fontSize: 12, marginTop: 4 }}>
                        {n.by?.email ?? "Someone"} · {at(n.at)}
                      </div>
                    </li>
                  ))}
                </ul>
              )}
              <div className="field" style={{ marginBottom: 8 }}>
                <label htmlFor="inq-note">Add a note</label>
                <textarea
                  id="inq-note"
                  className="input"
                  maxLength={NOTE_MAX}
                  placeholder="e.g. Called back, meeting on Tuesday."
                  value={note}
                  aria-invalid={!!noteErr}
                  onChange={(e) => setNote(e.target.value)}
                />
                <div className="row-between" style={{ marginTop: 6 }}>
                  <span className="hint" style={{ margin: 0 }}>
                    {note.length}/{NOTE_MAX}
                  </span>
                  <button type="button" className="btn btn-primary btn-sm" disabled={busy === "note" || !note.trim() || inq.notes.length >= 100} onClick={addNote}>
                    {busy === "note" ? <span className="spin" /> : "Add note"}
                  </button>
                </div>
                {inq.notes.length >= 100 && <div className="hint">This inquiry has the maximum of 100 notes.</div>}
                {noteErr && <div className="form-error">{noteErr}</div>}
              </div>
            </div>
          </div>
        </div>

        <div>
          <div className="card" style={{ marginBottom: 16 }}>
            <div className="card-h">
              <h3>Contact</h3>
            </div>
            <div className="card-b">
              <dl className="kv">
                <Row label="Name">{inq.name}</Row>
                <Row label="Email">
                  <a href={`mailto:${inq.email}`} className="link">
                    {inq.email}
                  </a>
                </Row>
                {inq.phone && (
                  <Row label="Phone">
                    <a href={`tel:${tel}`} className="link">
                      {inq.phone}
                    </a>
                  </Row>
                )}
                {inq.company && <Row label="Company">{inq.company}</Row>}
              </dl>
              <a href={`mailto:${inq.email}`} className="btn btn-outline btn-sm" style={{ marginTop: 14 }}>
                <Icon name="mail" size={14} />
                Reply by email
              </a>
            </div>
          </div>
          <div className="card">
            <div className="card-h">
              <h3>Sent from</h3>
            </div>
            <div className="card-b">
              <dl className="kv">
                <Row label="Form">{SOURCE_LABEL[inq.source] ?? inq.source}</Row>
                {inq.pageUrl && <Row label="Page">{inq.pageUrl}</Row>}
                {inq.language && <Row label="Language">{languageName(inq.language)}</Row>}
                {inq.country && <Row label="Country">{countryName(inq.country)}</Row>}
                {inq.region && <Row label="Region">{inq.region}</Row>}
                <Row label="Received">{at(inq.createdAt)}</Row>
                {inq.statusChangedAt && (
                  <Row label="Status set">
                    {at(inq.statusChangedAt)}
                    {inq.statusChangedBy && ` by ${inq.statusChangedBy.email}`}
                  </Row>
                )}
              </dl>
            </div>
          </div>
        </div>
      </div>

      {deleting && (
        <ConfirmDialog title={`Delete the inquiry from ${inq.name}?`} confirmLabel="Delete permanently" danger busy={busy === "delete"} onConfirm={remove} onClose={() => busy !== "delete" && setDeleting(false)}>
          The inquiry and its notes are deleted permanently (e.g. for a data erasure request). This can&apos;t be undone. To just clear it from the inbox, set it to Closed or Spam instead.
          {deleteErr && <div className="form-error">{deleteErr}</div>}
        </ConfirmDialog>
      )}
    </div>
  );
}
