"use client";

import { useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState, type DragEvent } from "react";
import { errorMessage } from "@/app/(admin)/_lib/api";
import { ACCEPT, deleteMedia, fileProblem, mediaName, mediaUrl, prettySize, renameMedia, uploadMedia, type Media, type MediaKind, type MediaQuery } from "@/app/(admin)/_lib/media";
import { qk, useMediaList } from "@/app/(admin)/_lib/queries";
import { useStore } from "@/app/(admin)/_lib/store";
import { Icon } from "./Icon";
import { ConfirmDialog, Modal } from "./Modal";

const SORTS = [
  ["-createdAt", "Newest first"],
  ["originalName", "File name"],
  ["title", "Title"],
  ["size", "Smallest first"],
] as const;

const hasFiles = (e: DragEvent) => Array.from(e.dataTransfer.types).includes("Files");

/** Upload files one by one (keeps under the 30/min limit for normal use); returns what succeeded. */
export function useUploader() {
  const qc = useQueryClient();
  const { toast } = useStore();
  const [busy, setBusy] = useState<{ done: number; total: number } | null>(null);
  const [errors, setErrors] = useState<string[]>([]);

  const upload = async (files: File[], want: MediaKind | "any" = "any"): Promise<Media[]> => {
    const problems = files.map((f) => fileProblem(f, want)).filter((p): p is string => !!p);
    const ok = files.filter((f) => !fileProblem(f, want));
    setErrors(problems);
    if (!ok.length) return [];
    const out: Media[] = [];
    setBusy({ done: 0, total: ok.length });
    for (const [i, f] of ok.entries()) {
      try {
        out.push(await uploadMedia(f, f.name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ")));
      } catch (e) {
        setErrors((x) => [...x, `${f.name}: ${errorMessage(e)}`]);
      }
      setBusy({ done: i + 1, total: ok.length });
    }
    setBusy(null);
    if (out.length) {
      qc.invalidateQueries({ queryKey: qk.media() });
      toast(out.length === 1 ? `Uploaded ${out[0].originalName}` : `Uploaded ${out.length} files`);
    }
    return out;
  };
  return { upload, busy, errors, clearErrors: () => setErrors([]) };
}

function Thumb({ m }: { m: Media }) {
  const [failed, setFailed] = useState(false);
  if (failed || m.kind === "document") return <div className="ml-thumb ph">{m.kind === "document" ? "PDF" : m.mimeType.split("/")[1]?.toUpperCase()}</div>;
  return m.kind === "video" ? (
    <video className="ml-thumb" src={mediaUrl(m)} muted preload="metadata" onError={() => setFailed(true)} />
  ) : (
    // eslint-disable-next-line @next/next/no-img-element -- media from the CMS host
    <img className="ml-thumb" src={mediaUrl(m)} alt={m.title ?? ""} loading="lazy" onError={() => setFailed(true)} />
  );
}

type BrowserProps = { mode: "page" | "pick"; kind?: MediaKind; onPick?: (m: Media) => void };

export function MediaBrowser({ mode, kind, onPick }: BrowserProps) {
  const qc = useQueryClient();
  const { toast } = useStore();
  const [q, setQ] = useState<MediaQuery>({ page: 1, limit: mode === "pick" ? 12 : 24, search: "", kind: kind ?? "", sort: "-createdAt" });
  const [searchText, setSearchText] = useState("");
  useEffect(() => {
    const t = setTimeout(() => setQ((p) => (p.search === searchText ? p : { ...p, search: searchText, page: 1 })), 300);
    return () => clearTimeout(t);
  }, [searchText]);

  const { data, error, isPending, isFetching, refetch } = useMediaList(q);
  const items = data?.data ?? [];
  const meta = data?.meta;
  const { upload, busy, errors, clearErrors } = useUploader();
  const fileRef = useRef<HTMLInputElement>(null);
  const [over, setOver] = useState(false);

  const [renaming, setRenaming] = useState<{ id: string; title: string } | null>(null);
  const [deleting, setDeleting] = useState<Media | null>(null);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [deleteBusy, setDeleteBusy] = useState(false);

  const doUpload = async (files: File[]) => {
    const done = await upload(files, kind ?? "any");
    setQ((p) => ({ ...p, page: 1, sort: "-createdAt" }));
    if (mode === "pick" && done.length === 1) onPick?.(done[0]);
  };

  const saveTitle = async () => {
    if (!renaming) return;
    try {
      await renameMedia(renaming.id, renaming.title.trim() || null);
      qc.invalidateQueries({ queryKey: qk.media() });
      toast("Title saved");
      setRenaming(null);
    } catch (e) {
      toast(errorMessage(e));
    }
  };

  const doDelete = async () => {
    if (!deleting) return;
    setDeleteBusy(true);
    setDeleteError(null);
    try {
      await deleteMedia(deleting.id);
      qc.invalidateQueries({ queryKey: qk.media() });
      toast(`Deleted ${mediaName(deleting)}`);
      setDeleting(null);
    } catch (e) {
      setDeleteError(errorMessage(e));
    } finally {
      setDeleteBusy(false);
    }
  };

  const copy = async (m: Media) => {
    try {
      await navigator.clipboard.writeText(mediaUrl(m));
      toast("URL copied");
    } catch {
      toast(mediaUrl(m));
    }
  };

  const set = (patch: Partial<MediaQuery>) => setQ((p) => ({ ...p, ...patch, page: patch.page ?? 1 }));
  const accept = kind ? ACCEPT[kind] : ACCEPT.any;

  return (
    <div className="ml">
      <div
        className={`ml-drop${over ? " over" : ""}`}
        onDragOver={(e) => {
          if (!hasFiles(e)) return;
          e.preventDefault();
          setOver(true);
        }}
        onDragLeave={() => setOver(false)}
        onDrop={(e) => {
          if (!hasFiles(e)) return;
          e.preventDefault();
          setOver(false);
          doUpload(Array.from(e.dataTransfer.files));
        }}
      >
        <Icon name="upload" size={20} />
        <div>
          {busy ? (
            <b>
              Uploading {busy.done + 1 > busy.total ? busy.total : busy.done + 1} of {busy.total}…
            </b>
          ) : (
            <p>
              <b>Drop {kind === "video" ? "videos" : kind === "image" ? "images" : kind === "document" ? "PDFs" : "files"} here</b> or{" "}
              <button type="button" className="link" onClick={() => fileRef.current?.click()}>
                browse
              </button>
            </p>
          )}
          <span>
            {kind === "video"
              ? "MP4 or WebM, up to 10 MB"
              : kind === "image"
                ? "JPG, PNG, WebP, GIF, AVIF up to 10 MB · SVG up to 1 MB"
                : kind === "document"
                  ? "PDF up to 20 MB (downloaded on the website)"
                  : "Images up to 10 MB (SVG 1 MB) · MP4/WebM video up to 10 MB · PDF up to 20 MB"}
          </span>
        </div>
        {busy && <span className="spin dark" />}
        <input
          ref={fileRef}
          type="file"
          accept={accept}
          multiple={mode === "page"}
          hidden
          onChange={(e) => {
            doUpload(Array.from(e.target.files ?? []));
            e.target.value = "";
          }}
        />
      </div>
      {errors.length > 0 && (
        <div className="form-error" role="alert">
          {errors.join("\n")}
          <button type="button" className="link" style={{ marginLeft: 8 }} onClick={clearErrors}>
            Dismiss
          </button>
        </div>
      )}

      <div className="toolbar ml-tools">
        <div className="search">
          <Icon name="search" />
          <input placeholder="Search file name or title…" aria-label="Search media" maxLength={100} value={searchText} onChange={(e) => setSearchText(e.target.value)} />
        </div>
        {!kind && (
          <select className="select" aria-label="Filter by type" value={q.kind} onChange={(e) => set({ kind: e.target.value as MediaQuery["kind"] })}>
            <option value="">All types</option>
            <option value="image">Images</option>
            <option value="video">Videos</option>
            <option value="document">Documents (PDF)</option>
          </select>
        )}
        <select className="select" aria-label="Sort" value={q.sort} onChange={(e) => set({ sort: e.target.value })}>
          {SORTS.map(([v, l]) => (
            <option key={v} value={v}>
              {l}
            </option>
          ))}
        </select>
        {isFetching && !isPending && <span className="spin dark" aria-label="Updating" />}
      </div>

      {isPending ? (
        <div className="ml-empty">
          <span className="spin dark" /> Loading media…
        </div>
      ) : error ? (
        <div className="ml-empty">
          {errorMessage(error)}{" "}
          <button type="button" className="link" onClick={() => refetch()}>
            Retry
          </button>
        </div>
      ) : items.length === 0 ? (
        <div className="ml-empty">{q.search || q.kind ? "No media matches." : "No media yet. Upload the first file above."}</div>
      ) : (
        <ul className={`ml-grid${mode === "pick" ? " pick" : ""}`}>
          {items.map((m) => (
            <li key={m.id} className="ml-card">
              {mode === "pick" ? (
                <button type="button" className="ml-pick" onClick={() => onPick?.(m)} aria-label={`Use ${mediaName(m)}`}>
                  <Thumb m={m} />
                </button>
              ) : (
                <a href={mediaUrl(m)} target="_blank" rel="noreferrer" className="ml-pick" aria-label={`Open ${mediaName(m)}`}>
                  <Thumb m={m} />
                </a>
              )}
              <div className="ml-info">
                {renaming?.id === m.id ? (
                  <form
                    className="ml-rename"
                    onSubmit={(e) => {
                      e.preventDefault();
                      saveTitle();
                    }}
                  >
                    <input className="input input-sm" autoFocus maxLength={150} placeholder={m.originalName} value={renaming.title} onChange={(e) => setRenaming({ ...renaming, title: e.target.value })} aria-label="Title" />
                    <button type="submit" className="link">
                      Save
                    </button>
                    <button type="button" className="link" onClick={() => setRenaming(null)}>
                      Cancel
                    </button>
                  </form>
                ) : (
                  <b title={m.originalName}>{mediaName(m)}</b>
                )}
                <span>
                  {(m.mimeType.split("/")[1] ?? "").replace("svg+xml", "svg").toUpperCase()} · {prettySize(m.size)}
                  {m.width && m.height ? ` · ${m.width}×${m.height}` : ""}
                </span>
                {mode === "page" && renaming?.id !== m.id && (
                  <div className="ml-actions">
                    <button type="button" className="link" onClick={() => copy(m)}>
                      Copy URL
                    </button>
                    <button type="button" className="link" onClick={() => setRenaming({ id: m.id, title: m.title ?? "" })}>
                      Rename
                    </button>
                    <button
                      type="button"
                      className="link danger"
                      onClick={() => {
                        setDeleteError(null);
                        setDeleting(m);
                      }}
                    >
                      Delete
                    </button>
                  </div>
                )}
              </div>
            </li>
          ))}
        </ul>
      )}

      {meta && meta.totalPages > 1 && (
        <div className="pager">
          <span>
            {(meta.page - 1) * meta.limit + 1}–{Math.min(meta.page * meta.limit, meta.total)} of {meta.total}
          </span>
          <div>
            <button type="button" className="btn btn-outline btn-sm" disabled={meta.page <= 1} onClick={() => set({ page: meta.page - 1 })}>
              Previous
            </button>
            <button type="button" className="btn btn-outline btn-sm" disabled={meta.page >= meta.totalPages} onClick={() => set({ page: meta.page + 1 })}>
              Next
            </button>
          </div>
        </div>
      )}

      {deleting && (
        <ConfirmDialog title={`Delete ${mediaName(deleting)}?`} confirmLabel="Delete file" danger busy={deleteBusy} onConfirm={doDelete} onClose={() => setDeleting(null)}>
          The file is removed and its URL stops working. Files still used in page content (draft or live) can&apos;t be deleted.
          {deleteError && <div className="form-error">{deleteError}</div>}
        </ConfirmDialog>
      )}
    </div>
  );
}

/** "Choose from library" dialog used by image/video fields. */
export function MediaPicker({ kind, onPick, onClose }: { kind: MediaKind; onPick: (m: Media) => void; onClose: () => void }) {
  return (
    <Modal title={kind === "video" ? "Choose a video" : kind === "document" ? "Choose a PDF" : "Choose an image"} onClose={onClose} wide>
      <MediaBrowser mode="pick" kind={kind} onPick={onPick} />
    </Modal>
  );
}
