"use client";

import { useState, useCallback, useRef } from "react";
import { useAnimation } from "framer-motion";
import { useToast } from "@/hooks/useToast";
import type { MyIdea } from "@/components/BlindboxMyIdeas";
import type { DrawnIdea } from "@/components/BlindboxDrawnHistory";
import type { RoomInfo } from "@/hooks/useBlindboxRoom";
import type { UserProfile } from "@/types";

const IDEA_INSPIRATIONS = [
  "去城市最高楼看日落",
  "挑战一人做一道菜",
  "找一家从没去过的店",
  "逛一个从没去过的街区",
  "去公园野餐",
  "看一场午夜电影",
  "在家做一顿异国料理",
  "骑车去郊外探险",
  "去二手市场淘宝",
  "去博物馆逛半天",
  "试一项没玩过的运动",
  "随机坐公交到终点站",
  "一起画画或做手工",
  "找个天台看星星",
  "去一家评分最低的餐厅",
  "穿最好看的衣服去拍照",
  "交换手机玩一个小时",
  "一起去做志愿者",
];

function pickRandom<T>(arr: T[], n: number): T[] {
  const shuffled = [...arr].sort(() => Math.random() - 0.5);
  return shuffled.slice(0, n);
}

export function useBlindboxIdeas(room: RoomInfo | null, profile: UserProfile | null) {
  const toast = useToast();
  const boxControls = useAnimation();

  const [input, setInput] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [suggestions, setSuggestions] = useState(() => pickRandom(IDEA_INSPIRATIONS, 4));
  const [suggestionsLoading, setSuggestionsLoading] = useState(false);
  const [suggestionsSource, setSuggestionsSource] = useState<"static" | "ai">("static");
  const [poolCount, setPoolCount] = useState(0);
  const [myIdeas, setMyIdeas] = useState<MyIdea[]>([]);
  const [drawnHistory, setDrawnHistory] = useState<DrawnIdea[]>([]);
  const [submitFlash, setSubmitFlash] = useState(false);
  const [error, setError] = useState("");
  const inputRef = useRef<HTMLInputElement>(null);
  const timersRef = useRef<ReturnType<typeof setTimeout>[]>([]);

  const fetchIdeas = useCallback(async () => {
    if (!room || !profile) return;
    try {
      const res = await fetch(`/api/blindbox?roomId=${room.id}&userId=${profile.id}`);
      if (res.ok) {
        const data = await res.json();
        setPoolCount(data.poolCount ?? 0);
        setMyIdeas(data.myIdeas ?? []);
        setDrawnHistory(data.drawn ?? []);
      }
    } catch (e) { console.error("fetchIdeas failed:", e); }
  }, [room, profile]);

  const fetchSuggestions = useCallback(async () => {
    if (!room || !profile) return;
    setSuggestionsLoading(true);
    try {
      const res = await fetch(`/api/blindbox/suggest?roomId=${room.id}&userId=${profile.id}`);
      if (res.ok) {
        const data = await res.json();
        if (data.suggestions?.length > 0) {
          setSuggestions(data.suggestions);
          setSuggestionsSource("ai");
          setSuggestionsLoading(false);
          return;
        }
      }
    } catch (e) { console.error("fetchSuggestions failed:", e); }
    setSuggestions(pickRandom(IDEA_INSPIRATIONS, 4));
    setSuggestionsSource("static");
    setSuggestionsLoading(false);
  }, [room, profile]);

  const refreshSuggestions = useCallback(() => {
    if (suggestionsSource === "ai") {
      fetchSuggestions();
    } else {
      setSuggestions(pickRandom(IDEA_INSPIRATIONS, 4));
    }
  }, [suggestionsSource, fetchSuggestions]);

  const handleSubmit = async () => {
    const text = input.trim();
    if (!text || submitting || !profile || !room) return;
    setSubmitting(true);
    setError("");
    try {
      const res = await fetch("/api/blindbox", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ roomId: room.id, userId: profile.id, content: text }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "提交失败");
      }
      const data = await res.json();
      setInput("");
      setPoolCount((c) => c + 1);
      setMyIdeas((prev) => [{
        id: data.id,
        content: text,
        createdAt: new Date().toISOString(),
        ...data.tags && {
          category: data.tags.category,
          timeSlot: data.tags.timeSlot,
          estimatedMinutes: data.tags.estimatedMinutes,
          costLevel: data.tags.costLevel,
          intensity: data.tags.intensity,
          needsBooking: data.tags.needsBooking,
          searchQuery: data.tags.searchQuery,
          searchType: data.tags.searchType,
        },
      }, ...prev]);
      setSubmitFlash(true);
      timersRef.current.push(setTimeout(() => setSubmitFlash(false), 600));
      boxControls.start({
        scale: [1, 1.08, 1],
        rotate: [0, -3, 3, 0],
        transition: { duration: 0.5 },
      });
      fetchSuggestions();
    } catch (e) {
      setError(e instanceof Error ? e.message : "提交失败");
    } finally {
      setSubmitting(false);
    }
  };

  const handleEditIdea = useCallback(async (ideaId: string, newContent: string) => {
    if (!profile) return;
    const trimmed = newContent.trim();
    if (!trimmed || trimmed.length > 200) return;
    try {
      const res = await fetch("/api/blindbox", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ideaId, userId: profile.id, content: trimmed }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "编辑失败");
      }
      const data = await res.json();
      setMyIdeas((prev) => prev.map((i) => (i.id === ideaId ? {
        ...i,
        content: trimmed,
        ...data.tags && {
          category: data.tags.category,
          timeSlot: data.tags.timeSlot,
          estimatedMinutes: data.tags.estimatedMinutes,
          costLevel: data.tags.costLevel,
          intensity: data.tags.intensity,
          needsBooking: data.tags.needsBooking,
          searchQuery: data.tags.searchQuery,
          searchType: data.tags.searchType,
        },
      } : i)));
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "编辑失败");
    }
  }, [profile, toast]);

  const handleDeleteIdea = useCallback(async (ideaId: string) => {
    if (!profile) return;
    try {
      const res = await fetch("/api/blindbox", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ideaId, userId: profile.id }),
      });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.error || "删除失败");
      }
      setMyIdeas((prev) => prev.filter((i) => i.id !== ideaId));
      setPoolCount((c) => Math.max(0, c - 1));
    } catch (e) {
      toast.show(e instanceof Error ? e.message : "删除失败");
    }
  }, [profile, toast]);

  return {
    input,
    setInput,
    submitting,
    suggestions,
    suggestionsLoading,
    suggestionsSource,
    poolCount,
    setPoolCount,
    myIdeas,
    drawnHistory,
    setDrawnHistory,
    submitFlash,
    error,
    setError,
    inputRef,
    boxControls,
    fetchIdeas,
    fetchSuggestions,
    refreshSuggestions,
    handleSubmit,
    handleEditIdea,
    handleDeleteIdea,
  };
}
