"use client";

import { useState, useEffect, useRef } from "react";
import { useParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowLeft,
  Loader2,
  Package,
  Share2,
  LogIn,
  Copy,
  Trash2,
  LogOut,
  MapPin,
  Sparkles,
  ClipboardCheck,
  ChevronRight,
} from "lucide-react";
import ShareCardModal from "@/components/ShareCardModal";
import Button from "@/components/Button";
import BlindboxMyIdeas from "@/components/BlindboxMyIdeas";
import BlindboxDrawnHistory from "@/components/BlindboxDrawnHistory";
import WeekendTimeSelector from "@/components/WeekendTimeSelector";
import BlindboxPlan from "@/components/BlindboxPlan";
import BlindboxPoolPhase from "@/components/BlindboxPoolPhase";
import BlindboxRevealPhase from "@/components/BlindboxRevealPhase";
import ContractCompletionModal from "@/components/ContractCompletionModal";
import { useToast } from "@/hooks/useToast";
import { BlindboxRoomSkeleton } from "@/components/Skeleton";
import { useBlindboxRoom } from "@/hooks/useBlindboxRoom";
import { useBlindboxIdeas } from "@/hooks/useBlindboxIdeas";
import { useBlindboxPlan } from "@/hooks/useBlindboxPlan";
import { useBlindboxDraw } from "@/hooks/useBlindboxDraw";

type Phase = "pool" | "shaking" | "reveal" | "time_select" | "planning" | "plan_reveal";

export default function BlindboxRoomPage() {
  const { code } = useParams<{ code: string }>();
  const toast = useToast();
  const [phase, setPhase] = useState<Phase>("pool");
  const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);

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

  // Hook: Room
  const {
    profile, room, isMember, joiningRoom, pageLoading, locating,
    confirmLeave, leaving, showInvite, setShowInvite, isCreator,
    handleJoinRoom, handleSetLocation, handleLeaveOrDelete,
    handleCopyCode, handleShareRoom, handleBackToLobby,
  } = useBlindboxRoom(code);

  // Hook: Ideas
  const {
    input, setInput, submitting, suggestions, suggestionsLoading,
    suggestionsSource, poolCount, setPoolCount, myIdeas, drawnHistory,
    setDrawnHistory, submitFlash, error, setError, inputRef,
    boxControls: ideaBoxControls,
    fetchIdeas, fetchSuggestions, refreshSuggestions,
    handleSubmit, handleEditIdea, handleDeleteIdea,
  } = useBlindboxIdeas(room, profile);

  // Hook: Draw (needs fireConfetti for plan too)
  const {
    revealedIdea, showShareCard, setShowShareCard,
    boxControls: drawBoxControls,
    fireConfetti, handleDraw, handleContinue,
  } = useBlindboxDraw(room, profile, poolCount, setPoolCount, setDrawnHistory, setError, setPhase);

  // Hook: Plan
  const {
    planDays, planAccepted, generating, planStatusMessages,
    showPlanShareCard, setShowPlanShareCard, activeContract,
    pendingContracts, planLogRef,
    fetchAcceptedPlan, handleGeneratePlan, handlePlanDaysChange,
    handleRefine, handleAcceptPlan, handleRegenerate,
    showActiveContract, clearPendingContracts,
  } = useBlindboxPlan(room, profile, phase, setPhase, fireConfetti);

  // Fetch data when member joins — run once when isMember+room are ready
  const dataFetchedRef = useRef(false);
  useEffect(() => {
    if (isMember && room && !dataFetchedRef.current) {
      dataFetchedRef.current = true;
      fetchIdeas();
      fetchAcceptedPlan();
      fetchSuggestions();
    }
  }, [isMember, room, fetchIdeas, fetchAcceptedPlan, fetchSuggestions]);

  // Focus input when member
  useEffect(() => {
    if (isMember && inputRef.current) {
      const t = setTimeout(() => inputRef.current?.focus(), 300);
      timersRef.current.push(t);
    }
  }, [isMember, inputRef]);

  if (pageLoading) return <BlindboxRoomSkeleton />;
  if (!room) return null;

  return (
    <div className={`relative flex h-dvh flex-col items-center bg-background px-5 py-6 scrollbar-none ${
      phase === "plan_reveal" ? "overflow-hidden" : "overflow-y-auto"
    }`}>

      {/* Header */}
      <div className="flex w-full max-w-sm items-center gap-3">
        <button
          onClick={handleBackToLobby}
          aria-label="返回"
          className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-surface ring-1 ring-border transition-colors active:bg-elevated"
        >
          <ArrowLeft size={16} className="text-muted" />
        </button>
        <div className="min-w-0 flex-1">
          <p className="truncate text-sm font-bold text-heading">{room.name}</p>
          <div className="mt-0.5 flex items-center gap-2">
            <p className="text-[10px] text-dim">房间 {room.code}</p>
            <button
              onClick={handleSetLocation}
              disabled={locating}
              className="flex items-center gap-0.5 text-[10px] font-medium text-purple-400/70 transition-colors active:text-purple-400"
            >
              {locating ? <Loader2 size={9} className="animate-spin" /> : <MapPin size={9} />}
              {room.city || "设置位置"}
            </button>
          </div>
        </div>

        <div className="flex -space-x-1.5">
          {room.members.slice(0, 4).map((m) => (
            <div
              key={m.id}
              className="flex h-7 w-7 items-center justify-center rounded-full bg-elevated text-xs ring-2 ring-background"
              title={m.username}
            >
              {m.avatar}
            </div>
          ))}
          {room.members.length > 4 && (
            <div className="flex h-7 w-7 items-center justify-center rounded-full bg-elevated text-[10px] font-bold text-muted ring-2 ring-background">
              +{room.members.length - 4}
            </div>
          )}
        </div>

        <button
          onClick={() => setShowInvite(!showInvite)}
          aria-label="邀请成员"
          className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-purple-600/15 text-purple-400 ring-1 ring-purple-500/20 transition-colors active:bg-purple-600/25"
        >
          <Share2 size={14} />
        </button>
      </div>

      {/* Active contract indicator */}
      {activeContract && phase !== "plan_reveal" && (
        <motion.button
          className="mt-3 flex w-full max-w-sm items-center gap-2 rounded-xl bg-purple-600/10 px-3 py-2 ring-1 ring-purple-500/20 transition-colors active:bg-purple-600/20"
          initial={{ opacity: 0, y: -8 }}
          animate={{ opacity: 1, y: 0 }}
          onClick={showActiveContract}
        >
          <ClipboardCheck size={14} className="shrink-0 text-purple-400" />
          <span className="text-xs font-medium text-purple-300">契约进行中</span>
          <span className="text-[10px] text-purple-400/50">
            {activeContract.days.map((d) => d.date).join(" + ")}
          </span>
          <ChevronRight size={12} className="ml-auto text-purple-400/40" />
        </motion.button>
      )}

      {/* Invite panel */}
      <AnimatePresence>
        {showInvite && (
          <motion.div
            className="mt-3 w-full max-w-sm overflow-hidden rounded-xl bg-surface ring-1 ring-border"
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
          >
            <div className="flex items-center gap-3 p-3">
              <span className="text-xs text-muted">房间号</span>
              <span className="font-mono text-base font-bold tracking-[0.2em] text-purple-400">
                {room.code}
              </span>
              <div className="flex-1" />
              <button
                onClick={handleCopyCode}
                className="flex h-8 items-center gap-1 rounded-lg bg-elevated px-3 text-xs font-medium text-secondary ring-1 ring-border transition-colors active:bg-subtle"
              >
                <Copy size={12} /> 复制
              </button>
              <button
                onClick={handleShareRoom}
                className="flex h-8 items-center gap-1 rounded-lg bg-purple-600 px-3 text-xs font-medium text-white transition-colors active:bg-purple-500"
              >
                <Share2 size={12} /> 分享
              </button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Non-member state */}
      {!isMember ? (
        <motion.div
          className="mt-16 flex flex-col items-center gap-4"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
        >
          <Package size={40} className="text-purple-400/50" strokeWidth={1.5} />
          <p className="text-sm text-tertiary">你还不是这个房间的成员</p>
          <Button
            onClick={handleJoinRoom}
            variant="purple"
            size="lg"
            loading={joiningRoom}
            icon={<LogIn size={16} />}
          >
            加入房间
          </Button>
        </motion.div>
      ) : (
        <>
          {/* Blind Box Visual */}
          {phase !== "planning" && phase !== "plan_reveal" && (
            <div className="mt-8 flex flex-col items-center">
              <motion.div
                animate={drawBoxControls}
                className="relative flex h-36 w-36 items-center justify-center"
              >
                <div className="absolute inset-0 rounded-3xl bg-linear-to-br from-purple-600/20 to-indigo-600/20 blur-xl" />
                <div className="relative flex h-32 w-32 flex-col items-center justify-center rounded-2xl bg-linear-to-br from-indigo-900 to-purple-900 shadow-2xl shadow-purple-900/50 ring-1 ring-purple-700/30">
                  <div className="absolute -top-2 left-1/2 h-5 w-[90%] -translate-x-1/2 rounded-t-xl bg-linear-to-r from-purple-700 to-indigo-700 shadow-md" />
                  <div className="absolute top-3 h-full w-3 bg-linear-to-b from-amber-400/60 to-amber-400/10" />
                  <div className="absolute top-6 h-3 w-full bg-linear-to-r from-amber-400/0 via-amber-400/60 to-amber-400/0" />
                  <motion.div
                    animate={submitFlash ? { scale: [1, 1.3, 1] } : {}}
                    transition={{ duration: 0.3 }}
                  >
                    <Package size={40} className="relative z-10 text-purple-300/60" strokeWidth={1.5} />
                  </motion.div>
                  <motion.div
                    className="absolute -right-2 -top-2 text-lg"
                    animate={{ rotate: [0, 15, -15, 0], scale: [1, 1.2, 1] }}
                    transition={{ duration: 2, repeat: Infinity, repeatDelay: 3 }}
                  >
                    ✨
                  </motion.div>
                </div>
              </motion.div>

              <motion.p
                className="mt-4 text-sm font-semibold text-muted"
                key={poolCount}
                initial={{ scale: 1.2, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
              >
                盒子里已有{" "}
                <span className="text-lg font-black text-purple-400">{poolCount}</span>{" "}
                个想法
              </motion.p>
            </div>
          )}

          {/* Phase content */}
          <AnimatePresence mode="wait">
            {phase === "pool" && (
              <BlindboxPoolPhase
                input={input}
                setInput={setInput}
                submitting={submitting}
                suggestions={suggestions}
                suggestionsLoading={suggestionsLoading}
                suggestionsSource={suggestionsSource}
                poolCount={poolCount}
                error={error}
                setError={setError}
                inputRef={inputRef}
                planDays={planDays}
                planAccepted={planAccepted}
                hasLocation={!!room.city}
                onSubmit={handleSubmit}
                onDraw={handleDraw}
                onPlanStart={() => setPhase("time_select")}
                onRefreshSuggestions={refreshSuggestions}
                onShowPlan={() => setPhase("plan_reveal")}
                onLocationMissing={() => toast.show("请先点击房间名下方设置位置")}
              />
            )}

            {phase === "shaking" && (
              <motion.div
                key="shaking"
                className="mt-8 flex flex-col items-center gap-4"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
              >
                <p className="text-sm font-bold text-purple-300 animate-pulse">
                  命运正在决定...
                </p>
                <div className="flex gap-1">
                  {[0, 1, 2].map((i) => (
                    <motion.div
                      key={i}
                      className="h-2 w-2 rounded-full bg-purple-400"
                      animate={{ y: [0, -8, 0] }}
                      transition={{ duration: 0.6, repeat: Infinity, delay: i * 0.15 }}
                    />
                  ))}
                </div>
              </motion.div>
            )}

            {phase === "reveal" && revealedIdea && (
              <BlindboxRevealPhase
                idea={revealedIdea}
                onShare={() => setShowShareCard(true)}
                onContinue={handleContinue}
              />
            )}

            {phase === "planning" && (
              <motion.div
                key="planning"
                className="mt-8 flex flex-col items-center gap-4 w-full px-4"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
              >
                <motion.div
                  className="relative flex h-16 w-16 items-center justify-center"
                  animate={{ rotate: [0, 360] }}
                  transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
                >
                  <div className="absolute inset-0 rounded-full bg-purple-600/15 blur-lg" />
                  <Sparkles size={24} className="relative text-purple-400" />
                </motion.div>
                <div className="w-full max-w-sm rounded-xl bg-surface/60 ring-1 ring-border/60 overflow-hidden">
                  <div
                    ref={planLogRef}
                    className="h-40 overflow-y-auto scrollbar-none p-3 flex flex-col gap-1.5"
                  >
                    {planStatusMessages.map((msg, i) => (
                      <motion.div
                        key={i}
                        initial={{ opacity: 0, y: 6 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.2 }}
                        className={`flex items-center gap-2 text-xs ${i === planStatusMessages.length - 1 ? "text-purple-300 font-medium" : "text-dim"}`}
                      >
                        {i === planStatusMessages.length - 1 ? (
                          <Loader2 size={11} className="shrink-0 animate-spin text-purple-400" />
                        ) : (
                          <span className="shrink-0 text-[10px] text-purple-500">✓</span>
                        )}
                        {msg}
                      </motion.div>
                    ))}
                  </div>
                </div>
              </motion.div>
            )}

            {phase === "plan_reveal" && planDays.length > 0 && (
              <motion.div
                key="plan_reveal"
                className="mt-4 flex min-h-0 flex-1 w-full"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
              >
                <BlindboxPlan
                  days={planDays}
                  accepted={planAccepted}
                  regenerating={generating}
                  onDaysChange={handlePlanDaysChange}
                  onRefine={handleRefine}
                  location={room.lng != null && room.lat != null ? `${room.lng},${room.lat}` : undefined}
                  startLocationLabel={room.address ?? room.city ?? undefined}
                  onAccept={async () => {
                    await handleAcceptPlan();
                    timersRef.current.push(setTimeout(() => {
                      setPhase("pool");
                    }, 1500));
                  }}
                  onRegenerate={handleRegenerate}
                  onShare={() => setShowPlanShareCard(true)}
                  onBack={() => setPhase("pool")}
                />
              </motion.div>
            )}
          </AnimatePresence>

          {/* Time selector modal */}
          <AnimatePresence>
            {phase === "time_select" && (
              <WeekendTimeSelector
                onConfirm={handleGeneratePlan}
                onClose={() => setPhase("pool")}
                loading={generating}
              />
            )}
          </AnimatePresence>

          {myIdeas.length > 0 && phase === "pool" && (
            <BlindboxMyIdeas
              ideas={myIdeas}
              onEdit={handleEditIdea}
              onDelete={handleDeleteIdea}
            />
          )}

          {phase !== "shaking" && phase !== "planning" && (
            <BlindboxDrawnHistory items={drawnHistory} />
          )}
        </>
      )}

      {revealedIdea && room && (
        <ShareCardModal
          open={showShareCard}
          onClose={() => setShowShareCard(false)}
          data={{
            type: "blindbox",
            idea: revealedIdea.content,
            submitter: revealedIdea.user ?? undefined,
            drawer: revealedIdea.drawnBy ?? undefined,
            roomName: room.name,
          }}
        />
      )}

      {planDays.length > 0 && room && (
        <ShareCardModal
          open={showPlanShareCard}
          onClose={() => setShowPlanShareCard(false)}
          data={{
            type: "plan",
            days: planDays,
            roomName: room.name,
          }}
        />
      )}

      {/* Leave / Back */}
      {isMember && room && phase !== "plan_reveal" && phase !== "planning" && (
        <motion.div
          className="mt-12 flex w-full max-w-sm flex-col items-center gap-2"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5 }}
        >
          {isCreator ? (
            <>
              <button
                onClick={handleBackToLobby}
                className="flex w-full items-center justify-center gap-2 rounded-xl py-2.5 text-xs font-medium text-muted transition-colors hover:text-foreground active:bg-elevated"
              >
                <ArrowLeft size={13} />
                返回大厅
              </button>
              <button
                onClick={handleLeaveOrDelete}
                disabled={leaving}
                className={`flex w-full items-center justify-center gap-2 rounded-xl py-2 text-xs font-medium transition-colors ${
                  confirmLeave
                    ? "bg-rose-600/15 text-rose-400 ring-1 ring-rose-500/30"
                    : "text-dim hover:text-rose-400/80"
                }`}
              >
                {leaving ? <Loader2 size={12} className="animate-spin" /> : <Trash2 size={12} />}
                {confirmLeave ? "确认删除房间？所有想法将被清除" : "删除房间"}
              </button>
            </>
          ) : (
            <button
              onClick={handleLeaveOrDelete}
              disabled={leaving}
              className={`flex w-full items-center justify-center gap-2 rounded-xl py-2.5 text-xs font-medium transition-colors ${
                confirmLeave
                  ? "bg-rose-600/15 text-rose-400 ring-1 ring-rose-500/30"
                  : "text-muted hover:text-rose-400/80"
              }`}
            >
              {leaving ? <Loader2 size={13} className="animate-spin" /> : <LogOut size={13} />}
              {confirmLeave ? "确认退出房间？" : "退出房间"}
            </button>
          )}
        </motion.div>
      )}

      <div className="h-8 shrink-0" />

      {/* Contract expiration check modal */}
      {pendingContracts.length > 0 && profile && (
        <ContractCompletionModal
          contracts={pendingContracts}
          userId={profile.id}
          onDone={clearPendingContracts}
        />
      )}
    </div>
  );
}
