import { useState, useEffect } from "react";
import { motion, AnimatePresence } from "motion/react";
import { ShoppingBag, Package, Lock, X, Download } from "lucide-react";
import coinImage from "../../assets/coin-star.png";
import itemImage from "figma:asset/0469c3ac6223dede16e9f8943a3cac9943835707.png";
import {
  loadMagicBagMissions,
  getMagicBagFileUrl,
  isImageFile,
  type MagicBagMissionItem
} from "../../services/feedService";
import { usePageTracking } from "../../hooks/usePageTracking";

interface Item {
  id: string;
  name: string;
  price?: number;
  isOwned: boolean;
  isLocked?: boolean;
}

const shopItems: Item[] = [
  {
    id: "1",
    name: "نشان ستاره طلایی",
    price: 150,
    isOwned: false,
  },
  {
    id: "2",
    name: "آواتار جادوگر",
    price: 250,
    isOwned: false,
  },
  {
    id: "3",
    name: "قاب طلایی",
    price: 100,
    isOwned: false,
  },
  {
    id: "4",
    name: "پس‌زمینه کهکشانی",
    price: 200,
    isOwned: false,
  },
  {
    id: "5",
    name: "نشان شیر",
    price: 80,
    isOwned: false,
  },
  {
    id: "6",
    name: "افکت درخشش",
    price: 300,
    isOwned: false,
    isLocked: true,
  },
  {
    id: "7",
    name: "تاج طلایی",
    price: 180,
    isOwned: false,
  },
  {
    id: "8",
    name: "جام قهرمانی",
    price: 220,
    isOwned: false,
  },
];

const ownedItems: Item[] = [
  {
    id: "o1",
    name: "نشان چالشگر برتر",
    isOwned: true,
  },
  {
    id: "o2",
    name: "تاج موفقیت",
    isOwned: true,
  },
  {
    id: "o3",
    name: "نشان آغازگر",
    isOwned: true,
  },
];

const purchasedItems: Item[] = [
  {
    id: "p1",
    name: "نشان ستاره طلایی",
    isOwned: true,
  },
  {
    id: "p2",
    name: "قاب طلایی",
    isOwned: true,
  },
];

export function MagicBagPage() {
  usePageTracking("کیف جادویی");

  const [activeTab, setActiveTab] = useState<"shop" | "owned">("owned");
  const [missionItems, setMissionItems] = useState<MagicBagMissionItem[]>([]);
  const [loadingMissions, setLoadingMissions] = useState(false);
  const [selectedImage, setSelectedImage] = useState<{ url: string; title: string } | null>(null);
  const userCoins = 1000;

  useEffect(() => {
    // فقط زمانی که تب "ایتم‌های من" فعال است، داده‌ها را بارگذاری کن
    if (activeTab === "owned" && missionItems.length === 0) {
      const fetchMissionItems = async () => {
        setLoadingMissions(true);
        const result = await loadMagicBagMissions();
        
        if (result.success) {
          setMissionItems(result.data);
        } else {
          console.error("Error loading magic bag missions:", result.message);
        }
        
        setLoadingMissions(false);
      };

      fetchMissionItems();
    }
  }, [activeTab, missionItems.length]);

  return (
    <div className="pt-6 pb-2" dir="rtl">
      {/* Tab Switcher */}
      <div
        className="mb-4 flex rounded-2xl p-1"
        style={{
          backgroundImage:
            "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.94) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
          backgroundOrigin: "border-box",
          backgroundClip: "padding-box, border-box",
          border: "0.5px solid transparent",
        }}
      >
        <motion.button
          whileTap={{ scale: 0.97 }}
          onClick={() => setActiveTab("owned")}
          className="flex-1 flex items-center justify-center gap-1.5 rounded-xl py-2.5 text-sm font-bold transition-all duration-300"
          style={{
            background: activeTab === "owned"
              ? "linear-gradient(135deg, rgba(174, 117, 255, 0.96) 0%, rgba(138, 82, 238, 0.95) 46%, rgba(102, 55, 204, 0.94) 100%)"
              : "transparent",
            boxShadow: activeTab === "owned"
              ? "0 0 18px rgba(155,108,241,0.4)"
              : "none",
            color: activeTab === "owned" ? "#FFFFFF" : "rgba(251,231,245,0.72)",
          }}
        >
          <Package className="w-4 h-4" />
          ایتم‌های من
        </motion.button>

        <motion.button
          whileTap={{ scale: 0.97 }}
          onClick={() => setActiveTab("shop")}
          className="flex-1 flex items-center justify-center gap-1.5 rounded-xl py-2.5 text-sm font-bold transition-all duration-300"
          style={{
            background: activeTab === "shop"
              ? "linear-gradient(135deg, rgba(174, 117, 255, 0.96) 0%, rgba(138, 82, 238, 0.95) 46%, rgba(102, 55, 204, 0.94) 100%)"
              : "transparent",
            boxShadow: activeTab === "shop"
              ? "0 0 18px rgba(155,108,241,0.4)"
              : "none",
            color: activeTab === "shop" ? "#FFFFFF" : "rgba(251,231,245,0.72)",
          }}
        >
          <ShoppingBag className="w-4 h-4" />
          فروشگاه
        </motion.button>
      </div>

      {/* Shop Tab */}
      {activeTab === "shop" && (
        <div className="grid grid-cols-4 gap-4">
          {shopItems.map((item, index) => {
            const canAfford = !item.isLocked && item.price && userCoins >= item.price;
            
            return (
              <motion.button
                key={item.id}
                initial={{ opacity: 0, scale: 0.8 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: index * 0.05, duration: 0.3 }}
                whileHover={{ scale: item.isLocked ? 1 : 1.1, y: -4 }}
                whileTap={{ scale: item.isLocked ? 1 : 0.9 }}
                disabled={item.isLocked}
                className="flex flex-col items-center gap-1.5"
              >
                {/* Item Image with Price Badge */}
                <div className="relative w-full">
                  <img
                    src={itemImage}
                    alt={item.name}
                    className="w-full h-auto object-contain"
                    style={{
                      filter: item.isLocked 
                        ? "grayscale(100%) brightness(0.4)" 
                        : "drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3))",
                    }}
                  />
                  
                  {/* Lock Icon */}
                  {item.isLocked && (
                    <div className="absolute inset-0 flex items-center justify-center">
                      <div
                        className="w-8 h-8 rounded-full flex items-center justify-center"
                        style={{
                          background: "linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.95) 100%)",
                          boxShadow: "0 4px 12px rgba(220, 38, 38, 0.8)",
                        }}
                      >
                        <Lock className="w-4 h-4 text-white" />
                      </div>
                    </div>
                  )}

                  {/* Price Badge - Top Left */}
                  {!item.isLocked && item.price && (
                    <div 
                      className="absolute top-0 left-0 flex items-center gap-1 px-2 py-1 rounded-full"
                      style={{
                        background: canAfford
                          ? "linear-gradient(135deg, rgba(44, 34, 66, 0.96) 0%, rgba(30, 22, 50, 0.98) 100%)"
                          : "linear-gradient(135deg, rgba(68, 74, 88, 0.96) 0%, rgba(53, 58, 71, 0.98) 100%)",
                        border: `1.5px solid ${canAfford ? "rgba(255, 214, 240, 0.45)" : "rgba(148, 163, 184, 0.45)"}`,
                        boxShadow: canAfford
                          ? "0 2px 8px rgba(15, 10, 25, 0.6)"
                          : "0 2px 8px rgba(0, 0, 0, 0.4)",
                      }}
                    >
                      <img src={coinImage} alt="سکه" className="w-4 h-4" />
                      <span 
                        className="text-[10px] font-bold"
                        style={{ 
                          color: canAfford ? "#FFF3CC" : "rgba(255, 255, 255, 0.74)",
                          textShadow: "none",
                        }}
                      >
                        {item.price}
                      </span>
                    </div>
                  )}
                </div>

                {/* Item Name */}
                <p 
                  className="text-white text-[11px] font-bold text-center leading-tight line-clamp-2 w-full"
                  style={{
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.5)",
                  }}
                >
                  {item.name}
                </p>
              </motion.button>
            );
          })}
        </div>
      )}

      {/* Owned Tab */}
      {activeTab === "owned" && (
        <div>
          {missionItems.length === 0 && purchasedItems.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-16">
              <div
                className="w-24 h-24 rounded-full flex items-center justify-center mb-4"
                style={{
                  background: "linear-gradient(135deg, rgba(138, 206, 224, 0.2) 0%, rgba(76, 127, 137, 0.2) 100%)",
                  border: "3px solid rgba(138, 206, 224, 0.3)",
                }}
              >
                <Package className="w-12 h-12 text-white/50" />
              </div>
              <h3 className="text-white text-lg font-bold mb-2">هنوز ایتمی ندارید</h3>
              <p className="text-white/60 text-sm text-center">
                با انجام چالش‌ها و خرید از فروشگاه، ایتم‌های جذاب جمع کنید!
              </p>
              <motion.button
                whileTap={{ scale: 0.95 }}
                onClick={() => setActiveTab("shop")}
                className="mt-6 px-6 py-3 rounded-full font-bold"
                style={{
                  background: "linear-gradient(135deg, rgba(255, 183, 0, 0.95) 0%, rgba(255, 140, 0, 0.95) 100%)",
                  boxShadow: "0 8px 24px rgba(255, 165, 0, 0.5)",
                  color: "#5A3800",
                }}
              >
                رفتن به فروشگاه
              </motion.button>
            </div>
          ) : (
            <>
              {/* Section: از ماموریت‌ها */}
              {missionItems.length > 0 && (
                <>
                  <h3 
                    className="text-white text-sm font-bold mb-3"
                    style={{
                      textShadow: "0 2px 4px rgba(0, 0, 0, 0.5)",
                    }}
                  >
                    🏆 از ماموریت‌ها
                  </h3>
                  {loadingMissions ? (
                    <div className="grid grid-cols-4 gap-4 mb-6">
                      {[1, 2, 3, 4].map((i) => (
                        <div key={i} className="flex flex-col items-center gap-1.5">
                          <div 
                            className="w-full aspect-square rounded-lg animate-pulse"
                            style={{
                              background: "linear-gradient(135deg, rgba(138, 206, 224, 0.2) 0%, rgba(76, 127, 137, 0.2) 100%)",
                            }}
                          />
                          <div 
                            className="w-full h-4 rounded animate-pulse"
                            style={{
                              background: "linear-gradient(135deg, rgba(138, 206, 224, 0.2) 0%, rgba(76, 127, 137, 0.2) 100%)",
                            }}
                          />
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="grid grid-cols-4 gap-4 mb-6">
                      {missionItems.map((item, index) => {
                        const isImage = isImageFile(item.magic_bag_file);
                        
                        const handleItemClick = () => {
                          if (isImage) {
                            // نمایش تصویر بزرگ
                            setSelectedImage({
                              url: getMagicBagFileUrl(item.StageID),
                              title: item.magic_bag_title,
                            });
                          } else {
                            // دانلود فایل
                            const link = document.createElement("a");
                            link.href = getMagicBagFileUrl(item.StageID);
                            link.download = item.magic_bag_file || item.magic_bag_title;
                            link.click();
                          }
                        };
                        
                        return (
                          <motion.div
                            key={item.StageID}
                            initial={{ opacity: 0, scale: 0.8 }}
                            animate={{ opacity: 1, scale: 1 }}
                            transition={{ delay: index * 0.05, duration: 0.3 }}
                            className="flex flex-col items-center gap-1.5"
                          >
                            {/* Item Image */}
                            <motion.button
                              onClick={handleItemClick}
                              whileHover={{ scale: 1.1, y: -4 }}
                              whileTap={{ scale: 0.9 }}
                              className="relative w-full"
                            >
                              <img
                                src={getMagicBagFileUrl(item.StageID)}
                                alt={item.magic_bag_title}
                                className="w-full h-auto object-contain"
                                style={{
                                  filter: "drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3))",
                                }}
                                onError={(e) => {
                                  // Fallback to default image if mission image fails to load
                                  e.currentTarget.src = itemImage;
                                }}
                              />
                              
                              {/* دکمه دانلود برای فایل‌های غیر تصویری */}
                              {!isImage && (
                                <div className="absolute inset-0 flex items-center justify-center bg-black/30 rounded-lg">
                                  <div
                                    className="w-10 h-10 rounded-full flex items-center justify-center"
                                    style={{
                                      background: "linear-gradient(135deg, rgba(255, 183, 0, 0.95) 0%, rgba(255, 140, 0, 0.95) 100%)",
                                      boxShadow: "0 4px 12px rgba(255, 165, 0, 0.8)",
                                    }}
                                  >
                                    <Download className="w-5 h-5 text-white" />
                                  </div>
                                </div>
                              )}
                            </motion.button>

                            {/* Item Name */}
                            <p 
                              className="text-white text-[11px] font-bold text-center leading-tight line-clamp-2 w-full"
                              style={{
                                textShadow: "0 1px 2px rgba(0, 0, 0, 0.5)",
                              }}
                            >
                              {item.magic_bag_title}
                            </p>
                          </motion.div>
                        );
                      })}
                    </div>
                  )}
                </>
              )}

              {/* Divider */}
              {missionItems.length > 0 && purchasedItems.length > 0 && (
                <div className="my-5 h-px w-full bg-white/20" />
              )}

              {/* Section: خریداری شده */}
              {purchasedItems.length > 0 && (
                <>
                  <h3 
                    className="text-white text-sm font-bold mb-3"
                    style={{
                      textShadow: "0 2px 4px rgba(0, 0, 0, 0.5)",
                    }}
                  >
                    🛒 خریداری شده
                  </h3>
                  <div className="grid grid-cols-4 gap-4">
                    {purchasedItems.map((item, index) => {
                      return (
                        <motion.button
                          key={item.id}
                          initial={{ opacity: 0, scale: 0.8 }}
                          animate={{ opacity: 1, scale: 1 }}
                          transition={{ delay: (missionItems.length + index) * 0.05, duration: 0.3 }}
                          whileHover={{ scale: 1.1, y: -4 }}
                          whileTap={{ scale: 0.9 }}
                          className="flex flex-col items-center gap-1.5"
                        >
                          {/* Item Image */}
                          <div className="relative w-full">
                            <img
                              src={itemImage}
                              alt={item.name}
                              className="w-full h-auto object-contain"
                              style={{
                                filter: "drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3))",
                              }}
                            />
                          </div>

                          {/* Item Name */}
                          <p 
                            className="text-white text-[11px] font-bold text-center leading-tight line-clamp-2 w-full"
                            style={{
                              textShadow: "0 1px 2px rgba(0, 0, 0, 0.5)",
                            }}
                          >
                            {item.name}
                          </p>
                        </motion.button>
                      );
                    })}
                  </div>
                </>
              )}
            </>
          )}
        </div>
      )}

      {/* Image Preview Modal */}
      <AnimatePresence>
        {selectedImage && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={() => setSelectedImage(null)}
            className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 px-4"
            style={{ backdropFilter: "blur(8px)" }}
          >
            <motion.div
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.8, opacity: 0 }}
              onClick={(e) => e.stopPropagation()}
              className="relative max-w-4xl w-full"
            >
              {/* Close Button */}
              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={() => setSelectedImage(null)}
                className="absolute -top-12 left-0 w-10 h-10 rounded-full flex items-center justify-center z-10"
                style={{
                  background: "linear-gradient(135deg, rgba(220, 38, 38, 0.95) 0%, rgba(185, 28, 28, 0.95) 100%)",
                  boxShadow: "0 4px 12px rgba(220, 38, 38, 0.8)",
                }}
              >
                <X className="w-6 h-6 text-white" />
              </motion.button>

              {/* Download Button */}
              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={() => {
                  const link = document.createElement("a");
                  link.href = selectedImage.url;
                  link.download = selectedImage.title;
                  link.click();
                }}
                className="absolute -top-12 right-0 w-10 h-10 rounded-full flex items-center justify-center z-10"
                style={{
                  background: "linear-gradient(135deg, rgba(255, 183, 0, 0.95) 0%, rgba(255, 140, 0, 0.95) 100%)",
                  boxShadow: "0 4px 12px rgba(255, 165, 0, 0.8)",
                }}
              >
                <Download className="w-6 h-6 text-white" />
              </motion.button>

              {/* Image Container */}
              <div
                className="rounded-2xl overflow-hidden"
                style={{
                  boxShadow: "0 25px 50px rgba(0, 0, 0, 0.5)",
                  border: "2px solid rgba(138, 206, 224, 0.3)",
                }}
              >
                <img
                  src={selectedImage.url}
                  alt={selectedImage.title}
                  className="w-full h-auto max-h-[80vh] object-contain bg-black/50"
                />
              </div>

              {/* Title */}
              <div className="mt-4 text-center">
                <p
                  className="text-white text-lg font-bold"
                  style={{
                    textShadow: "0 2px 4px rgba(0, 0, 0, 0.8)",
                  }}
                >
                  {selectedImage.title}
                </p>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
