import React, { useState } from 'react';
import { motion, AnimatePresence } from 'motion/react';
import { X, ShoppingCart, Check, ShieldCheck, Zap, Sparkles, Plus, Minus, Tag, Clock, ArrowLeft } from 'lucide-react';
import type { Product } from '../types';
import { formatPrice, toPersianDigits } from '../utils/formatters';
import { useCart } from '../context/CartContext';

interface ProductDetailsModalProps {
  product: Product | null;
  onClose: () => void;
  onSelectRelatedProduct: (product: Product) => void;
  relatedProducts: Product[];
}

export const ProductDetailsModal: React.FC<ProductDetailsModalProps> = ({
  product,
  onClose,
  onSelectRelatedProduct,
  relatedProducts,
}) => {
  const { addToCart, items } = useCart();
  const [quantity, setQuantity] = useState(1);
  const [selectedRegion, setSelectedRegion] = useState(product?.regions?.[0] || '');

  if (!product) return null;

  const inCart = items.some(i => i.product.id === product.id);

  const handleAddToCart = () => {
    if (product.regions?.length && !selectedRegion) return;
    addToCart(product, quantity, selectedRegion || undefined);
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4">
      {/* Backdrop */}
      <div onClick={onClose} className="fixed inset-0 bg-black/80 backdrop-blur-md" />

      <motion.div
        initial={{ opacity: 0, scale: 0.95, y: 15 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95 }}
        className="relative w-full max-w-4xl bg-[#110926] border border-purple-500/30 rounded-3xl p-6 sm:p-8 shadow-2xl z-10 text-right overflow-hidden max-h-[90vh] flex flex-col"
      >
        
        {/* Close Button */}
        <button
          onClick={onClose}
          className="absolute left-4 top-4 p-2 text-zinc-400 hover:text-white rounded-xl bg-[#1a0f35] border border-purple-500/20 z-20"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="overflow-y-auto pr-1 space-y-8">
          
          {/* Main Top Section */}
          <div className="grid grid-cols-1 md:grid-cols-12 gap-8 items-start">
            
            {/* Product Image */}
            <div className="md:col-span-5 relative rounded-2xl overflow-hidden bg-[#0a0516] border border-purple-500/20 aspect-square shadow-xl">
              <img
                src={product.image}
                alt={product.title}
                className="w-full h-full object-cover"
                referrerPolicy="no-referrer"
              />
              
              {/* Badges */}
              <div className="absolute top-3 right-3 flex flex-col gap-1.5 items-end">
                {product.badge && (
                  <span className="px-3 py-1 rounded-lg bg-purple-600/90 backdrop-blur-md text-white text-xs font-bold shadow-md">
                    {product.badge}
                  </span>
                )}
                {product.discountPercent && (
                  <span className="px-2.5 py-1 rounded-lg bg-rose-600 text-white text-xs font-black shadow-md">
                    {toPersianDigits(product.discountPercent)}٪ تخفیف ویژه
                  </span>
                )}
              </div>
            </div>

            {/* Product Meta & Details */}
            <div className="md:col-span-7 space-y-4">
              
              {/* Category & Stock Pill */}
              <div className="flex items-center gap-2">
                <span className="px-2.5 py-0.5 rounded-md bg-purple-950/80 text-purple-300 border border-purple-500/30 text-xs font-medium">
                  {product.categoryName || 'محصول دیجیتال'}
                </span>
                {product.inStock ? (
                  <span className="px-2.5 py-0.5 rounded-md bg-emerald-950/80 text-emerald-400 border border-emerald-500/30 text-xs font-medium flex items-center gap-1">
                    <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                    موجود در انبار ({toPersianDigits(product.stockCount)} عدد)
                  </span>
                ) : (
                  <span className="px-2.5 py-0.5 rounded-md bg-zinc-900 text-zinc-400 text-xs">
                    ناموجود
                  </span>
                )}
              </div>

              {/* Title */}
              <h1 className="text-xl sm:text-2xl font-black text-white leading-snug">
                {product.title}
              </h1>

              {/* Price Row */}
              <div className="p-4 rounded-2xl bg-[#170e33] border border-purple-500/20 flex items-center justify-between">
                <div>
                  <div className="text-xs text-zinc-400">قیمت نهایی محصول:</div>
                  <div className="text-2xl font-black text-purple-300 mt-0.5">
                    {formatPrice(product.price)}
                  </div>
                </div>

                {product.originalPrice && product.originalPrice > product.price && (
                  <div className="text-left">
                    <div className="text-xs text-zinc-500">قیمت اصلی:</div>
                    <div className="text-sm text-zinc-400 line-through">
                      {formatPrice(product.originalPrice)}
                    </div>
                  </div>
                )}
              </div>

              {/* Region / Platform Selection */}
              {product.regions && product.regions.length > 0 && (
                <div className="p-3 rounded-2xl bg-[#140c2a] border border-purple-500/20 space-y-2">
                  <label className="block text-xs font-bold text-zinc-300">ریجن قابل تحویل</label>
                  <select
                    value={selectedRegion}
                    onChange={(e) => setSelectedRegion(e.target.value)}
                    className="w-full bg-[#0c071a] text-sm text-white px-3 py-2.5 rounded-xl border border-purple-500/20 focus:border-purple-500 focus:outline-none"
                  >
                    <option value="">انتخاب ریجن</option>
                    {product.regions.map((region) => (
                      <option key={region} value={region}>{region}</option>
                    ))}
                  </select>
                  <p className="text-[11px] text-zinc-500 leading-relaxed">ریجن حساب خود را با دقت انتخاب کنید. قابلیت تحویل به هر ریجن باید قبل از خرید بررسی شود.</p>
                </div>
              )}

              {/* Quantity and Add to Cart Button */}
              {product.inStock ? (
                <div className="flex items-center gap-3 pt-2">
                  <div className="flex items-center border border-purple-500/30 rounded-xl bg-[#0c071a] px-2 py-2">
                    <button
                      onClick={() => setQuantity(q => q + 1)}
                      className="p-1 text-zinc-400 hover:text-white"
                    >
                      <Plus className="w-4 h-4" />
                    </button>
                    <span className="px-3 text-sm font-bold text-white min-w-[28px] text-center font-vazir">
                      {toPersianDigits(quantity)}
                    </span>
                    <button
                      onClick={() => setQuantity(q => Math.max(1, q - 1))}
                      className="p-1 text-zinc-400 hover:text-white"
                    >
                      <Minus className="w-4 h-4" />
                    </button>
                  </div>

                  <button
                    onClick={handleAddToCart}
                    className="flex-1 py-3.5 rounded-xl bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white font-bold text-sm shadow-xl shadow-purple-600/30 transition-all hover:scale-[1.01] active:scale-95 flex items-center justify-center gap-2"
                  >
                    <ShoppingCart className="w-5 h-5" />
                    <span>افزودن به سبد خرید ({toPersianDigits(quantity)} عدد)</span>
                  </button>
                </div>
              ) : (
                <div className="p-3 bg-zinc-900/80 rounded-xl text-center text-xs text-zinc-400">
                  این محصول موقتاً به اتمام رسیده است.
                </div>
              )}

              {/* Fast Delivery Info Note */}
              <div className="grid grid-cols-2 gap-2 text-xs text-zinc-300 pt-2">
                <div className="flex items-center gap-1.5 p-2 rounded-lg bg-[#140c2a] border border-purple-500/10">
                  <Zap className="w-3.5 h-3.5 text-purple-400 shrink-0" />
                  <span>تحویل خودکار کمتر از ۱۰ دقیقه</span>
                </div>
                <div className="flex items-center gap-1.5 p-2 rounded-lg bg-[#140c2a] border border-purple-500/10">
                  <ShieldCheck className="w-3.5 h-3.5 text-emerald-400 shrink-0" />
                  <span>گارانتی کامل و اصالت دائم</span>
                </div>
              </div>

            </div>

          </div>

          {/* Description & Features Tabs/Boxes */}
          <div className="space-y-4 pt-4 border-t border-purple-900/40">
            <h3 className="text-base font-bold text-white flex items-center gap-2">
              <Sparkles className="w-4 h-4 text-purple-400" />
              توضیحات و مشخصات جامع
            </h3>

            <p className="text-sm text-zinc-300 leading-relaxed font-light whitespace-pre-line">
              {product.description}
            </p>

            {product.features && product.features.length > 0 && (
              <div className="pt-2">
                <div className="text-xs font-bold text-zinc-400 mb-2">ویژگی‌های برجسته محصول:</div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {product.features.map((feat, i) => (
                    <div
                      key={i}
                      className="p-2.5 rounded-xl bg-[#140c2c] border border-purple-500/15 text-xs text-zinc-200 flex items-start gap-2"
                    >
                      <Check className="w-4 h-4 text-emerald-400 shrink-0 mt-0.5" />
                      <span>{feat}</span>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {product.deliveryNote && (
              <div className="p-3.5 rounded-xl bg-[#180f33] border border-purple-500/20 text-xs text-purple-200 flex items-start gap-2.5">
                <Clock className="w-4 h-4 text-purple-400 shrink-0 mt-0.5" />
                <div>
                  <span className="font-bold">نحوه تحویل: </span>
                  <span>{product.deliveryNote}</span>
                </div>
              </div>
            )}

            {product.tags && product.tags.length > 0 && (
              <div className="flex flex-wrap items-center gap-1.5 pt-2">
                <Tag className="w-3.5 h-3.5 text-zinc-500 ml-1" />
                {product.tags.map((tag, i) => (
                  <span
                    key={i}
                    className="px-2 py-0.5 rounded-md bg-[#160d31] text-[11px] text-zinc-400 border border-purple-900/40"
                  >
                    #{tag}
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* Related Products */}
          {relatedProducts.length > 0 && (
            <div className="pt-6 border-t border-purple-900/40">
              <h3 className="text-sm font-bold text-white mb-3">محصولات مشابه و مرتبط:</h3>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
                {relatedProducts.slice(0, 3).map((rel) => (
                  <div
                    key={rel.id}
                    onClick={() => onSelectRelatedProduct(rel)}
                    className="p-2.5 rounded-xl bg-[#140c2b] border border-purple-500/15 hover:border-purple-500/40 cursor-pointer transition-all hover:-translate-y-0.5 group"
                  >
                    <img
                      src={rel.image}
                      alt={rel.title}
                      className="w-full aspect-[16/10] object-cover rounded-lg mb-2"
                      referrerPolicy="no-referrer"
                    />
                    <div className="text-xs font-bold text-zinc-200 group-hover:text-purple-300 truncate">
                      {rel.title}
                    </div>
                    <div className="text-xs text-purple-400 font-medium mt-1">
                      {formatPrice(rel.price)}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

        </div>

      </motion.div>
    </div>
  );
};
