"use client";

/** /admin/products: every product with filters, its text state per language, and row actions. */
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { errorMessage, getAccessToken } from "@/app/(admin)/_lib/api";
import { resolveMedia } from "@/app/(admin)/_lib/cms";
import { isSlug, langBadge, money, productsApi, tr, type ProductQuery, type ProductRow } from "@/app/(admin)/_lib/products";
import { qk, useCategories, useProducts } from "@/app/(admin)/_lib/queries";
import { BUILT_IN_PRODUCTS, PRICED_SAMPLE, addPricedSample, importWebsiteProducts } from "@/app/(admin)/_lib/productImport";
import { refreshSiteContent } from "@/app/(admin)/_lib/siteCache";
import { useStore } from "@/app/(admin)/_lib/store";
import { useActiveLangs } from "./CatalogPage";
import { Icon } from "./Icon";
import { ConfirmDialog, Modal } from "./Modal";
import { PageHeader } from "./ui";

const ALL_PRODUCTS: ProductQuery = { page: 1, limit: 100, search: "", category: "", type: "", status: "", lang: "en", state: "", sort: "slug" };

const when = (iso: string) => new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" });

function priceRange(p: ProductRow) {
  if (!p.price || p.price.min == null) return "—";
  const unit = ` / ${p.price.unit}`;
  return p.price.max != null && p.price.max !== p.price.min ? `${money(p.price.min, p.price.currency)}–${money(p.price.max, p.price.currency)}${unit}` : `${money(p.price.min, p.price.currency)}${unit}`;
}

export function ProductsList() {
  const qc = useQueryClient();
  const router = useRouter();
  const { toast } = useStore();
  const langs = useActiveLangs();
  const { data: groups } = useCategories();
  const [q, setQ] = useState<ProductQuery>({ page: 1, limit: 20, search: "", category: "", type: "", status: "", lang: "en", state: "", sort: "-updatedAt" });
  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<ProductQuery>) => setQ((p) => ({ ...p, ...patch, page: patch.page ?? 1 }));
  const { data, error, isPending, isFetching, refetch } = useProducts(q);
  const rows = data?.data ?? [];
  const meta = data?.meta;
  // Every product's slug (up to 100), to know which of the website's products exist already.
  const { data: everything } = useProducts(ALL_PRODUCTS);
  const existing = new Set((everything?.data ?? []).map((p) => p.slug));
  const missing = everything ? BUILT_IN_PRODUCTS.filter((p) => !existing.has(p.slug)) : [];
  const [importing, setImporting] = useState(false);
  const [progress, setProgress] = useState<string | null>(null);
  const doImport = async () => {
    setBusy("import");
    try {
      const r = await importWebsiteProducts(existing, setProgress);
      await reload();
      await qc.invalidateQueries({ queryKey: ["admin", "catalog"] });
      setImporting(false);
      toast(
        r.failed.length
          ? `Imported ${r.created.length}, ${r.failed.length} failed: ${r.failed[0]}`
          : `Imported ${r.created.length} products as drafts${r.catalog.length ? ` (and ${r.catalog.length} catalog items)` : ""}. Review prices and details, then publish.`,
      );
    } catch (e) {
      toast(`Import stopped: ${errorMessage(e)}`);
    } finally {
      setBusy(null);
      setProgress(null);
    }
  };

  const [addingSample, setAddingSample] = useState(false);
  const [sampleError, setSampleError] = useState<string | null>(null);
  const hasSample = existing.has(PRICED_SAMPLE.slug);
  const doAddSample = async () => {
    setBusy("sample");
    setSampleError(null);
    try {
      const r = await addPricedSample(setProgress);
      await reload();
      await qc.invalidateQueries({ queryKey: ["admin", "catalog"] });
      setAddingSample(false);
      if (r.published) {
        refreshSite();
        toast(`${PRICED_SAMPLE.name} is live with its price on Global Agriculture`);
      } else toast(`${PRICED_SAMPLE.name} was created as a draft, but publishing failed: ${r.publishError}`);
      router.push(`/admin/products/${r.id}`);
    } catch (e) {
      setSampleError(errorMessage(e));
    } finally {
      setBusy(null);
      setProgress(null);
    }
  };

  const [duplicating, setDuplicating] = useState<ProductRow | null>(null);
  const [dupSlug, setDupSlug] = useState("");
  const [deleting, setDeleting] = useState<ProductRow | null>(null);
  const [busy, setBusy] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);

  const reload = () => qc.invalidateQueries({ queryKey: qk.products() });
  const refreshSite = () => {
    const token = getAccessToken();
    if (token) void refreshSiteContent("products", token).catch(() => undefined);
  };

  const archive = async (p: ProductRow) => {
    setBusy(p.id);
    try {
      await productsApi.setStatus(p.id, p.status === "archived" ? "active" : "archived");
      await reload();
      qc.removeQueries({ queryKey: qk.product(p.id) });
      refreshSite();
      toast(p.status === "archived" ? `${p.name} is back (shown where published)` : `${p.name} archived: off the website`);
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const duplicate = async () => {
    if (!duplicating) return;
    setBusy("dup");
    setErr(null);
    try {
      const copy = await productsApi.duplicate(duplicating.id, dupSlug);
      await reload();
      toast("Copy created as a draft (SKUs end in -COPY)");
      setDuplicating(null);
      router.push(`/admin/products/${copy.id}`);
    } catch (e) {
      setErr(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const remove = async () => {
    if (!deleting) return;
    setBusy("del");
    setErr(null);
    try {
      await productsApi.remove(deleting.id);
      await reload();
      toast(`Deleted ${deleting.name}`);
      setDeleting(null);
    } catch (e) {
      setErr(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="page">
      <PageHeader crumb="Website" title="Products" desc="The catalogue on Global Agriculture and each product page (/products/…). Text is published per language; prices and variants are shared.">
        {missing.length > 0 && (
          <button type="button" className="btn btn-outline btn-sm" disabled={!!busy} onClick={() => setImporting(true)} title="Create the products the website's catalogue shows today, as drafts">
            <Icon name="file" size={14} />
            Import website products ({missing.length})
          </button>
        )}
        {everything && !hasSample && (
          <button type="button" className="btn btn-outline btn-sm" disabled={!!busy} onClick={() => setAddingSample(true)} title="Create and publish one product whose price is shown on the website">
            <Icon name="plus" size={14} />
            Add priced sample product
          </button>
        )}
        <Link href="/admin/catalog" className="btn btn-outline btn-sm">
          <Icon name="settings" size={14} />
          Catalog lists
        </Link>
        <Link href="/admin/products/new" className="btn btn-primary btn-sm">
          <Icon name="plus" size={14} />
          New product
        </Link>
      </PageHeader>

      <div className="card">
        <div className="toolbar" style={{ flexWrap: "wrap" }}>
          <div className="search">
            <Icon name="search" />
            <input placeholder="Search name, SKU or slug…" aria-label="Search products" maxLength={100} value={searchText} onChange={(e) => setSearchText(e.target.value)} />
          </div>
          <select className="select" aria-label="Category" value={q.category} onChange={(e) => set({ category: e.target.value })}>
            <option value="">All categories</option>
            {(groups ?? []).map((g) => (
              <optgroup key={g.id} label={tr(g.translations, "en", "name")}>
                {(g.children ?? []).map((c) => (
                  <option key={c.id} value={c.id}>
                    {tr(c.translations, "en", "name")}
                  </option>
                ))}
              </optgroup>
            ))}
          </select>
          <select className="select" aria-label="Type" value={q.type} onChange={(e) => set({ type: e.target.value as ProductQuery["type"] })}>
            <option value="">All types</option>
            <option value="simple">Simple</option>
            <option value="variable">With variants</option>
          </select>
          <select className="select" aria-label="Status" value={q.status} onChange={(e) => set({ status: e.target.value as ProductQuery["status"] })}>
            <option value="">Active and archived</option>
            <option value="active">Active</option>
            <option value="archived">Archived</option>
          </select>
          <select className="select" aria-label="Text state" value={q.state} onChange={(e) => set({ state: e.target.value as ProductQuery["state"] })}>
            <option value="">Any text state</option>
            <option value="missing">Missing</option>
            <option value="draft">Draft</option>
            <option value="in_review">In review</option>
            <option value="published">Published</option>
          </select>
          {q.state && (
            <select className="select" aria-label="In language" value={q.lang} onChange={(e) => set({ lang: e.target.value })}>
              {langs.map((l) => (
                <option key={l.code} value={l.code}>
                  in {l.name}
                </option>
              ))}
            </select>
          )}
          {isFetching && !isPending && <span className="spin dark" aria-label="Updating" />}
        </div>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Product</th>
                <th>Default SKU</th>
                <th>Type</th>
                <th>Price</th>
                <th>Languages</th>
                <th>Status</th>
                <th>Updated</th>
                <th>
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {isPending ? (
                <tr>
                  <td className="empty" colSpan={8}>
                    <span className="spin dark" /> Loading products…
                  </td>
                </tr>
              ) : error ? (
                <tr>
                  <td className="empty" colSpan={8}>
                    {errorMessage(error)}{" "}
                    <button type="button" className="link" onClick={() => refetch()}>
                      Retry
                    </button>
                  </td>
                </tr>
              ) : rows.length === 0 ? (
                <tr>
                  <td className="empty" colSpan={8}>
                    {q.search || q.category || q.type || q.status || q.state ? (
                      "No products match."
                    ) : (
                      <>
                        No products yet.{" "}
                        <Link href="/admin/products/new" className="link">
                          Create the first one
                        </Link>{" "}
                        (set up the <Link href="/admin/catalog" className="link">catalog lists</Link> first).
                      </>
                    )}
                  </td>
                </tr>
              ) : (
                rows.map((p) => {
                  const img = resolveMedia(p.thumbnail?.url);
                  const published = Object.values(p.languages).includes("published");
                  return (
                    <tr key={p.id}>
                      <td>
                        <div className="who">
                          <span className="thumb" style={{ backgroundImage: img ? `url("${img}")` : undefined, backgroundColor: "var(--bg)" }} />
                          <div>
                            <Link href={`/admin/products/${p.id}`} className="link">
                              <b>{p.name || p.slug}</b>
                            </Link>
                            <div style={{ color: "var(--muted)", fontSize: 12 }}>/products/{p.slug}</div>
                          </div>
                        </div>
                      </td>
                      <td>{p.defaultSku ?? "—"}</td>
                      <td>{p.type === "variable" ? `${p.variantCount} variants` : "Simple"}</td>
                      <td>{priceRange(p)}</td>
                      <td>
                        <span className="sec-tags">
                          {langs.map((l) => {
                            const b = langBadge(p.languages[l.code]);
                            return (
                              <span key={l.code} className={`tag ${b.tone}`} title={`${l.name}: ${b.label}`}>
                                {l.code.toUpperCase()}
                              </span>
                            );
                          })}
                        </span>
                      </td>
                      <td>{p.status === "archived" ? <span className="tag n">Archived</span> : <span className="tag g">Active</span>}</td>
                      <td style={{ color: "var(--muted)" }}>{when(p.updatedAt)}</td>
                      <td>
                        <div style={{ display: "flex", gap: 6, justifyContent: "flex-end" }}>
                          <Link href={`/admin/products/${p.id}`} className="btn btn-outline btn-sm">
                            Edit
                          </Link>
                          <button
                            type="button"
                            className="btn-plain"
                            onClick={() => {
                              setErr(null);
                              setDupSlug(`${p.slug}-copy`.slice(0, 100));
                              setDuplicating(p);
                            }}
                          >
                            Duplicate
                          </button>
                          <button type="button" className="btn-plain" disabled={busy === p.id} onClick={() => archive(p)}>
                            {p.status === "archived" ? "Unarchive" : "Archive"}
                          </button>
                          {!published && (
                            <button
                              type="button"
                              className="btn-plain danger"
                              onClick={() => {
                                setErr(null);
                                setDeleting(p);
                              }}
                            >
                              Delete
                            </button>
                          )}
                        </div>
                      </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">Archive takes a product off the website in every language and keeps everything. Delete is only possible for products that were never published.</p>

      {duplicating && (
        <Modal title={`Duplicate ${duplicating.name}`} onClose={() => setDuplicating(null)}>
          <div className="field">
            <label htmlFor="dup-slug">Address of the copy</label>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ color: "var(--muted)" }}>/products/</span>
              <input id="dup-slug" className="input" maxLength={100} value={dupSlug} onChange={(e) => setDupSlug(e.target.value.toLowerCase())} autoFocus />
            </div>
            <div className="hint">The copy is an unpublished draft with the same data and text; its SKUs get -COPY added.</div>
          </div>
          {err && <div className="form-error">{err}</div>}
          <div className="modal-actions">
            <button type="button" className="btn btn-outline btn-sm" onClick={() => setDuplicating(null)}>
              Cancel
            </button>
            <button type="button" className="btn btn-primary btn-sm" disabled={busy === "dup" || !isSlug(dupSlug) || dupSlug.length < 3} onClick={duplicate}>
              {busy === "dup" ? <span className="spin" /> : "Duplicate"}
            </button>
          </div>
        </Modal>
      )}
      {importing && (
        <ConfirmDialog
          title="Import the website's products?"
          confirmLabel={busy === "import" ? "Importing…" : `Import ${missing.length}`}
          busy={busy === "import"}
          onConfirm={doImport}
          onClose={() => busy !== "import" && setImporting(false)}
        >
          These products from the Global Agriculture catalogue are created as English drafts: <b>{missing.map((p) => p.name).join(", ")}</b>. The category groups, categories and
          certifications its filters show are added to the{" "}
          <Link href="/admin/catalog" className="link">
            Product Catalog
          </Link>{" "}
          when missing.
          <div className="info-note" style={{ marginTop: 12 }}>
            The design has no prices or volumes, so each product gets: price on request (one variant, SKU like GARLIC-01), volume from 0 MT, origin Iran &amp; Spain, ISO 22000 and the
            template&apos;s description. Review them before publishing. Nothing goes live until you publish.
          </div>
          {progress && (
            <div className="hint">
              <span className="spin dark" /> {progress}
            </div>
          )}
        </ConfirmDialog>
      )}
      {addingSample && (
        <ConfirmDialog
          title={`Add "${PRICED_SAMPLE.name}"?`}
          confirmLabel={busy === "sample" ? "Adding…" : "Add and publish"}
          busy={busy === "sample"}
          onConfirm={doAddSample}
          onClose={() => busy !== "sample" && setAddingSample(false)}
        >
          A sample product with its price shown is created and its English text published, so it appears on the Global Agriculture catalogue straight away: selling price{" "}
          <b>{money(PRICED_SAMPLE.sellingPrice, "EUR")} / kg</b>, market price <s>{money(PRICED_SAMPLE.marketPrice, "EUR")}</s> (shown crossed out), category Spice &amp; Herbs, featured so it
          is listed first. Afterwards you can edit, unpublish or archive it like any product (published products can&apos;t be deleted).
          {progress && (
            <div className="hint">
              <span className="spin dark" /> {progress}
            </div>
          )}
          {sampleError && <div className="form-error">{sampleError}</div>}
        </ConfirmDialog>
      )}
      {deleting && (
        <ConfirmDialog title={`Delete ${deleting.name}?`} confirmLabel="Delete product" danger busy={busy === "del"} onConfirm={remove} onClose={() => setDeleting(null)}>
          The product and its text in every language are deleted. This can&apos;t be undone.
          {err && <div className="form-error">{err}</div>}
        </ConfirmDialog>
      )}
    </div>
  );
}
