"use client";
import { useEffect, useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Tag, ChevronDown, Eye, EyeOff, Gem, Star, Package, MinusCircle } from "lucide-react";
import { useSelection } from "@/components/select/SelectionProvider";
import { bulkSetMark, bulkSetWatched, bulkSetOwned } from "@/app/actions/bulk";
import { dispatchQueueRemove } from "@/components/queue/watchQueueEvents";
import { cn } from "@/lib/utils";

type Action = "watched" | "unwatched" | "vip" | "favorite" | "owned" | "unmark";

export function MarkActionPopover() {
  const sel = useSelection();
  const count = sel.ids.size;
  const enabled = count > 0;

  const [open, setOpen] = useState(false);
  const wrapRef = useRef<HTMLDivElement>(null);
  const [pending, start] = useTransition();
  const router = useRouter();

  useEffect(() => {
    if (!open) return;
    const onDoc = (e: MouseEvent) => {
      if (!wrapRef.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  // If selection drains while menu is open, close it.
  useEffect(() => {
    if (!enabled && open) setOpen(false);
  }, [enabled, open]);

  function pick(action: Action) {
    setOpen(false);
    const ids = Array.from(sel.ids);
    if (ids.length === 0) return;
    start(async () => {
      if (action === "watched") { await bulkSetWatched(ids, true); dispatchQueueRemove(ids); }
      else if (action === "unwatched") await bulkSetWatched(ids, false);
      else if (action === "vip") await bulkSetMark(ids, "vip");
      else if (action === "favorite") await bulkSetMark(ids, "favorite");
      else if (action === "owned") await bulkSetOwned(ids, true);
      else if (action === "unmark") await bulkSetMark(ids, "unmarked");
      router.refresh();
    });
  }

  return (
    <div className="relative" ref={wrapRef}>
      <button
        type="button"
        onClick={() => enabled && setOpen((v) => !v)}
        disabled={!enabled || pending}
        title={enabled ? `Mark ${count} selected cover${count === 1 ? "" : "s"}` : "Select covers first"}
        className={cn(
          "flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-sm transition-colors min-w-[140px] justify-between",
          enabled
            ? "bg-[var(--color-cyan)]/10 border-[var(--color-cyan)]/40 text-[var(--color-cyan)] hover:bg-[var(--color-cyan)]/20"
            : "glass text-[var(--color-fg-muted)] opacity-50 cursor-not-allowed",
        )}
      >
        <Tag className="w-3.5 h-3.5" />
        Mark As
        <span
          className={cn(
            "inline-flex items-center justify-center min-w-[22px] h-4 px-1 rounded-full text-black text-[10px] font-mono font-bold tabular-nums bg-[var(--color-cyan)]",
            !enabled && "invisible",
          )}
        >
          {count}
        </span>
        <ChevronDown className="w-3 h-3 opacity-70" />
      </button>

      {open && enabled && (
        <div
          className="absolute left-0 top-[calc(100%+6px)] z-30 bg-[var(--color-bg-0)] border border-[var(--color-glass-border-strong)] rounded-xl shadow-2xl p-1 w-56"
          onClick={(e) => e.stopPropagation()}
        >
          <Row icon={Eye} label="Watched" colorClass="text-[var(--color-mint)]" onClick={() => pick("watched")} />
          <Row icon={EyeOff} label="Unwatched" onClick={() => pick("unwatched")} />
          <Divider />
          <Row icon={Gem} label="VIP" colorClass="text-[var(--color-cyan)]" onClick={() => pick("vip")} />
          <Row icon={Star} label="Favorite" colorClass="text-amber-300" iconStyle={{ fill: "#fbbf24" }} onClick={() => pick("favorite")} />
          <Row icon={Package} label="Owned" colorClass="text-[var(--color-violet)]" onClick={() => pick("owned")} />
          <Row icon={MinusCircle} label="Unmark VIP/Fav" colorClass="text-[var(--color-fg-muted)]" onClick={() => pick("unmark")} />
        </div>
      )}
    </div>
  );
}

function Divider() {
  return <div className="h-px bg-[var(--color-glass-border)] my-1" />;
}

function Row({
  icon: Icon,
  label,
  onClick,
  colorClass,
  iconStyle,
}: {
  icon: React.ComponentType<{ className?: string; style?: React.CSSProperties }>;
  label: string;
  onClick: () => void;
  colorClass?: string;
  iconStyle?: React.CSSProperties;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={cn(
        "w-full flex items-center gap-2.5 px-2 py-1.5 rounded-md text-sm text-left transition-colors hover:bg-[var(--color-glass)]",
        colorClass ?? "text-[var(--color-fg-dim)]",
      )}
    >
      <Icon className="w-3.5 h-3.5" style={iconStyle} />
      <span className="flex-1">{label}</span>
    </button>
  );
}
