"use client";

/**
 * Services (API reference: "How services work (admin panel)"). A service is a card on
 * the Services page (under one of four divisions) plus its own page at /services/<slug>.
 *
 * - /admin/services: the services by division, create / settings / delete, and an import
 *   of the 12 services the website has built in.
 * - /admin/services/<id>: the card and page sections in the page editor.
 */
import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useMemo, useState } from "react";
import { ApiError, errorMessage, fieldErrors, getAccessToken } from "@/app/(admin)/_lib/api";
import { cleanForSchema, resolveMedia, schemaFor, serviceEditorApi, type SectionType } from "@/app/(admin)/_lib/cms";
import { isSlug, slugify } from "@/app/(admin)/_lib/products";
import { qk, useService, useServiceTemplate, useServices } from "@/app/(admin)/_lib/queries";
import { DIVISION_NAMES, servicesApi, type DivisionKey, type Service } from "@/app/(admin)/_lib/services";
import { refreshSiteContent } from "@/app/(admin)/_lib/siteCache";
import { useStore } from "@/app/(admin)/_lib/store";
import { builtInDivisionOf, builtInServiceSections } from "@/app/(site)/_components/pages/service/defaults";
import { DIVISIONS } from "@/app/(site)/_lib/divisions";
import { Icon } from "./Icon";
import { ConfirmDialog, Modal } from "./Modal";
import { PageEditor } from "./PageEditor";
import { PageHeader } from "./ui";

const DIVISION_KEYS = Object.keys(DIVISION_NAMES) as DivisionKey[];
const STATUS_TONE = { published: "g", in_review: "a", draft: "b" } as const;

/** Clears the website's cached services after a change it shows. Never fails the change itself. */
async function refreshServicesOnSite() {
  const token = getAccessToken();
  if (!token) return;
  try {
    await refreshSiteContent("services", token);
  } catch (e) {
    console.warn("[cms] could not refresh the website's services:", e);
  }
}

function useDivisions() {
  const { data } = useServiceTemplate();
  return data?.divisions ?? DIVISION_KEYS.map((key) => ({ key, name: DIVISION_NAMES[key] }));
}

/* ------------------------------------------------------------------ */
/* List                                                                */
/* ------------------------------------------------------------------ */

export function ServicesList() {
  const qc = useQueryClient();
  const router = useRouter();
  const { toast } = useStore();
  const { data, error, isPending, refetch } = useServices();
  const divisions = useDivisions();
  const [division, setDivision] = useState<"" | DivisionKey>("");
  const [creating, setCreating] = useState(false);
  const [editing, setEditing] = useState<Service | null>(null);
  const [deleting, setDeleting] = useState<Service | null>(null);
  const [busy, setBusy] = useState<string | null>(null);

  const services = useMemo(() => data ?? [], [data]);
  const missing = useMemo(() => DIVISIONS.filter((d) => !services.some((s) => s.slug === d.slug)), [services]);
  const anyLive = services.some((s) => Object.values(s.cardStatus).includes("published"));

  const refresh = () => qc.invalidateQueries({ queryKey: qk.services });

  /** Creates the built-in services that don't exist yet, with their card and page as English drafts. */
  const [confirmImport, setConfirmImport] = useState(false);
  const doImport = async () => {
    setBusy("import");
    const failed: string[] = [];
    let done = 0;
    for (const d of missing) {
      try {
        const div = builtInDivisionOf(d.slug) as DivisionKey;
        const order = DIVISIONS.filter((x) => builtInDivisionOf(x.slug) === div).indexOf(d);
        const s = await servicesApi.create({ slug: d.slug, division: div, order });
        const cms = serviceEditorApi(s.id);
        for (const sec of builtInServiceSections(d.slug) ?? []) {
          await cms.save(sec.key, "global", "en", cleanForSchema(sec.content, schemaFor(sec.type as SectionType)));
        }
        done++;
      } catch (e) {
        failed.push(`${d.card.title}: ${errorMessage(e)}`);
      }
    }
    await refresh();
    setBusy(null);
    setConfirmImport(false);
    toast(failed.length ? `Imported ${done}, ${failed.length} failed: ${failed[0]}` : `Imported ${done} services as drafts. Review each one, then publish.`);
  };

  const doDelete = async () => {
    if (!deleting) return;
    setBusy("delete");
    try {
      await servicesApi.remove(deleting.id);
      await refresh();
      await refreshServicesOnSite();
      toast(`Deleted ${deleting.card?.title ?? deleting.slug}`);
      setDeleting(null);
    } catch (e) {
      toast(errorMessage(e));
    } finally {
      setBusy(null);
    }
  };

  const shown = division ? divisions.filter((d) => d.key === division) : divisions;

  return (
    <div className="page">
      <PageHeader crumb="Website" title="Services" desc="Each service is a card on the Services page and its own page (/services/…). Shared by every region, translated per language.">
        {missing.length > 0 && (
          <button type="button" className="btn btn-outline btn-sm" disabled={!!busy || isPending} onClick={() => setConfirmImport(true)} title="Create the services the website shows today, as drafts">
            <Icon name="file" size={14} />
            Import website services ({missing.length})
          </button>
        )}
        <button type="button" className="btn btn-primary btn-sm" onClick={() => setCreating(true)}>
          <Icon name="plus" size={14} />
          New service
        </button>
      </PageHeader>

      <div className="info-note" style={{ marginBottom: 16 }}>
        {anyLive ? (
          <>The Services page lists the services whose card is published, in this order. Hide a service&apos;s card in its editor to take the whole service off the website.</>
        ) : (
          <>
            No service is published yet, so the website shows its {DIVISIONS.length} built-in services. Once one card is published, the Services page shows only published services: get them ready
            first (<b>Import website services</b> copies the built-in ones as drafts).
          </>
        )}
      </div>

      <div className="card">
        <div className="toolbar">
          <select className="select" aria-label="Filter by division" value={division} onChange={(e) => setDivision(e.target.value as "" | DivisionKey)}>
            <option value="">All divisions</option>
            {divisions.map((d) => (
              <option key={d.key} value={d.key}>
                {d.name}
              </option>
            ))}
          </select>
        </div>
        <div className="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Service</th>
                <th>Address</th>
                <th>Order</th>
                <th>Card per language</th>
                <th>
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {isPending ? (
                <tr>
                  <td className="empty" colSpan={5}>
                    <span className="spin dark" /> Loading services…
                  </td>
                </tr>
              ) : error ? (
                <tr>
                  <td className="empty" colSpan={5}>
                    {errorMessage(error)}{" "}
                    <button type="button" className="link" onClick={() => refetch()}>
                      Retry
                    </button>
                  </td>
                </tr>
              ) : (
                shown.map((d) => {
                  const rows = services.filter((s) => s.division === d.key).sort((a, b) => a.order - b.order);
                  return [
                    <tr key={d.key}>
                      <td colSpan={5} style={{ background: "#FAFBFD", fontWeight: 600 }}>
                        {d.name} <span style={{ color: "var(--muted)", fontWeight: 400 }}>· {rows.length}</span>
                      </td>
                    </tr>,
                    rows.length === 0 ? (
                      <tr key={`${d.key}-empty`}>
                        <td colSpan={5} style={{ color: "var(--muted)" }}>
                          No services in this division.
                        </td>
                      </tr>
                    ) : (
                      rows.map((s) => (
                        <tr key={s.id}>
                          <td>
                            <div className="who">
                              <span className="thumb" style={{ backgroundImage: resolveMedia(s.card?.image?.url) ? `url("${resolveMedia(s.card?.image?.url)}")` : undefined, backgroundColor: "var(--bg)" }} />
                              <Link href={`/admin/services/${s.id}`} className="link">
                                <b>{s.card?.title ?? s.slug}</b>
                              </Link>
                            </div>
                          </td>
                          <td style={{ color: "var(--muted)" }}>{s.path}</td>
                          <td>{s.order}</td>
                          <td>
                            <span className="sec-tags">
                              {Object.keys(s.cardStatus).length === 0 ? (
                                <span className="tag n">No card yet</span>
                              ) : (
                                Object.entries(s.cardStatus).map(([l, st]) => (
                                  <span key={l} className={`tag ${STATUS_TONE[st]}`} title={st.replace("_", " ")}>
                                    {l.toUpperCase()}
                                  </span>
                                ))
                              )}
                            </span>
                          </td>
                          <td>
                            <div className="row-actions" style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
                              <Link href={`/admin/services/${s.id}`} className="btn btn-outline btn-sm">
                                Edit
                              </Link>
                              <button type="button" className="btn-plain" onClick={() => setEditing(s)}>
                                Settings
                              </button>
                              <button type="button" className="btn-plain danger" onClick={() => setDeleting(s)}>
                                Delete
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))
                    ),
                  ];
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {creating && (
        <ServiceSettings
          divisions={divisions}
          onClose={() => setCreating(false)}
          onSaved={async (s) => {
            await refresh();
            setCreating(false);
            toast("Service created. Fill in its card and page, then publish.");
            router.push(`/admin/services/${s.id}`);
          }}
        />
      )}
      {editing && (
        <ServiceSettings
          service={editing}
          divisions={divisions}
          onClose={() => setEditing(null)}
          onSaved={async () => {
            await refresh();
            qc.invalidateQueries({ queryKey: qk.service(editing.id) });
            await refreshServicesOnSite();
            setEditing(null);
            toast("Service settings saved");
          }}
        />
      )}
      {deleting && (
        <ConfirmDialog title={`Delete ${deleting.card?.title ?? deleting.slug}?`} confirmLabel="Delete service" danger busy={busy === "delete"} onConfirm={doDelete} onClose={() => setDeleting(null)}>
          The service, its card and its page are deleted in every language. This can&apos;t be undone. To take it off the website but keep it, hide its card in the editor instead.
        </ConfirmDialog>
      )}
      {confirmImport && (
        <ConfirmDialog title="Import the website's services?" confirmLabel={`Import ${missing.length}`} busy={busy === "import"} onConfirm={doImport} onClose={() => setConfirmImport(false)}>
          These services are created with the card and page the website shows today, saved as English drafts: <b>{missing.map((d) => d.card.title).join(", ")}</b>. Nothing goes live until you publish.
        </ConfirmDialog>
      )}
    </div>
  );
}

/** Create a service, or change its slug, division or position. */
function ServiceSettings({
  service,
  divisions,
  onClose,
  onSaved,
}: {
  service?: Service;
  divisions: { key: DivisionKey; name: string }[];
  onClose: () => void;
  onSaved: (s: Service) => void;
}) {
  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState(service?.slug ?? "");
  const [slugTouched, setSlugTouched] = useState(!!service);
  const [division, setDivision] = useState<DivisionKey>(service?.division ?? divisions[0].key);
  const [order, setOrder] = useState(service ? String(service.order) : "");
  const [errs, setErrs] = useState<Record<string, string>>({});
  const [err, setErr] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const shownSlug = slugTouched ? slug : slugify(title);
  const slugProblem = shownSlug && !isSlug(shownSlug) ? "Lowercase letters and numbers joined by single hyphens." : shownSlug && shownSlug.length < 3 ? "At least 3 characters." : null;

  const submit = async () => {
    setBusy(true);
    setErr(null);
    setErrs({});
    try {
      const o = order.trim() === "" ? undefined : Number(order);
      const s = service
        ? await servicesApi.update(service.id, {
            ...(shownSlug !== service.slug ? { slug: shownSlug } : {}),
            ...(division !== service.division ? { division } : {}),
            ...(o !== undefined && o !== service.order ? { order: o } : {}),
          })
        : await servicesApi.create({ slug: shownSlug, division, ...(o !== undefined ? { order: o } : {}) });
      onSaved(s);
    } catch (e) {
      setErrs(fieldErrors(e));
      setErr(e instanceof ApiError && e.status === 409 ? e.message : errorMessage(e));
    } finally {
      setBusy(false);
    }
  };

  return (
    <Modal title={service ? `Settings: ${service.card?.title ?? service.slug}` : "New service"} onClose={onClose}>
      {!service && (
        <div className="field">
          <label htmlFor="svc-title">English title (suggests the address)</label>
          <input id="svc-title" className="input" maxLength={160} value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Food Robotics & Automation" autoFocus />
        </div>
      )}
      <div className="field">
        <label htmlFor="svc-slug">
          Address <span className="req">*</span>
        </label>
        <div className="input-ico" style={{ display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ color: "var(--muted)", whiteSpace: "nowrap" }}>/services/</span>
          <input
            id="svc-slug"
            className="input"
            maxLength={80}
            value={shownSlug}
            onChange={(e) => {
              setSlugTouched(true);
              setSlug(e.target.value.toLowerCase());
            }}
            aria-invalid={!!(slugProblem || errs.slug)}
          />
        </div>
        {service && shownSlug !== service.slug && <div className="hint">The old address stops working (404). Links to it elsewhere need updating.</div>}
        {(slugProblem || errs.slug) && <div className="hint bad">{slugProblem ?? errs.slug}</div>}
      </div>
      <div className="form-grid">
        <div className="field">
          <label htmlFor="svc-division">Division</label>
          <select id="svc-division" className="select input" value={division} onChange={(e) => setDivision(e.target.value as DivisionKey)}>
            {divisions.map((d) => (
              <option key={d.key} value={d.key}>
                {d.name}
              </option>
            ))}
          </select>
        </div>
        <div className="field">
          <label htmlFor="svc-order">Position in the division</label>
          <input id="svc-order" className="input" type="number" min={0} max={1000} step={1} placeholder="Last" value={order} onChange={(e) => setOrder(e.target.value)} />
          {errs.order && <div className="hint bad">{errs.order}</div>}
        </div>
      </div>
      {err && <div className="form-error">{err}</div>}
      <div className="modal-actions">
        <button type="button" className="btn btn-outline btn-sm" onClick={onClose}>
          Cancel
        </button>
        <button type="button" className="btn btn-primary btn-sm" disabled={busy || !shownSlug || !!slugProblem} onClick={submit}>
          {busy ? <span className="spin" /> : service ? "Save" : "Create & edit"}
        </button>
      </div>
    </Modal>
  );
}

/* ------------------------------------------------------------------ */
/* Editor                                                              */
/* ------------------------------------------------------------------ */

/** /admin/services/<id>: the service's card and page, in the page editor. */
export function ServiceEditor({ id }: { id: string }) {
  const { data: service, error, isPending } = useService(id);
  const cms = useMemo(() => serviceEditorApi(id), [id]);
  if (isPending)
    return (
      <div className="page">
        <div className="card empty-card">
          <span className="spin dark" /> Loading…
        </div>
      </div>
    );
  if (error || !service)
    return (
      <div className="page">
        <div className="card empty-card">
          {error ? errorMessage(error) : "This service doesn't exist."}{" "}
          <Link href="/admin/services" className="link">
            Back to Services
          </Link>
        </div>
      </div>
    );
  return (
    <PageEditor
      key={service.id}
      pageKey={`service:${service.id}`}
      name={service.card?.title ?? service.slug}
      regional={false}
      crumb={
        <>
          Website ›{" "}
          <Link href="/admin/services" className="link" style={{ fontSize: "inherit" }}>
            Services
          </Link>{" "}
          › {DIVISION_NAMES[service.division] ?? service.division}
        </>
      }
      desc="The card on the Services page and the service's own page, per language. Changes go live only when published."
      api={cms}
      connected
      previewKey="service"
      designKey="service"
      defaults={builtInServiceSections(service.slug)}
      sitePath={service.path}
      refresh={(token) => refreshSiteContent("services", token)}
      notes={
        <div className="info-note" style={{ marginBottom: 16 }}>
          The service is on the website once its <b>Service Card</b> is published (the Services page lists it, and its page opens). Hiding the card takes the whole service off the website. Page
          sections that aren&apos;t published are left out. The website shows services in English for now.
        </div>
      }
    />
  );
}
