import { db } from "@/lib/db";
import { requireConfAccess } from "@/lib/rbac";
import { Badge, btn, Card, EmptyState, Field, PageHeader, input } from "@/components/ui";
import { fmtDate } from "@/lib/utils";
import { ASSET_TYPES, ASSET_TYPE_LABELS } from "@/lib/constants";
import { attachAssetFromLibrary, deleteConfAsset, uploadConfAssets } from "../actions";

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

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

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`;
}

export default async function ConferenceAssetsPage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ saved?: string; error?: string }>;
}) {
  const { id } = await params;
  const { saved, error } = await searchParams;
  await requireConfAccess(id, "content.manage");
  const conf = await db.conference.findUniqueOrThrow({ where: { id }, select: { orgId: true, name: true } });

  const [assets, libraryAssets] = await Promise.all([
    db.asset.findMany({ where: { conferenceId: id }, orderBy: { createdAt: "desc" } }),
    db.asset.findMany({
      where: { orgId: conf.orgId, OR: [{ conferenceId: null }, { conferenceId: { not: id } }] },
      orderBy: { createdAt: "desc" },
      select: { id: true, name: true, type: true, url: true, conferenceId: true },
    }),
  ]);
  // Hide library entries whose file is already attached here.
  const hereUrls = new Set(assets.map((a) => a.url));
  const attachable = libraryAssets.filter((a) => !hereUrls.has(a.url));

  return (
    <main>
      <PageHeader
        title="Assets"
        sub={`${assets.length} files for this conference — logos, banners, brochures, creatives and documents.`}
      />
      {saved && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">✓ {saved}</p>}
      {error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{error}</p>}

      <div className="grid gap-4 lg:grid-cols-2">
        <Card className="p-5">
          <h3 className="text-sm font-bold text-zinc-100">Upload to this conference</h3>
          <form action={uploadConfAssets.bind(null, id)} className="mt-3 grid gap-3 sm:grid-cols-2">
            <div className="sm:col-span-2">
              <Field name="files" title="Files (bulk 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="tags" title="Tags"><input id="tags" name="tags" placeholder="print, social…" className={input} /></Field>
            <div className="sm:col-span-2"><button className={btn.primary}>Upload</button></div>
          </form>
        </Card>

        <Card className="p-5">
          <h3 className="text-sm font-bold text-zinc-100">📚 Use from organization library</h3>
          <p className="mt-0.5 text-xs text-zinc-500">
            {attachable.length > 0
              ? `${attachable.length} asset${attachable.length === 1 ? "" : "s"} in ${"your library"} can be used here — same file, no re-upload.`
              : "Everything in your organization library is already attached here."}
          </p>
          {attachable.length > 0 && (
            <form action={attachAssetFromLibrary.bind(null, id)} className="mt-3 flex flex-wrap gap-2">
              <select name="assetId" required className={`${input} max-w-sm`} aria-label="Asset from library">
                <option value="">Choose an asset…</option>
                {attachable.map((a) => (
                  <option key={a.id} value={a.id}>
                    {TYPE_ICONS[a.type] ?? "📁"} {a.name}{a.conferenceId ? "" : " (org-wide)"}
                  </option>
                ))}
              </select>
              <button className={btn.secondary}>Attach</button>
            </form>
          )}
          <p className="mt-3 text-xs text-zinc-600">Manage the full library in the console → <b>Assets</b>.</p>
        </Card>
      </div>

      {assets.length === 0 ? (
        <div className="mt-6"><EmptyState title="No assets yet" body="Upload files or attach them from your organization library." /></div>
      ) : (
        <div className="mt-6 grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
          {assets.map((a) => (
            <Card key={a.id} className="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>
                <div className="mt-2 flex items-center justify-between text-[11px]">
                  <span className="text-zinc-600">{fmtDate(a.createdAt)}</span>
                  <span className="flex items-center gap-2">
                    <a href={a.url} download className="font-medium text-indigo-600 hover:underline">⬇</a>
                    <form action={deleteConfAsset.bind(null, id, a.id)}>
                      <button className="text-red-500 hover:underline">Delete</button>
                    </form>
                  </span>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}
    </main>
  );
}
