"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { getCachedProfile, isRegistered } from "@/lib/userId";
import { requestJson } from "@/lib/fetcher";
import { useToast } from "@/hooks/useToast";
import { useShare } from "@/hooks/useShare";
import type { UserProfile } from "@/types";

export interface RoomInfo {
  id: string;
  code: string;
  name: string;
  creatorId: string;
  city: string | null;
  address: string | null;
  lat: number | null;
  lng: number | null;
  poolCount: number;
  members: { id: string; username: string; avatar: string }[];
}

export function useBlindboxRoom(code: string) {
  const router = useRouter();
  const toast = useToast();
  const { share, copyToClipboard } = useShare();

  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [room, setRoom] = useState<RoomInfo | null>(null);
  const [isMember, setIsMember] = useState(false);
  const [joiningRoom, setJoiningRoom] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const [locating, setLocating] = useState(false);
  const [confirmLeave, setConfirmLeave] = useState(false);
  const [leaving, setLeaving] = useState(false);
  const [showInvite, setShowInvite] = useState(false);
  const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);

  useEffect(() => {
    const timers = timersRef.current;
    return () => {
      timers.forEach(clearTimeout);
      timers.length = 0;
    };
  }, []);

  useEffect(() => {
    if (!isRegistered()) {
      router.replace("/blindbox");
      return;
    }
    setProfile(getCachedProfile());
  }, [router]);

  const fetchRoom = useCallback(async () => {
    if (!code) return;
    try {
      const data = await requestJson<RoomInfo>(`/api/blindbox/room/${code}`);
      setRoom(data);
      const p = getCachedProfile();
      setIsMember(data.members.some((m) => m.id === p?.id));
    } catch {
      router.replace("/blindbox");
    } finally {
      setPageLoading(false);
    }
  }, [code, router]);

  useEffect(() => { fetchRoom(); }, [fetchRoom]);

  const handleJoinRoom = async () => {
    if (joiningRoom || !profile || !room) return;
    setJoiningRoom(true);
    try {
      await requestJson<{ id: string; code: string; name: string }>("/api/blindbox/room/join", {
        method: "POST",
        body: { code },
      });
      setIsMember(true);
      fetchRoom();
    } catch (e) { console.error("handleJoinRoom failed:", e); }
    finally { setJoiningRoom(false); }
  };

  const handleSetLocation = useCallback(async () => {
    if (locating || !profile || !room) return;
    setLocating(true);
    try {
      const pos = await new Promise<GeolocationPosition>((resolve, reject) =>
        navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: 10000 }),
      );
      const { latitude: lat, longitude: lng } = pos.coords;
      const regeo = await requestJson<{ name?: string; formatted?: string }>(
        `/api/location/regeo?lat=${lat}&lng=${lng}`,
      );
      const cityName = regeo.name || "未知位置";
      const addressLabel = regeo.formatted || cityName;
      await requestJson(`/api/blindbox/room/${room.code}`, {
        method: "PATCH",
        body: { city: cityName, address: addressLabel, lat, lng },
      });
      setRoom((prev) => prev ? { ...prev, city: cityName, address: addressLabel, lat, lng } : prev);
      toast.show("位置已设置");
    } catch {
      toast.show("获取位置失败，请允许定位权限");
    } finally {
      setLocating(false);
    }
  }, [locating, profile, room, toast]);

  const handleLeaveOrDelete = async () => {
    if (!confirmLeave) {
      setConfirmLeave(true);
      timersRef.current.push(setTimeout(() => setConfirmLeave(false), 3000));
      return;
    }
    if (leaving || !profile || !room) return;
    setLeaving(true);
    try {
      await requestJson<{ action: "deleted" | "left" }>(`/api/blindbox/room/${room.code}`, {
        method: "DELETE",
      });
      router.push("/blindbox");
      router.refresh();
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "操作失败");
      setConfirmLeave(false);
    } finally {
      setLeaving(false);
    }
  };

  const handleCopyCode = useCallback(
    () => room ? copyToClipboard(room.code, "房间号已复制") : undefined,
    [room, copyToClipboard],
  );

  const handleShareRoom = useCallback(() => {
    if (!room) return;
    const url = typeof window !== "undefined" ? `${window.location.origin}/blindbox/${room.code}` : "";
    share(
      { title: `周末契约 · ${room.name}`, text: `来和我一起玩周末盲盒吧！房间号：${room.code}`, url },
      handleCopyCode,
    );
  }, [room, share, handleCopyCode]);

  const handleBackToLobby = useCallback(() => {
    router.push("/blindbox");
    router.refresh();
  }, [router]);

  const isCreator = profile?.id === room?.creatorId;

  return {
    profile,
    room,
    isMember,
    joiningRoom,
    pageLoading,
    locating,
    confirmLeave,
    leaving,
    showInvite,
    setShowInvite,
    isCreator,
    handleJoinRoom,
    handleSetLocation,
    handleLeaveOrDelete,
    handleCopyCode,
    handleShareRoom,
    handleBackToLobby,
    fetchRoom,
  };
}
