"use client";

import { useMemo, useState } from "react";
import Link from "next/link";
import { SYSTEM_LIST, detectSystemFromFilename, getSystem } from "@/lib/systems";
import type { SystemId } from "@/lib/types";
import { BootTheater } from "@/components/boot/BootTheater";
import { useProfile } from "@/lib/profile/context";
import { hashGameId } from "@/lib/profile/ids";

export function LocalRomPlayer() {
  const [romUrl, setRomUrl] = useState<string | null>(null);
  const [fileName, setFileName] = useState("");
  const [systemId, setSystemId] = useState<SystemId | "">("");
  const [phase, setPhase] = useState<"pick" | "boot" | "play">("pick");
  const [error, setError] = useState("");
  const { profile } = useProfile();

  const system = systemId ? getSystem(systemId) : undefined;

  const iframeSrc = useMemo(() => {
    if (!romUrl || !system) return null;
    const profileId = profile?.id ?? "guest";
    const key = `local:${fileName || "rom"}`;
    const params = new URLSearchParams({
      core: system.core,
      rom: romUrl,
      title: fileName || "Local ROM",
      gameName: `${profileId}:${key}`,
      gameId: String(hashGameId(profileId, key)),
    });
    return `/emulator.html?${params.toString()}`;
  }, [fileName, romUrl, system, profile?.id]);

  function onFile(file: File | undefined) {
    if (!file) return;
    setError("");
    setPhase("pick");
    if (romUrl) URL.revokeObjectURL(romUrl);
    const url = URL.createObjectURL(file);
    setRomUrl(url);
    setFileName(file.name);
    const detected = detectSystemFromFilename(file.name);
    if (detected) setSystemId(detected);
  }

  if (phase === "play" && romUrl && system && iframeSrc) {
    return (
      <div className="fixed inset-0 z-30 bg-black">
        <div className="absolute left-0 right-0 top-0 z-40 flex items-center justify-between gap-3 border-b border-white/10 bg-black/70 px-3 py-2 backdrop-blur">
          <div className="min-w-0">
            <p className="truncate font-display text-[0.55rem] tracking-wider text-accent uppercase">
              {system.shortName} · Local
            </p>
            <h1 className="truncate text-sm text-foreground">{fileName}</h1>
          </div>
          <button
            type="button"
            className="btn-ghost"
            onClick={() => setPhase("pick")}
          >
            Load another
          </button>
        </div>
        <iframe
          title="Local ROM emulator"
          src={iframeSrc}
          className="absolute inset-0 h-full w-full border-0 pt-12"
          allow="gamepad *; autoplay *; fullscreen *"
        />
        <p className="pointer-events-none absolute bottom-3 left-1/2 z-40 w-[min(90%,28rem)] -translate-x-1/2 rounded-sm border border-white/15 bg-black/80 px-3 py-2 text-center text-xs text-foreground/90 backdrop-blur">
          Keyboard / gamepad supported · on phone use EmulatorJS on-screen
          controls (Settings → gamepad)
        </p>
      </div>
    );
  }

  if (phase === "boot" && system) {
    return (
      <BootTheater
        media={system.media}
        label={fileName}
        accent={system.color}
        onDone={() => setPhase("play")}
      />
    );
  }

  return (
    <div className="mx-auto max-w-2xl px-4 py-12 sm:px-6">
      <Link
        href="/"
        className="font-display text-[0.55rem] tracking-[0.2em] text-muted uppercase hover:text-accent"
      >
        ← Back to library
      </Link>
      <h1 className="mt-4 font-display text-2xl tracking-wide text-foreground sm:text-3xl">
        Open a ROM
      </h1>
      <p className="mt-3 text-muted">
        Stays on your computer. If the system isn&apos;t detected, pick it below.
      </p>

      <label
        className="mt-8 flex min-h-48 cursor-pointer flex-col items-center justify-center border border-dashed border-line bg-panel/60 px-6 py-10 text-center transition hover:border-accent"
        onDragOver={(e) => e.preventDefault()}
        onDrop={(e) => {
          e.preventDefault();
          onFile(e.dataTransfer.files?.[0]);
        }}
      >
        <span className="font-display text-[0.65rem] tracking-[0.2em] text-accent uppercase">
          Drop a file here
        </span>
        <span className="mt-2 text-sm text-muted">or click to choose one</span>
        <input
          type="file"
          className="sr-only"
          accept=".nes,.sfc,.smc,.gb,.gbc,.gba,.md,.gen,.bin,.n64,.z64,.v64,.nds,.iso,.cso,.pbp,.sms,.gg,.a26,.vb,.chd,.cue,.zip"
          onChange={(e) => onFile(e.target.files?.[0])}
        />
      </label>

      {fileName && (
        <p className="mt-4 text-sm text-foreground">
          Selected: <span className="text-accent">{fileName}</span>
        </p>
      )}

      <label className="mt-6 block">
        <span className="font-display text-[0.55rem] tracking-wider text-muted uppercase">
          System
        </span>
        <select
          className="mt-2 w-full border border-line bg-elevated px-3 py-3 text-sm text-foreground outline-none focus:border-accent"
          value={systemId}
          onChange={(e) => setSystemId(e.target.value as SystemId | "")}
        >
          <option value="">Select system…</option>
          {SYSTEM_LIST.map((s) => (
            <option key={s.id} value={s.id}>
              {s.name}
            </option>
          ))}
        </select>
      </label>

      {error && <p className="mt-4 text-sm text-accent-hot">{error}</p>}

      <button
        type="button"
        className="btn-primary mt-8 disabled:cursor-not-allowed disabled:opacity-40"
        disabled={!romUrl || !systemId}
        onClick={() => {
          if (!romUrl || !systemId) {
            setError("Choose a ROM file and system first.");
            return;
          }
          setError("");
          setPhase("boot");
        }}
      >
        Play
      </button>
    </div>
  );
}
