"use client";

import { useCallback, useEffect, useState } from "react";

import { FileUploadField } from "@/components/admin/FileUploadField";

interface Asset { id: string; name: string; kind: string; url: string; size_bytes?: number | null; sort: number }

const inp = "rounded-lg border border-[#262b40] bg-[#0c0e1a] px-2 py-1 text-sm text-gray-100 outline-none focus:border-indigo-500";

const KINDS = [
  { v: "footage", l: "ویدیو/فوتیج" },
  { v: "image", l: "تصویر" },
  { v: "audio", l: "صدا" },
  { v: "font", l: "فونت" },
  { v: "other", l: "سایر" },
];

/** Manage the named asset files (footage/images/audio/fonts) attached to one project. */
export function ProjectAssets({ projectId }: { projectId: string }) {
  const [assets, setAssets] = useState<Asset[]>([]);
  const [name, setName] = useState("");
  const [kind, setKind] = useState("footage");
  const [busy, setBusy] = useState(false);
  const base = `/api/admin/resource/projects/${projectId}/assets`;

  const load = useCallback(async () => {
    const r = await fetch(base, { cache: "no-store" }).then((x) => x.json()).catch(() => null);
    setAssets(Array.isArray(r) ? r : r?.data ?? []);
  }, [base]);
  useEffect(() => { load(); }, [load]);

  const add = async (url: string) => {
    if (!url) return;
    setBusy(true);
    const fileName = name || url.split("/").pop() || "asset";
    const res = await fetch(base, {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: fileName, kind, url, sort: assets.length }),
    });
    if (res.ok) { setName(""); load(); }
    setBusy(false);
  };

  const remove = async (id: string) => {
    await fetch(`${base}/${id}`, { method: "DELETE" });
    load();
  };

  return (
    <div className="rounded-lg border border-[#262b40] p-2">
      <p className="mb-2 text-[11px] font-medium text-gray-400">فایل‌های پروژه (فوتیج/تصویر/صدا/فونت)</p>
      {assets.length === 0 ? (
        <p className="px-1 text-xs text-gray-600">هنوز فایلی اضافه نشده.</p>
      ) : (
        <ul className="mb-2 space-y-1">
          {assets.map((a) => (
            <li key={a.id} className="flex items-center justify-between rounded bg-[#0c0e1a] px-2 py-1 text-xs">
              <span className="flex items-center gap-2">
                <span className="rounded bg-[#1e2235] px-1.5 py-0.5 text-[10px] text-gray-400">{KINDS.find((k) => k.v === a.kind)?.l ?? a.kind}</span>
                <a href={a.url} target="_blank" rel="noreferrer" className="text-gray-200 hover:underline" dir="ltr">{a.name}</a>
              </span>
              <button className="text-red-300 hover:text-red-200" onClick={() => remove(a.id)}>حذف</button>
            </li>
          ))}
        </ul>
      )}
      <div className="flex flex-wrap items-end gap-2 border-t border-[#1e2235] pt-2">
        <input className={`${inp} w-36`} placeholder="نام فایل (اختیاری)" value={name} onChange={(e) => setName(e.target.value)} />
        <select className={inp} value={kind} onChange={(e) => setKind(e.target.value)}>
          {KINDS.map((k) => <option key={k.v} value={k.v}>{k.l}</option>)}
        </select>
        <FileUploadField value="" onChange={add} accept="*/*" />
        {busy && <span className="text-[11px] text-gray-500">در حال افزودن…</span>}
      </div>
    </div>
  );
}
