"use client";

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

import { FILE_TYPE_TABS, fetchFiles, fileUrl, humanSize, isImage, isVideo, type FileItem } from "@/lib/admin-files";

/** Modal to pick an existing file from the media library (search + type filter). */
export function FilePicker({
  open,
  onClose,
  onSelect,
  initialType = "",
}: {
  open: boolean;
  onClose: () => void;
  onSelect: (url: string, file: FileItem) => void;
  initialType?: string;
}) {
  const [files, setFiles] = useState<FileItem[]>([]);
  const [search, setSearch] = useState("");
  const [type, setType] = useState(initialType);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    setFiles(await fetchFiles(search, type));
    setLoading(false);
  }, [search, type]);
  useEffect(() => { if (open) load(); }, [open, load]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[60] flex items-stretch justify-center bg-black/70 p-2 sm:p-6" dir="rtl" onClick={onClose}>
      <div className="flex max-h-full w-full max-w-4xl flex-col rounded-xl border border-[#1e2235] bg-[#0f1120]" onClick={(e) => e.stopPropagation()}>
        <div className="flex flex-wrap items-center gap-2 border-b border-[#1e2235] px-4 py-3">
          <h2 className="text-sm font-semibold text-white">انتخاب از کتابخانه</h2>
          <input
            className="ms-auto w-48 rounded-lg border border-[#262b40] bg-[#0c0e1a] px-3 py-1.5 text-sm text-gray-100 outline-none focus:border-indigo-500"
            placeholder="جستجو…" value={search} onChange={(e) => setSearch(e.target.value)}
          />
          <button className="rounded-lg px-2 py-1 text-gray-400 hover:bg-[#161a2e] hover:text-white" onClick={onClose}>✕</button>
        </div>
        <div className="flex flex-wrap gap-1 border-b border-[#1e2235] px-4 py-2">
          {FILE_TYPE_TABS.map((t) => (
            <button key={t.v} onClick={() => setType(t.v)}
              className={`rounded-lg px-2.5 py-1 text-xs ${type === t.v ? "bg-indigo-600 text-white" : "border border-[#262b40] text-gray-400 hover:bg-[#161a2e]"}`}>
              {t.l}
            </button>
          ))}
        </div>
        <div className="flex-1 overflow-y-auto p-4">
          {loading ? (
            <p className="py-10 text-center text-sm text-gray-500">در حال بارگذاری…</p>
          ) : files.length === 0 ? (
            <p className="py-10 text-center text-sm text-gray-500">فایلی یافت نشد.</p>
          ) : (
            <div className="grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-6">
              {files.map((f) => {
                const url = fileUrl(f);
                return (
                  <button key={f.id} type="button" onClick={() => url && onSelect(url, f)}
                    className="group rounded-lg border border-[#262b40] bg-[#0c0e1a] p-2 text-start hover:border-indigo-500">
                    <div className="flex aspect-square items-center justify-center overflow-hidden rounded-md bg-[#070811]">
                      {url && isImage(f) ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={url} alt={f.name} className="h-full w-full object-cover" />
                      ) : url && isVideo(f) ? (
                        <video src={url} className="h-full w-full object-cover" muted />
                      ) : (
                        <span className="text-[10px] uppercase text-gray-500">{(f.name.split(".").pop() ?? "file").slice(0, 5)}</span>
                      )}
                    </div>
                    <p className="mt-1.5 truncate text-[11px] text-gray-300" title={f.name}>{f.name}</p>
                    <p className="text-[10px] text-gray-600">{humanSize(f.size_bytes)}</p>
                  </button>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
