import { useNavigate, useParams } from "react-router-dom";
import { motion } from "motion/react";
import { useState, useEffect, useCallback } from "react";
import challengeIcon from "figma:asset/c11973053d8410ffeb3c76aa4d1da6991076e7e1.png";
import { getTopicConfig } from "../../config/topicConfig";
import { loadMissions, getMissionImageUrl, MissionData, startMission } from "../../services/feedService";
import { usePageTracking } from "../../hooks/usePageTracking";
import { FeedHeader } from "./feed/FeedHeader";
import { BottomNav } from "./BottomNav";
import { AppBackground } from "./shared/AppBackground";
import { useInbox } from "../context/InboxContext";
import { backgroundImages } from "../../config/backgroundConfig";

export function ChallengeSelectionPage() {
  const navigate = useNavigate();
  // Support both /challenges/:topicId and legacy /challenges (defaults to topic 1)
  const { topicId = "1" } = useParams<{ topicId: string }>();

  const topicConfig = getTopicConfig(topicId);

  usePageTracking(`انتخاب چالش ${topicConfig.title}`);
  const { refreshInbox } = useInbox();

  const handleChallengeSelectCallback = useCallback(async (missionId: string) => {
    setStartingMission(true);
    try {
      const response = await startMission(topicConfig.title, missionId);
      
      // ذخیره اطلاعات ماموریت در localStorage برای بازگشت‌های بعدی
      localStorage.setItem('current_mission_type', topicConfig.title);
      localStorage.setItem('current_mission_id', missionId);
      
      // ذخیره workflow_ID از doing_mission
      if (response.doing_mission?.workflow_ID) {
        localStorage.setItem('current_workflow_ID', response.doing_mission.workflow_ID);
      }

      // Refresh inbox to load new messages
      await refreshInbox();

      // Navigate to chatbot page with mission data
      navigate(`/chatbot/${topicId}`, {
        state: {
          chats: response.chats,
          doingMission: response.doing_mission,
          missionType: topicConfig.title,
        },
      });
    } catch (error) {
      console.error("Error starting mission:", error);
      alert("خطا در شروع چالش. لطفاً دوباره تلاش کنید.");
      setAutoNavigating(false);
    } finally {
      setStartingMission(false);
    }
  }, [topicConfig.title, topicId, navigate, refreshInbox]);

  const [missions, setMissions] = useState<MissionData[]>([]);
  const [loading, setLoading] = useState(true);
  const [startingMission, setStartingMission] = useState(false);
  const [autoNavigating, setAutoNavigating] = useState(false);

  const handleBack = useCallback(() => {
    navigate(`/feed/${topicId}`);
  }, [navigate, topicId]);

  useEffect(() => {
    const fetchMissions = async () => {
      setLoading(true);
      const response = await loadMissions(topicConfig.title);
      setMissions(response.missions);
      setLoading(false);

      // برای دفترچه یادداشت (topicId === "3"): به طور خودکار چالش را انتخاب کن
      if (topicId === "3") {
        if (response.missions.length > 0) {
          // اگر چالشی وجود داشت، به طور خودکار آن را انتخاب کن
          setAutoNavigating(true);
          await handleChallengeSelectCallback(response.missions[0].mission_workflowID);
        } else {
          // اگر چالشی وجود نداشت، پیام خطا نمایش بده
          alert("چالشی برای این بخش وجود ندارد");
          // بازگشت به فید
          navigate(`/feed/${topicId}`);
        }
      }
    };

    fetchMissions();
  }, [topicConfig.title, topicId, navigate, handleChallengeSelectCallback]);

  return (
    <div className="fixed inset-0 w-full h-screen overflow-hidden">
      <AppBackground position="fixed" zIndex={0} imageUrl={backgroundImages.challenges} />

      {/* Auto-navigation Loading Overlay - برای دفترچه یادداشت */}
      {autoNavigating && (
        <div
          className="fixed inset-0 z-[100] flex items-center justify-center backdrop-blur-sm"
          style={{
            background:
              "radial-gradient(120% 120% at 50% 0%, rgba(124, 58, 237, 0.36) 0%, rgba(46, 27, 61, 0.9) 55%, rgba(35, 24, 62, 0.96) 100%)",
          }}
        >
          <div className="text-center">
            <div className="inline-block w-12 h-12 border-4 border-[#ffd6f0]/30 border-t-[#ff79cf] rounded-full animate-spin mb-3" />
            <p className="text-white text-base font-bold">در حال بارگذاری چالش...</p>
          </div>
        </div>
      )}

      {/* Content */}
      <div className="relative z-10 max-w-md mx-auto h-full flex flex-col">
        {/* Header */}
        <FeedHeader topicTitle={topicConfig.title} subtitle="انتخاب چالش" onBack={handleBack} />

        {/* Main Content - Scrollable */}
        <div
          className="flex-1 overflow-y-auto px-4 pb-20"
          style={{
            maskImage: "linear-gradient(to bottom, transparent 0%, black 48px)",
            WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 48px)",
            scrollbarWidth: "none",
            msOverflowStyle: "none",
          }}
        >
          <div className="pt-8">
           

            {/* Challenges List */}
            <div className="w-full space-y-4" dir="rtl">
              {loading ? (
                /* Loading State */
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  className="text-center py-10"
                >
                  <div className="inline-block w-10 h-10 border-4 border-[#ffd6f0]/30 border-t-[#ff79cf] rounded-full animate-spin mb-3" />
                  <p className="text-[#ffd6f0] text-xs">در حال بارگذاری چالش‌ها...</p>
                </motion.div>
              ) : missions.length === 0 ? (
                /* Empty State */
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  className="text-center py-10"
                >
                  <p className="text-teal-200 text-xs">هیچ چالشی یافت نشد</p>
                </motion.div>
              ) : (
                /* Missions from Server */
                missions.map((mission, index) => (
                  <motion.div
                    key={mission.mission_workflowID}
                    initial={{ x: -80, opacity: 0 }}
                    animate={{ x: 0, opacity: 1 }}
                    transition={{ delay: 0.3 + index * 0.1, duration: 0.4 }}
                    className="relative"
                  >
                    <div className="bg-gradient-to-br from-teal-700/60 to-teal-900/70 backdrop-blur-md rounded-2xl p-4 border border-teal-500/30 shadow-xl shadow-teal-500/20 flex items-center gap-3 hover:scale-[1.01] transition-transform">
                      {/* Challenge Icon */}
                      <div className="flex-shrink-0 w-16 h-16 relative">
                        <div className="absolute inset-0 rounded-full bg-gradient-to-br from-purple-500/30 to-blue-500/30 blur-lg animate-pulse" />
                        <img
                          src={getMissionImageUrl(mission.StageID)}
                          alt={mission.title}
                          className="w-full h-full object-cover rounded-full relative z-10 drop-shadow-xl"
                          loading="eager"
                          onError={(e) => {
                            // Fallback به آیکون پیش‌فرض در صورت خطا
                            e.currentTarget.src = challengeIcon;
                            e.currentTarget.style.objectFit = "contain";
                          }}
                        />
                      </div>

                      {/* Content */}
                      <div className="flex-1 text-right">
                        <h3 className="text-white font-bold text-base mb-1">
                          {mission.title}
                        </h3>
                        <p className="text-teal-100 text-xs leading-relaxed mb-2 opacity-90">
                          {mission.description}
                        </p>

                        {/* Start Button */}
                        <motion.button
                          whileHover={{ scale: 1.03 }}
                          whileTap={{ scale: 0.97 }}
                          onClick={() => handleChallengeSelectCallback(mission.mission_workflowID)}
                          className="bg-gradient-to-r from-yellow-400 via-yellow-500 to-yellow-400 text-gray-900 font-bold text-sm rounded-full px-6 py-1.5 shadow-lg shadow-yellow-500/50 border-2 border-yellow-300/50"
                        >
                          شروع
                        </motion.button>
                      </div>
                    </div>
                  </motion.div>
                ))
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Bottom Navigation */}
      <BottomNav />

      <style>{`
        .flex-1.overflow-y-auto::-webkit-scrollbar {
          display: none;
        }
      `}</style>
    </div>
  );
}
