import React, { useMemo, useState } from "react";
import { DashboardTemplatePage } from "./DashboardTemplatePage";
import { useBPManifest } from "./useBPManifest";
import { BPItem } from "./bp-manifest";
import { COLORS, btnBase, cardBase, chip } from "./ui-tokens";

function gdocsViewerUrl(absUrl: string) {
  // View-only; users can File → Make a copy in Google Docs
  return `https://docs.google.com/gview?embedded=1&url=${encodeURIComponent(absUrl)}`;
}

export default function BusinessPlanTemplatesPage() {
  const state = useBPManifest("/site/data/manifest.bp.json");
  const [q, setQ] = useState("");
  const [tag, setTag] = useState("all");
  const [sort, setSort] = useState<"az"|"new">("az");

  const items = state.status === "ready" ? state.items : [];

  const allTags = useMemo(() => {
    const s = new Set<string>();
    items.forEach(i => i.tags?.forEach(t => s.add(t)));
    return ["all", ...Array.from(s).sort()];
  }, [items]);

  const filtered = useMemo(() => {
    const ql = q.trim().toLowerCase();
    let out = items.filter(i => {
      const inTag = tag === "all" || i.tags?.includes(tag);
      const inQ = !ql ||
        i.name.toLowerCase().includes(ql) ||
        (i.category || "").toLowerCase().includes(ql) ||
        i.tags?.some(t => t.toLowerCase().includes(ql));
      return inTag && inQ;
    });
    if (sort === "az") out = out.sort((a,b)=>a.name.localeCompare(b.name));
    if (sort === "new") out = out.sort((a,b)=> (b.updatedAt||"").localeCompare(a.updatedAt||""));
    return out;
  }, [items, q, tag, sort]);

  return (
    <DashboardTemplatePage title="Business Plan Templates">
      {state.status !== "ready" ? (
        <div className="text-sm text-gray-500">
          {state.status === "error" ? `Error: ${state.error}` : "Loading templates…"}
        </div>
      ) : (
        <>
          <header className="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
            <div className="text-sm text-gray-600">
              <b>{filtered.length}</b> of {items.length} templates
            </div>
            <div className="flex gap-2">
              <input
                placeholder="Search industries, tags…"
                value={q}
                onChange={(e)=>setQ(e.target.value)}
                className="w-56 rounded-lg border px-3 py-2"
              />
              <select value={tag} onChange={e=>setTag(e.target.value)} className="rounded-lg border px-3 py-2">
                {allTags.map(t => <option key={t} value={t}>{t}</option>)}
              </select>
              <select value={sort} onChange={e=>setSort(e.target.value as any)} className="rounded-lg border px-3 py-2">
                <option value="az">A–Z</option>
                <option value="new">Newest</option>
              </select>
            </div>
          </header>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {filtered.map(item => <Card key={item.id} item={item} />)}
          </div>
        </>
      )}
    </DashboardTemplatePage>
  );
}

function Card({ item }: { item: BPItem }) {
  const origin = typeof window !== "undefined" ? `${window.location.protocol}//${window.location.host}` : "";
  const docxAbs = origin + item.docxUrl;

  return (
    <div className={cardBase}>
      <div className="aspect-video rounded-xl bg-white overflow-hidden flex items-center justify-center">
        {item.previewUrl ? (
          <img src={item.previewUrl} alt={item.name} className="object-contain w-full h-full" />
        ) : (
          <div className="text-sm text-gray-500">Preview</div>
        )}
      </div>

      <div className="mt-3 text-sm font-medium">{item.name}</div>
      <div className="text-xs text-gray-500">{item.category || "—"}</div>

      {!!item.sections?.length && (
        <div className="mt-2 text-xs text-gray-600">
          <b>Sections:</b> {item.sections.slice(0,5).join(", ")}{item.sections.length>5?"…":""}
        </div>
      )}

      <div className="mt-2 flex flex-wrap gap-1">
        {item.tags?.map(t => <span key={t} className={chip}>{t}</span>)}
      </div>

      <div className="mt-3 flex flex-wrap gap-2">
        <a
          className={btnBase}
          style={{ backgroundColor: COLORS.orange, color: COLORS.white }}
          href={item.docxUrl}
          download
        >
          Download DOCX
        </a>
        <a
          className={btnBase}
          style={{ backgroundColor: COLORS.green, color: COLORS.white }}
          href={`https://docs.google.com/gview?embedded=1&url=${encodeURIComponent(docxAbs)}`}
          target="_blank"
          rel="noreferrer"
          title="View in Google Docs Viewer (then File → Make a copy to edit)"
        >
          Open in Google Docs
        </a>
      </div>
    </div>
  );
}
