import Link from "next/link";
import { db } from "@/lib/db";
import { getOrgContext, canOrgModule, canOrgMutate } from "@/lib/org";
import { requireUser } from "@/lib/auth";
import { Badge, btn, Card, EmptyState, Field, PageHeader, StatCard, input } from "@/components/ui";
import { fmtDate } from "@/lib/utils";
import { ASSET_TYPES, ASSET_TYPE_LABELS } from "@/lib/constants";
import { deleteAsset, moveAsset, renameAsset, uploadAssets } from "./actions";

export const metadata = { title: "Assets" };

function sizeLabel(bytes: number | null): string {
  if (!bytes) return "";
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

const TYPE_ICONS: Record<string, string> = {
  LOGO: "🎨", BANNER: "🖼", POSTER: "📰", SPEAKER_PHOTO: "🎤", SPONSOR_LOGO: "🤝",
  VIDEO: "🎬", DOCUMENT: "📄", BROCHURE: "📘", CERTIFICATE: "🏅", PRESENTATION: "📽",
  MARKETING: "📣", QR: "🔳", OTHER: "📁",
};

export default async function AssetsPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; type?: string; conf?: string; view?: string; saved?: string; error?: string }>;
}) {
  await requireUser();
  const ctx = await getOrgContext();
  if (!ctx?.org || !canOrgModule(ctx.role, "assets")) {
    return <EmptyState title="No access" body="The asset library is not part of your role." />;
  }
  const org = ctx.org;
  const canMutate = canOrgMutate(ctx.role);
  const sp = await searchParams;
  const view = sp.view === "list" ? "list" : "grid";

  const conferences = await db.conference.findMany({ where: { orgId: org.id }, orderBy: { startAt: "desc" }, select: { id: true, name: true } });
  const confFilter = sp.conf === "org" ? "org" : sp.conf && conferences.some((c) => c.id === sp.conf) ? sp.conf : undefined;

  const assets = await db.asset.findMany({
    where: {
      orgId: org.id,
      ...(confFilter === "org" ? { conferenceId: null } : confFilter ? { conferenceId: confFilter } : {}),
      ...(sp.type ? { type: sp.type } : {}),
      ...(sp.q ? { OR: [{ name: { contains: sp.q } }, { tags: { contains: sp.q } }] } : {}),
    },
    include: { conference: { select: { id: true, name: true } } },
    orderBy: { createdAt: "desc" },
  });

  const totalSize = assets.reduce((s, a) => s + (a.size ?? 0), 0);

  // Organization → Conference → Asset type hierarchy
  const groups = new Map<string, typeof assets>();
  for (const a of assets) {
    const k = a.conference?.name ?? `${org.name} (organization-wide)`;
    if (!groups.has(k)) groups.set(k, []);
    groups.get(k)!.push(a);
  }

  const qs = (overrides: Record<string, string | undefined>) => {
    const merged = { q: sp.q, type: sp.type, conf: confFilter, view: sp.view, ...overrides };
    const p = new URLSearchParams();
    for (const [k, v] of Object.entries(merged)) if (v) p.set(k, v);
    const s = p.toString();
    return `/dashboard/assets${s ? `?${s}` : ""}`;
  };

  return (
    <main>
      <PageHeader
        title="📁 Assets"
        sub={`Central asset library for ${org.name} — organized by organization → conference → type.`}
      />
      {sp.saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ {sp.saved}</p>}
      {sp.error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{sp.error}</p>}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Total Assets" value={assets.length} />
        <StatCard label="Storage Used" value={sizeLabel(totalSize) || "0 KB"} />
        <StatCard label="Conference Folders" value={groups.size} />
        <StatCard label="Images" value={assets.filter((a) => a.mime?.startsWith("image/")).length} />
      </div>

      {canMutate && (
        <Card className="mt-5 p-5">
          <h3 className="mb-3 text-sm font-semibold text-zinc-200">Upload assets</h3>
          <form action={uploadAssets} className="grid gap-3 sm:grid-cols-2 lg:grid-cols-6">
            <div className="lg:col-span-2">
              <Field name="files" title="Files (bulk upload supported) *">
                <input id="files" name="files" type="file" multiple required className={`${input} file:mr-2 file:rounded-lg file:border-0 file:bg-indigo-500/10 file:px-2.5 file:py-1 file:text-xs file:font-semibold file:text-indigo-600`} />
              </Field>
            </div>
            <Field name="type" title="Asset Type">
              <select id="type" name="type" className={input}>
                {ASSET_TYPES.map((t) => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
              </select>
            </Field>
            <Field name="conferenceId" title="Belongs to">
              <select id="conferenceId" name="conferenceId" className={input}>
                <option value="">Organization-wide</option>
                {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </Field>
            <Field name="tags" title="Tags (comma-separated)"><input id="tags" name="tags" placeholder="2026, social, print" className={input} /></Field>
            <div className="flex items-end"><button className={`${btn.primary} w-full`}>Upload</button></div>
          </form>
        </Card>
      )}

      {/* Filters & view toggle */}
      <div className="mt-5 flex flex-wrap items-center gap-2">
        <form className="flex flex-wrap items-center gap-2" action="/dashboard/assets">
          {sp.view && <input type="hidden" name="view" value={sp.view} />}
          <input type="search" name="q" defaultValue={sp.q ?? ""} placeholder="Search assets & tags… 🔍" className={`${input} !w-56 !py-1.5 text-xs`} />
          <select name="type" defaultValue={sp.type ?? ""} className={`${input} !w-44 !py-1.5 text-xs`} aria-label="Type">
            <option value="">All types</option>
            {ASSET_TYPES.map((t) => <option key={t} value={t}>{ASSET_TYPE_LABELS[t]}</option>)}
          </select>
          <select name="conf" defaultValue={confFilter ?? ""} className={`${input} !w-56 !py-1.5 text-xs`} aria-label="Conference">
            <option value="">Everything</option>
            <option value="org">Organization-wide only</option>
            {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <button className={btn.smSecondary}>Apply</button>
        </form>
        <div className="ml-auto flex rounded-lg border border-white/70 bg-white/50 p-0.5 text-xs">
          <Link href={qs({ view: undefined })} className={`rounded-md px-2.5 py-1 font-medium ${view === "grid" ? "bg-indigo-500 text-white" : "text-zinc-500"}`}>▦ Grid</Link>
          <Link href={qs({ view: "list" })} className={`rounded-md px-2.5 py-1 font-medium ${view === "list" ? "bg-indigo-500 text-white" : "text-zinc-500"}`}>☰ List</Link>
        </div>
      </div>

      {assets.length === 0 ? (
        <div className="mt-5"><EmptyState title="No assets in this view" body="Upload logos, banners, brochures, videos and documents to build your library." /></div>
      ) : (
        <div className="mt-5 space-y-6">
          {[...groups.entries()].map(([groupName, items]) => (
            <div key={groupName}>
              <h3 className="mb-2.5 flex items-center gap-2 text-sm font-bold text-zinc-200">
                🗂 {groupName} <span className="text-xs font-normal text-zinc-500">({items.length})</span>
              </h3>
              {view === "grid" ? (
                <div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
                  {items.map((a) => (
                    <Card key={a.id} className="group overflow-hidden p-0">
                      <a href={a.url} target="_blank" rel="noreferrer" className="block">
                        {a.mime?.startsWith("image/") ? (
                          // eslint-disable-next-line @next/next/no-img-element
                          <img src={a.url} alt={a.name} className="h-28 w-full bg-white/50 object-cover" loading="lazy" />
                        ) : (
                          <div className="flex h-28 w-full items-center justify-center bg-gradient-to-br from-indigo-500/10 to-fuchsia-500/10 text-4xl">
                            {TYPE_ICONS[a.type] ?? "📁"}
                          </div>
                        )}
                      </a>
                      <div className="p-3">
                        <div className="truncate text-xs font-semibold text-zinc-200" title={a.name}>{a.name}</div>
                        <div className="mt-1 flex items-center justify-between gap-1">
                          <Badge className="bg-indigo-500/10 text-indigo-600">{ASSET_TYPE_LABELS[a.type] ?? a.type}</Badge>
                          <span className="text-[10px] text-zinc-500">{sizeLabel(a.size)}</span>
                        </div>
                        {canMutate && (
                          <details className="mt-2">
                            <summary className="cursor-pointer select-none text-[11px] text-zinc-500 hover:text-zinc-200 [&::-webkit-details-marker]:hidden">Manage ▾</summary>
                            <div className="mt-2 space-y-2">
                              <form action={renameAsset.bind(null, a.id)} className="flex gap-1">
                                <input name="name" defaultValue={a.name} className={`${input} !py-1 text-[11px]`} aria-label="Rename" />
                                <button className={`${btn.smSecondary} !px-2 !py-1`}>✓</button>
                              </form>
                              <form action={moveAsset.bind(null, a.id)} className="flex gap-1">
                                <select name="conferenceId" defaultValue={a.conferenceId ?? ""} className={`${input} !py-1 text-[11px]`} aria-label="Move to">
                                  <option value="">Organization-wide</option>
                                  {conferences.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
                                </select>
                                <button className={`${btn.smSecondary} !px-2 !py-1`}>Move</button>
                              </form>
                              <div className="flex items-center justify-between">
                                <a href={a.url} download className="text-[11px] font-medium text-indigo-600 hover:underline">⬇ Download</a>
                                <form action={deleteAsset.bind(null, a.id)}>
                                  <button className="text-[11px] text-red-500 hover:underline">Delete</button>
                                </form>
                              </div>
                            </div>
                          </details>
                        )}
                      </div>
                    </Card>
                  ))}
                </div>
              ) : (
                <Card className="overflow-x-auto">
                  <table className="w-full min-w-[760px] text-sm">
                    <thead>
                      <tr className="border-b border-zinc-800/60 text-left text-xs uppercase tracking-wider text-zinc-500">
                        <th className="px-4 py-2.5">Asset</th><th className="px-3 py-2.5">Type</th><th className="px-3 py-2.5">Tags</th><th className="px-3 py-2.5">Size</th><th className="px-3 py-2.5">Uploaded</th><th className="px-3 py-2.5">Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {items.map((a) => (
                        <tr key={a.id} className="border-b border-zinc-800/40">
                          <td className="px-4 py-2.5 font-medium text-zinc-200">{TYPE_ICONS[a.type]} {a.name}</td>
                          <td className="px-3 py-2.5 text-zinc-400">{ASSET_TYPE_LABELS[a.type] ?? a.type}</td>
                          <td className="px-3 py-2.5 text-xs text-zinc-500">{a.tags ?? "—"}</td>
                          <td className="px-3 py-2.5 text-xs text-zinc-500">{sizeLabel(a.size) || "—"}</td>
                          <td className="whitespace-nowrap px-3 py-2.5 text-xs text-zinc-500">{fmtDate(a.createdAt)}{a.uploadedBy ? ` · ${a.uploadedBy}` : ""}</td>
                          <td className="px-3 py-2.5">
                            <div className="flex items-center gap-2">
                              <a href={a.url} target="_blank" rel="noreferrer" className={btn.smSecondary}>View</a>
                              {canMutate && (
                                <form action={deleteAsset.bind(null, a.id)}>
                                  <button className="rounded-lg px-2 py-1.5 text-xs text-red-500 transition hover:bg-red-500/10">Delete</button>
                                </form>
                              )}
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </Card>
              )}
            </div>
          ))}
        </div>
      )}
    </main>
  );
}
