import { useCallback, useEffect, useState } from "react";
import { apiGet, apiPost } from "../../api";
import { PageHead, Empty, Loading } from "../../components/ui";
import { IconCheck, IconGrid, IconRefresh, IconSearch } from "../../components/icons";
import { useToast } from "../../lib/toast";

interface Item {
  id: string;
  name: string;
  year?: number;
  type: string;
  poster_url: string | null;
  has_primary: boolean;
  has_logo: boolean;
  has_backdrop: boolean;
  can_bulk_assign: boolean;
}

const STUDIOS = ["netflix", "appletv", "paramountplus", "hbo", "disney", "hulu"];

export default function BulkAssign() {
  const toast = useToast();
  const [kind, setKind] = useState<"series" | "movies">("series");
  const [query, setQuery] = useState("");
  const [items, setItems] = useState<Item[]>([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [working, setWorking] = useState(false);

  const load = useCallback(() => {
    setLoading(true);
    apiGet<{ items: Item[]; total: number }>(`/api/bulk-assign/${kind}?q=${encodeURIComponent(query.trim())}&limit=60`)
      .then((d) => {
        setItems(d.items);
        setTotal(d.total);
      })
      .catch((e) => toast(e.message, "err"))
      .finally(() => setLoading(false));
  }, [kind, query, toast]);

  useEffect(() => {
    load();
  }, [kind]); // eslint-disable-line react-hooks/exhaustive-deps

  function toggle(id: string) {
    setSelected((s) => {
      const n = new Set(s);
      n.has(id) ? n.delete(id) : n.add(id);
      return n;
    });
  }
  function selectAllEligible() {
    setSelected(new Set(items.filter((i) => i.can_bulk_assign).map((i) => i.id)));
  }

  async function applySelected() {
    const ids = [...selected];
    if (!ids.length) return;
    setWorking(true);
    try {
      const res = await apiPost("/api/bulk-assign/apply", { item_ids: ids });
      toast(`Applied ${res.applied_count}, skipped ${res.skipped_missing_assets_count}, failed ${res.failed_count}`, "ok");
      setSelected(new Set());
    } catch (e: any) {
      toast(e.message, "err");
    } finally {
      setWorking(false);
    }
  }

  async function applyAll() {
    if (!window.confirm(`Apply thumbnails to ALL eligible ${kind} in your library? This may take a while.`)) return;
    setWorking(true);
    try {
      const res = await apiPost("/api/bulk-assign/apply-all", { item_type: kind === "series" ? "series" : "movie" });
      toast(`Applied ${res.applied_count} of ${res.eligible_count} eligible`, "ok");
    } catch (e: any) {
      toast(e.message, "err");
    } finally {
      setWorking(false);
    }
  }

  async function resetStudio(studio: string) {
    if (!window.confirm(`Reset Emby Thumb & Primary images for all ${studio} titles? Emby will re-download originals.`)) return;
    setWorking(true);
    try {
      const res = await apiPost("/api/bulk-reset/studio", { studio_key: studio });
      toast(`Reset ${res.reset} titles (${res.skipped} skipped)`, "ok");
    } catch (e: any) {
      toast(e.message, "err");
    } finally {
      setWorking(false);
    }
  }

  return (
    <>
      <PageHead title="Bulk Assign" icon={<IconGrid />} />

      <div className="row between wrap" style={{ marginBottom: 16, gap: 12 }}>
        <div className="row gap-sm wrap">
          <div className="seg">
            <button className={`seg-btn ${kind === "series" ? "active" : ""}`} onClick={() => setKind("series")}>
              Series
            </button>
            <button className={`seg-btn ${kind === "movies" ? "active" : ""}`} onClick={() => setKind("movies")}>
              Movies
            </button>
          </div>
          <form
            className="search-inner"
            style={{ width: 240 }}
            onSubmit={(e) => {
              e.preventDefault();
              load();
            }}
          >
            <IconSearch />
            <input className="input" placeholder="Filter…" value={query} onChange={(e) => setQuery(e.target.value)} />
          </form>
        </div>
        <div className="row gap-sm wrap">
          <button className="btn" onClick={selectAllEligible}>
            Select eligible
          </button>
          {selected.size > 0 && (
            <button className="btn btn-primary" onClick={applySelected} disabled={working}>
              {working ? <span className="spinner" /> : <IconCheck />} Apply {selected.size}
            </button>
          )}
          <button className="btn btn-green" onClick={applyAll} disabled={working}>
            Apply all eligible
          </button>
        </div>
      </div>

      <div className="hint" style={{ marginBottom: 14 }}>
        {total} {kind} · {items.filter((i) => i.can_bulk_assign).length} eligible on this page
      </div>

      {loading ? (
        <Loading />
      ) : !items.length ? (
        <div className="panel">
          <Empty icon={<IconGrid />}>No titles found.</Empty>
        </div>
      ) : (
        <div className="card-grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))" }}>
          {items.map((it) => (
            <div
              key={it.id}
              className={`media-card ${selected.has(it.id) ? "selected" : ""}`}
              onClick={() => it.can_bulk_assign && toggle(it.id)}
              style={{ opacity: it.can_bulk_assign ? 1 : 0.55, cursor: it.can_bulk_assign ? "pointer" : "default" }}
            >
              {it.poster_url ? (
                <img className="media-cover poster" src={it.poster_url} loading="lazy" alt="" />
              ) : (
                <div className="media-cover poster" />
              )}
              <div className="media-body">
                <div className="media-title">{it.name}</div>
                <div className="row wrap" style={{ gap: 4, marginTop: 5 }}>
                  <span className={`badge ${it.has_logo ? "badge-ok" : "badge-bad"}`} style={{ padding: "1px 6px" }}>
                    logo
                  </span>
                  <span className={`badge ${it.has_backdrop ? "badge-ok" : "badge-bad"}`} style={{ padding: "1px 6px" }}>
                    bd
                  </span>
                  {selected.has(it.id) && <span className="badge badge-accent" style={{ padding: "1px 6px" }}>✓</span>}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="panel" style={{ marginTop: 24 }}>
        <div className="panel-head">
          <h3>Reset studio artwork</h3>
          <span className="sub">Delete generated Thumb/Primary so Emby re-downloads originals</span>
        </div>
        <div className="panel-body row wrap" style={{ gap: 8 }}>
          {STUDIOS.map((s) => (
            <button key={s} className="btn btn-sm btn-danger" onClick={() => resetStudio(s)} disabled={working}>
              <IconRefresh /> {s}
            </button>
          ))}
        </div>
      </div>
    </>
  );
}
