"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { useParams, useRouter } from "next/navigation";
import TopNav from "@/components/TopNav";
import SwipeDeck from "@/components/SwipeDeck";
import { SwipeDeckSkeleton } from "@/components/Skeleton";
import LeaveConfirmModal from "@/components/LeaveConfirmModal";
import Button from "@/components/Button";
import { useRoomPolling } from "@/hooks/useRoomPolling";
import { getUserId } from "@/lib/userId";
import { joinRoom } from "@/lib/room";
import { getSceneConfig } from "@/lib/sceneConfig";
import { useToast } from "@/hooks/useToast";

export default function RoomPage() {
  const params = useParams<{ id: string }>();
  const router = useRouter();
  const roomId = params.id;

  const [userId, setUserId] = useState("");
  const [joined, setJoined] = useState(false);
  const [joinFailed, setJoinFailed] = useState(false);
  const [showLeaveConfirm, setShowLeaveConfirm] = useState(false);
  const leavingRef = useRef(false);
  const toast = useToast();

  const {
    userCount, match, matchType, matchLikes, runnerUps, likeCounts, swipeCounts,
    restaurants, notFound, mutate, creatorId, locked, users, userProfiles, scene,
  } = useRoomPolling(roomId);

  useEffect(() => {
    if (!roomId) return;
    const id = getUserId();
    setUserId(id);

    joinRoom(roomId, id)
      .then(() => setJoined(true))
      .catch(() => setJoinFailed(true));
  }, [roomId]);

  useEffect(() => {
    window.history.pushState({ roomGuard: true }, "");

    const handlePopState = () => {
      if (leavingRef.current) return;
      window.history.pushState({ roomGuard: true }, "");
      setShowLeaveConfirm(true);
    };

    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (leavingRef.current) return;
      e.preventDefault();
    };

    window.addEventListener("popstate", handlePopState);
    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => {
      window.removeEventListener("popstate", handlePopState);
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, []);

  const confirmLeave = useCallback(() => {
    leavingRef.current = true;
    setShowLeaveConfirm(false);
    router.push("/");
  }, [router]);

  const cancelLeave = useCallback(() => {
    setShowLeaveConfirm(false);
  }, []);

  const handleExitRequest = useCallback(() => {
    setShowLeaveConfirm(true);
  }, []);

  const handleReset = useCallback(async () => {
    try {
      const res = await fetch(`/api/room/${roomId}/reset`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "重置失败");
      }
      await mutate();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "重置失败");
    }
  }, [roomId, userId, mutate, toast]);

  const handleNarrow = useCallback(async (restaurantIds: string[]) => {
    try {
      const res = await fetch(`/api/room/${roomId}/reset`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ userId, restaurantIds }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error || "缩小范围失败");
      }
      await mutate();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "操作失败");
    }
  }, [roomId, userId, mutate, toast]);

  if (notFound || joinFailed) {
    return (
      <div className="flex h-dvh flex-col items-center justify-center gap-4 bg-background px-6">
        <p className="text-4xl">🍜</p>
        <p className="text-base font-semibold text-secondary">房间不存在或已过期</p>
        <p className="text-sm text-muted">房间号可能有误，或房间已超过 24 小时</p>
        <Button onClick={() => router.push("/")}>
          返回首页
        </Button>
      </div>
    );
  }

  const initialIndex = swipeCounts[userId] ?? 0;
  const ready = joined && userId && restaurants.length > 0;

  const sceneConfig = getSceneConfig(scene);

  if (!ready) {
    return <SwipeDeckSkeleton />;
  }

  return (
    <div className="flex h-dvh flex-col bg-background">
      <TopNav
        roomId={roomId}
        userCount={userCount}
        onExit={handleExitRequest}
        isCreator={userId === creatorId}
        userId={userId}
        users={users}
        locked={locked}
        swipeCounts={swipeCounts}
        totalCards={restaurants.length}
        userProfiles={userProfiles}
        scene={scene}
      />
      <SwipeDeck
        restaurants={restaurants}
        roomId={roomId}
        userId={userId}
        initialIndex={initialIndex}
        matchedRestaurantId={match}
        matchType={matchType}
        matchLikes={matchLikes}
        runnerUps={runnerUps}
        likeCounts={likeCounts}
        swipeCounts={swipeCounts}
        userCount={userCount}
        userProfiles={userProfiles}
        onReset={handleReset}
        onNarrow={handleNarrow}
        scene={scene}
      />
      <LeaveConfirmModal
        open={showLeaveConfirm}
        onConfirm={confirmLeave}
        onCancel={cancelLeave}
      />
    </div>
  );
}
