import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  DndContext,
  KeyboardSensor,
  PointerSensor,
  closestCenter,
  useSensor,
  useSensors,
  type DragEndEvent,
} from "@dnd-kit/core";
import {
  SortableContext,
  arrayMove,
  sortableKeyboardCoordinates,
  useSortable,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
  ArrowLeft,
  ChevronDown,
  ChevronRight,
  GripVertical,
  ListTree,
  Pencil,
  Play,
  Rows3,
  Trash2,
  X,
} from "lucide-react";
import { api, type PlexCard } from "../lib/api";
import { getAccountRaw, LS, setAccountRaw } from "../lib/storage";
import { useConfirm } from "./ConfirmProvider";

// A playlist's items, grouped for readability: movies stay standalone, while a run of episodes from the
// same show collapses into a season/show group so a whole series doesn't sprawl into an endless flat
// list. Reorder is drag & drop (a whole show-group moves as one block; episodes reorder within their
// show). Two layouts — Accordion (A) and Tree (C) — are a per-account preference. Rendered as a
// PlexBrowse subview; "Play all" opens the player with the whole ordered list as its queue.

type Layout = "accordion" | "tree";
type Season = { key: string; number: number | null; items: PlexCard[] };
type Block =
  | { kind: "movie"; id: string; item: PlexCard }
  | { kind: "show"; id: string; showKey: string; title: string; items: PlexCard[]; seasons: Season[] };

function buildSeasons(items: PlexCard[]): Season[] {
  const map = new Map<string, Season>();
  for (const it of items) {
    const num = it.season_number ?? null;
    const key = String(num ?? "?");
    let s = map.get(key);
    if (!s) {
      s = { key, number: num, items: [] };
      map.set(key, s);
    }
    s.items.push(it);
  }
  return [...map.values()];
}

// Turn the flat ordered list into blocks: contiguous episodes of one show group together (then split
// into seasons for display); everything else (movies) is its own block.
function buildBlocks(items: PlexCard[]): Block[] {
  const blocks: Block[] = [];
  for (const it of items) {
    if (it.type === "episode") {
      const showKey = it.show_id || it.show_title || "?";
      const last = blocks[blocks.length - 1];
      if (last && last.kind === "show" && last.showKey === showKey) {
        last.items.push(it);
      } else {
        blocks.push({
          kind: "show",
          id: `show:${showKey}`,
          showKey,
          title: it.show_title || it.title,
          items: [it],
          seasons: [],
        });
      }
    } else {
      blocks.push({ kind: "movie", id: it.id, item: it });
    }
  }
  for (const b of blocks) if (b.kind === "show") b.seasons = buildSeasons(b.items);
  return blocks;
}

const flatten = (blocks: Block[]): PlexCard[] =>
  blocks.flatMap((b) => (b.kind === "movie" ? [b.item] : b.items));

// Callbacks + shared state passed down to the module-scope block/row components.
type Ctx = {
  layout: Layout;
  busy: boolean;
  expandedShows: Set<string>;
  collapsedSeasons: Set<string>;
  toggleShow: (k: string) => void;
  toggleSeason: (k: string) => void;
  onPlay: (rk: string) => void;
  onRemove: (keys: string[]) => void;
};

function Poster({ src, className }: { src: string; className: string }) {
  return (
    <div className={`relative shrink-0 overflow-hidden rounded border border-border bg-surface ${className}`}>
      <img src={src} alt="" loading="lazy" className="h-full w-full object-cover" />
    </div>
  );
}

function DragHandle(props: Record<string, unknown>) {
  return (
    <button
      {...props}
      className="shrink-0 cursor-grab text-muted hover:text-fg active:cursor-grabbing"
      aria-label="reorder"
    >
      <GripVertical className="h-4 w-4" />
    </button>
  );
}

function EpisodeRow({ ep, ctx, dense }: { ep: PlexCard; ctx: Ctx; dense: boolean }) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: ep.id,
    disabled: ctx.busy,
  });
  const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 };
  const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched";
  return (
    <div
      ref={setNodeRef}
      style={style}
      className={`flex items-center gap-2.5 rounded-lg ${dense ? "px-1.5 py-1" : "glass-card p-1.5"}`}
    >
      <DragHandle {...attributes} {...listeners} />
      <span className="w-5 shrink-0 text-center text-[11px] text-muted tabular-nums">{ep.episode_number}</span>
      <button onClick={() => ctx.onPlay(ep.id)} className="group flex min-w-0 flex-1 items-center gap-2.5 text-left">
        <div className={`relative shrink-0 overflow-hidden rounded border border-border bg-surface ${dense ? "aspect-video w-14" : "aspect-video w-20"}`}>
          <img src={ep.thumb} alt="" loading="lazy" className="h-full w-full object-cover" />
          {ep.status === "watched" && (
            <span className="absolute right-0.5 top-0.5 rounded bg-black/70 px-1 text-[9px] text-white">✓</span>
          )}
          {inProgress && <div className="absolute inset-x-0 bottom-0 h-0.5 bg-accent" />}
          <div className="absolute inset-0 grid place-items-center bg-black/40 opacity-0 transition group-hover:opacity-100">
            <Play className="h-4 w-4 text-white" fill="currentColor" />
          </div>
        </div>
        <div className="min-w-0 truncate text-[13px]">{ep.title}</div>
      </button>
      <button
        onClick={() => ctx.onRemove([ep.id])}
        disabled={ctx.busy}
        className="shrink-0 rounded p-1 text-muted hover:text-red-400 disabled:opacity-30"
        aria-label="remove"
      >
        <X className="h-4 w-4" />
      </button>
    </div>
  );
}

function MovieRow({ item, ctx }: { item: PlexCard; ctx: Ctx }) {
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: item.id,
    disabled: ctx.busy,
  });
  const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 };
  const dense = ctx.layout === "tree";
  return (
    <div ref={setNodeRef} style={style} className="glass-card flex items-center gap-3 rounded-xl p-2">
      <DragHandle {...attributes} {...listeners} />
      <button onClick={() => ctx.onPlay(item.id)} className="group flex min-w-0 flex-1 items-center gap-3 text-left">
        <Poster src={item.thumb} className={dense ? "aspect-[2/3] w-10" : "aspect-[2/3] w-14"} />
        <div className="min-w-0">
          <div className="truncate text-sm font-medium">{item.title}</div>
          <div className="text-xs text-muted">{item.year}</div>
        </div>
        <div className="pointer-events-none ml-auto grid h-8 w-8 shrink-0 place-items-center rounded-full bg-accent/0 text-transparent transition group-hover:bg-accent/15 group-hover:text-accent">
          <Play className="h-4 w-4" fill="currentColor" />
        </div>
      </button>
      <button
        onClick={() => ctx.onRemove([item.id])}
        disabled={ctx.busy}
        className="shrink-0 rounded p-1 text-muted hover:text-red-400 disabled:opacity-30"
        aria-label="remove"
      >
        <X className="h-4 w-4" />
      </button>
    </div>
  );
}

function ShowGroup({ block, ctx }: { block: Extract<Block, { kind: "show" }>; ctx: Ctx }) {
  const { t } = useTranslation();
  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
    id: block.id,
    disabled: ctx.busy,
  });
  const style = { transform: CSS.Transform.toString(transform), transition, opacity: isDragging ? 0.6 : 1 };
  const open = ctx.expandedShows.has(block.showKey);
  const dense = ctx.layout === "tree";
  const seasonLabel = (s: Season) =>
    s.number != null ? t("plex.playlist.season", { n: s.number }) : t("plex.playlist.seasonUnknown");

  return (
    <div ref={setNodeRef} style={style} className="glass-card overflow-hidden rounded-xl">
      {/* Group header — drag moves the whole show; chevron collapses; X removes the whole show. */}
      <div className="flex items-center gap-2.5 p-2">
        <DragHandle {...attributes} {...listeners} />
        <button
          onClick={() => ctx.toggleShow(block.showKey)}
          className="grid h-6 w-6 shrink-0 place-items-center rounded text-muted hover:text-fg"
          aria-expanded={open}
        >
          {open ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
        </button>
        {!dense && (
          <button onClick={() => ctx.toggleShow(block.showKey)} className="flex shrink-0">
            {block.items.slice(0, 3).map((ep, i) => (
              <img
                key={ep.id}
                src={ep.thumb}
                alt=""
                loading="lazy"
                className="aspect-[2/3] w-8 rounded border-2 border-surface object-cover"
                style={{ marginLeft: i ? -14 : 0 }}
              />
            ))}
          </button>
        )}
        <button onClick={() => ctx.toggleShow(block.showKey)} className="min-w-0 flex-1 text-left">
          <div className="truncate text-sm font-semibold">{block.title}</div>
          <div className="text-[11px] text-muted">{t("plex.playlist.episodes", { count: block.items.length })}</div>
        </button>
        <button
          onClick={() => ctx.onRemove(block.items.map((i) => i.id))}
          disabled={ctx.busy}
          title={t("plex.playlist.removeShow")}
          className="shrink-0 rounded p-1 text-muted hover:text-red-400 disabled:opacity-30"
        >
          <X className="h-4 w-4" />
        </button>
      </div>

      {open && (
        <div className={`border-t border-border/50 ${dense ? "px-2 pb-1.5 pt-1" : "px-2 pb-2"}`}>
          <SortableContext items={block.items.map((i) => i.id)} strategy={verticalListSortingStrategy}>
            {block.seasons.map((s) => {
              const sKey = `${block.showKey}:${s.key}`;
              const sOpen = !dense || !ctx.collapsedSeasons.has(sKey);
              return (
                <div key={s.key} className={dense ? "" : "mt-1.5 first:mt-0.5"}>
                  <div className="flex items-center gap-1.5 py-1 pl-1">
                    {dense && (
                      <button
                        onClick={() => ctx.toggleSeason(sKey)}
                        className="grid h-5 w-5 shrink-0 place-items-center rounded text-muted hover:text-fg"
                        aria-expanded={sOpen}
                      >
                        {sOpen ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
                      </button>
                    )}
                    <span className="text-[11px] font-medium uppercase tracking-wide text-muted">
                      {seasonLabel(s)} · {s.items.length}
                    </span>
                    <button
                      onClick={() => ctx.onRemove(s.items.map((i) => i.id))}
                      disabled={ctx.busy}
                      title={t("plex.playlist.removeSeason")}
                      className="ml-1 rounded p-0.5 text-muted hover:text-red-400 disabled:opacity-30"
                    >
                      <X className="h-3.5 w-3.5" />
                    </button>
                  </div>
                  {sOpen && (
                    <div className={dense ? "ml-2 space-y-0.5 border-l border-border/50 pl-1.5" : "space-y-1"}>
                      {s.items.map((ep) => (
                        <EpisodeRow key={ep.id} ep={ep} ctx={ctx} dense={dense} />
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </SortableContext>
        </div>
      )}
    </div>
  );
}

export default function PlexPlaylistView({
  playlistId,
  onBack,
  onPlay,
}: {
  playlistId: number;
  onBack: () => void;
  onPlay: (itemRk: string, queue: string[]) => void;
}) {
  const { t } = useTranslation();
  const qc = useQueryClient();
  const confirm = useConfirm();
  const [renaming, setRenaming] = useState(false);
  const [name, setName] = useState("");
  const [busy, setBusy] = useState(false);
  const [layout, setLayout] = useState<Layout>(() =>
    getAccountRaw(LS.plexPlaylistLayout) === "tree" ? "tree" : "accordion",
  );
  useEffect(() => {
    setAccountRaw(LS.plexPlaylistLayout, layout);
  }, [layout]);
  // Show groups start collapsed (compact headers) so a long series doesn't force endless scrolling;
  // seasons start expanded once their show is opened. Both are just local view state.
  const [expandedShows, setExpandedShows] = useState<Set<string>>(new Set());
  const [collapsedSeasons, setCollapsedSeasons] = useState<Set<string>>(new Set());

  const q = useQuery({ queryKey: ["plex-playlist", playlistId], queryFn: () => api.plexPlaylist(playlistId) });
  // Local optimistic copy so drag/remove are instant; re-synced whenever the query returns.
  const [items, setItems] = useState<PlexCard[]>([]);
  useEffect(() => {
    if (q.data) setItems(q.data.items);
  }, [q.data]);
  const blocks = useMemo(() => buildBlocks(items), [items]);
  const order = useMemo(() => items.map((i) => i.id), [items]);

  const invalidate = () => {
    qc.invalidateQueries({ queryKey: ["plex-playlist", playlistId] });
    qc.invalidateQueries({ queryKey: ["plex-playlists"] });
  };

  function commit(next: PlexCard[]) {
    setItems(next);
    api
      .plexReorderPlaylist(playlistId, next.map((i) => i.id))
      .then(() => qc.invalidateQueries({ queryKey: ["plex-playlists"] }));
  }

  async function onRemove(keys: string[]) {
    if (busy || !keys.length) return;
    setBusy(true);
    const set = new Set(keys);
    setItems((prev) => prev.filter((i) => !set.has(i.id)));
    try {
      if (keys.length === 1) await api.plexPlaylistRemoveItem(playlistId, keys[0]);
      else await api.plexPlaylistRemoveBulk(playlistId, keys);
      invalidate();
    } finally {
      setBusy(false);
    }
  }

  async function rename() {
    const title = name.trim();
    if (!title) return;
    await api.plexRenamePlaylist(playlistId, title);
    setRenaming(false);
    invalidate();
  }
  async function del() {
    if (!(await confirm({ message: t("plex.playlist.deleteConfirm", { title: q.data?.title }), danger: true })))
      return;
    await api.plexDeletePlaylist(playlistId);
    qc.invalidateQueries({ queryKey: ["plex-playlists"] });
    onBack();
  }

  const toggleShow = (k: string) =>
    setExpandedShows((s) => {
      const n = new Set(s);
      n.has(k) ? n.delete(k) : n.add(k);
      return n;
    });
  const toggleSeason = (k: string) =>
    setCollapsedSeasons((s) => {
      const n = new Set(s);
      n.has(k) ? n.delete(k) : n.add(k);
      return n;
    });

  const sensors = useSensors(
    useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
  );

  function onDragEnd(e: DragEndEvent) {
    const { active, over } = e;
    if (!over || active.id === over.id) return;
    const aId = String(active.id);
    const oId = String(over.id);
    const blockIds = new Set(blocks.map((b) => b.id));
    if (blockIds.has(aId)) {
      // Moving a whole block (movie or show). Resolve the drop target to a block.
      let oBlockId = oId;
      if (!blockIds.has(oId)) {
        const b = blocks.find((bl) => bl.kind === "show" && bl.items.some((it) => it.id === oId));
        if (!b) return;
        oBlockId = b.id;
      }
      const from = blocks.findIndex((b) => b.id === aId);
      const to = blocks.findIndex((b) => b.id === oBlockId);
      if (from < 0 || to < 0) return;
      commit(flatten(arrayMove(blocks, from, to)));
    } else {
      // Moving an episode — only within its own show block.
      const b = blocks.find((bl) => bl.kind === "show" && bl.items.some((it) => it.id === aId));
      if (!b || b.kind !== "show" || !b.items.some((it) => it.id === oId)) return;
      const from = b.items.findIndex((it) => it.id === aId);
      const to = b.items.findIndex((it) => it.id === oId);
      commit(flatten(blocks.map((bl) => (bl.id === b.id ? { ...bl, items: arrayMove(b.items, from, to) } : bl))));
    }
  }

  const ctx: Ctx = {
    layout,
    busy,
    expandedShows,
    collapsedSeasons,
    toggleShow,
    toggleSeason,
    onPlay: (rk) => onPlay(rk, order),
    onRemove,
  };

  const LayoutBtn = ({ v, icon, label }: { v: Layout; icon: ReactNode; label: string }) => (
    <button
      onClick={() => setLayout(v)}
      title={label}
      aria-label={label}
      aria-pressed={layout === v}
      className={`rounded-lg p-2 text-sm transition ${
        layout === v ? "bg-accent/15 text-accent" : "glass-card glass-hover text-muted"
      }`}
    >
      {icon}
    </button>
  );

  return (
    <div className="mx-auto w-[90%] max-w-[1100px] p-4">
      <button
        onClick={onBack}
        className="glass-card glass-hover mb-4 inline-flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs"
      >
        <ArrowLeft className="h-4 w-4" />
        {t("plex.backToLibrary")}
      </button>

      <div className="glass rounded-2xl p-4 sm:p-6">
        <div className="mb-4 flex flex-wrap items-center gap-3">
          {renaming ? (
            <input
              autoFocus
              value={name}
              onChange={(e) => setName(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && rename()}
              onBlur={rename}
              className="glass-card min-w-0 flex-1 rounded-lg px-3 py-1.5 text-lg font-bold outline-none focus:border-accent"
            />
          ) : (
            <h1 className="min-w-0 flex-1 truncate text-2xl font-bold">{q.data?.title ?? " "}</h1>
          )}
          {/* Layout preference: Accordion (A) or Tree (C). */}
          <div className="flex items-center gap-1">
            <LayoutBtn v="accordion" icon={<Rows3 className="h-4 w-4" />} label={t("plex.playlist.layoutAccordion")} />
            <LayoutBtn v="tree" icon={<ListTree className="h-4 w-4" />} label={t("plex.playlist.layoutTree")} />
          </div>
          <button
            onClick={() => {
              setName(q.data?.title ?? "");
              setRenaming(true);
            }}
            title={t("plex.playlist.rename")}
            className="glass-card glass-hover rounded-lg p-2 text-sm hover:text-accent"
          >
            <Pencil className="h-4 w-4" />
          </button>
          {items.length > 0 && (
            <button
              onClick={() => onPlay(order[0], order)}
              className="inline-flex items-center gap-2 rounded-xl bg-accent px-4 py-2 font-medium text-white hover:opacity-90"
            >
              <Play className="h-5 w-5 fill-current" />
              {t("plex.playlist.playAll")}
            </button>
          )}
          <button
            onClick={del}
            title={t("plex.playlist.delete")}
            className="glass-card glass-hover rounded-lg p-2 text-sm hover:text-red-400"
          >
            <Trash2 className="h-4 w-4" />
          </button>
        </div>

        {q.isLoading ? (
          <p className="py-6 text-center text-sm text-muted">{t("plex.loading")}</p>
        ) : items.length === 0 ? (
          <p className="py-6 text-center text-sm text-muted">{t("plex.playlist.empty")}</p>
        ) : (
          <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={onDragEnd}>
            <SortableContext items={blocks.map((b) => b.id)} strategy={verticalListSortingStrategy}>
              <div className="space-y-1.5">
                {blocks.map((b) =>
                  b.kind === "movie" ? (
                    <MovieRow key={b.id} item={b.item} ctx={ctx} />
                  ) : (
                    <ShowGroup key={b.id} block={b} ctx={ctx} />
                  ),
                )}
              </div>
            </SortableContext>
          </DndContext>
        )}
      </div>
    </div>
  );
}
