import { useState } from 'react';
import Head from 'next/head';
import Image from 'next/image';
import Link from 'next/link';
import { GetStaticProps, GetStaticPaths } from 'next';
import { useRouter } from 'next/router';
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import { Product, products, getProductBySlug, getSimilarProducts, formatPrice } from '../../data/products';
import { Category, getCategoryById } from '../../data/categories';
import { Heart, ShoppingBag, ChevronLeft, ChevronRight } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface ProductPageProps {
  product: Product;
  category: Category;
  similarProducts: Product[];
}

export default function ProductPage({ product, category, similarProducts }: ProductPageProps) {
  const router = useRouter();
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [isFavorite, setIsFavorite] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [hoveredProduct, setHoveredProduct] = useState<number | null>(null);

  // Если страница еще загружается, показываем заглушку
  if (router.isFallback) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-gray-900"></div>
      </div>
    );
  }

  // Функция для переключения изображений
  const nextImage = () => {
    setCurrentImageIndex((prev) => (prev === product.images.length - 1 ? 0 : prev + 1));
  };

  const prevImage = () => {
    setCurrentImageIndex((prev) => (prev === 0 ? product.images.length - 1 : prev - 1));
  };

  // Функция для добавления/удаления товара из избранного
  const toggleFavorite = () => {
    setIsFavorite(!isFavorite);
  };

  // Функция для изменения количества товара
  const incrementQuantity = () => {
    setQuantity((prev) => prev + 1);
  };

  const decrementQuantity = () => {
    if (quantity > 1) {
      setQuantity((prev) => prev - 1);
    }
  };

  // Функция для добавления товара в корзину
  const addToCart = () => {
    // Здесь будет логика добавления товара в корзину
    alert(`Товар "${product.name}" добавлен в корзину в количестве ${quantity} шт.`);
  };

  return (
    <div className="min-h-screen bg-white font-['Arimo']">
      <Head>
        <title>{product.name} | Brand Store</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <Header />

      <main className="max-w-7xl mx-auto px-4 py-12 md:px-8">
        <div className="mb-8">
          <Link href={`/category/${category.slug}`} className="text-gray-600 hover:text-black transition-colors">
            ← {category.name}
          </Link>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Галерея изображений */}
          <div className="relative">
            <div className="relative aspect-[3/4] overflow-hidden rounded-xl">
              <AnimatePresence mode="wait">
                <motion.div
                  key={currentImageIndex}
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                  transition={{ duration: 0.3 }}
                  className="absolute inset-0"
                >
                  <Image
                    src={product.images[currentImageIndex]}
                    alt={product.name}
                    fill
                    className="object-cover"
                    priority
                    quality={95}
                  />
                </motion.div>
              </AnimatePresence>

              {/* Кнопки навигации по галерее */}
              {product.images.length > 1 && (
                <>
                  <button
                    onClick={prevImage}
                    className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-white/50 hover:bg-white/70 p-3 rounded-full transition-all z-10"
                    aria-label="Предыдущее изображение"
                  >
                    <ChevronLeft className="w-5 h-5 text-black" />
                  </button>
                  <button
                    onClick={nextImage}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-white/50 hover:bg-white/70 p-3 rounded-full transition-all z-10"
                    aria-label="Следующее изображение"
                  >
                    <ChevronRight className="w-5 h-5 text-black" />
                  </button>
                </>
              )}
            </div>

            {/* Миниатюры изображений */}
            {product.images.length > 1 && (
              <div className="flex mt-4 space-x-2 overflow-x-auto">
                {product.images.map((image, index) => (
                  <button
                    key={index}
                    onClick={() => setCurrentImageIndex(index)}
                    className={`relative w-20 h-20 rounded-md overflow-hidden ${
                      index === currentImageIndex ? 'ring-2 ring-black' : 'opacity-70 hover:opacity-100'
                    }`}
                    aria-label={`Изображение ${index + 1}`}
                  >
                    <Image src={image} alt={`${product.name} - изображение ${index + 1}`} fill className="object-cover" />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Информация о товаре */}
          <div>
            <motion.h1
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5 }}
              className="text-3xl font-bold font-['Playfair_Display']"
            >
              {product.name}
            </motion.h1>

            <motion.p
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.1 }}
              className="text-2xl font-bold mt-4"
            >
              {formatPrice(product.price)} ₽
            </motion.p>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              className="mt-6"
            >
              <h2 className="text-lg font-medium mb-2">Описание</h2>
              <p className="text-gray-600">{product.description}</p>
            </motion.div>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.3 }}
              className="mt-8"
            >
              <h2 className="text-lg font-medium mb-2">Количество</h2>
              <div className="flex items-center border border-gray-300 rounded-md w-fit">
                <button
                  onClick={decrementQuantity}
                  className="px-4 py-2 text-gray-600 hover:bg-gray-100 transition-colors"
                  aria-label="Уменьшить количество"
                  disabled={quantity <= 1}
                >
                  -
                </button>
                <span className="px-4 py-2 border-l border-r border-gray-300">{quantity}</span>
                <button
                  onClick={incrementQuantity}
                  className="px-4 py-2 text-gray-600 hover:bg-gray-100 transition-colors"
                  aria-label="Увеличить количество"
                >
                  +
                </button>
              </div>
            </motion.div>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.4 }}
              className="mt-8 flex flex-col sm:flex-row gap-4"
            >
              <button
                onClick={addToCart}
                className="flex items-center justify-center gap-2 bg-black text-white px-8 py-3 rounded-md hover:bg-gray-800 transition-colors"
              >
                <ShoppingBag className="w-5 h-5" />
                Добавить в корзину
              </button>
              <button
                onClick={toggleFavorite}
                className={`flex items-center justify-center gap-2 px-8 py-3 rounded-md border transition-colors ${
                  isFavorite
                    ? 'border-red-500 text-red-500 hover:bg-red-50'
                    : 'border-gray-300 text-gray-700 hover:bg-gray-50'
                }`}
              >
                <Heart className={isFavorite ? 'w-5 h-5 fill-red-500' : 'w-5 h-5'} />
                {isFavorite ? 'В избранном' : 'В избранное'}
              </button>
            </motion.div>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.5 }}
              className="mt-8 border-t border-gray-200 pt-8"
            >
              <h2 className="text-lg font-medium mb-2">Категория</h2>
              <Link href={`/category/${category.slug}`} className="text-gray-600 hover:text-black transition-colors">
                {category.name}
              </Link>
            </motion.div>
          </div>
        </div>

        {/* Похожие товары */}
        {similarProducts.length > 0 && (
          <section className="mt-16">
            <h2 className="text-2xl font-bold mb-8 font-['Playfair_Display']">Похожие товары</h2>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
              {similarProducts.map((similarProduct) => (
                <motion.div
                  key={similarProduct.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: similarProduct.id * 0.05 }}
                  whileHover={{ y: -5, transition: { duration: 0.2 } }}
                >
                  <Link
                    href={`/product/${similarProduct.slug}`}
                    className="block h-full"
                    onMouseEnter={() => setHoveredProduct(similarProduct.id)}
                    onMouseLeave={() => setHoveredProduct(null)}
                  >
                    <div className="relative overflow-hidden rounded-xl">
                      <div className="aspect-[3/4] relative overflow-hidden rounded-xl">
                        <Image
                          src={
                            hoveredProduct === similarProduct.id && similarProduct.images.length > 1
                              ? similarProduct.images[1]
                              : similarProduct.images[0]
                          }
                          alt={similarProduct.name}
                          fill
                          sizes="(max-width: 640px) 100vw, (max-width: 768px) 50vw, (max-width: 1024px) 33vw, 25vw"
                          className="object-cover transition-all duration-500 group-hover:scale-105"
                        />
                        {similarProduct.isNew && (
                          <span className="absolute top-4 left-4 bg-black text-white text-sm py-1 px-3 rounded">
                            Новинка
                          </span>
                        )}
                      </div>
                    </div>
                    <div className="mt-4">
                      <h3 className="text-lg font-medium">{similarProduct.name}</h3>
                      <p className="mt-1 text-lg font-bold">{formatPrice(similarProduct.price)} ₽</p>
                    </div>
                  </Link>
                </motion.div>
              ))}
            </div>
          </section>
        )}
      </main>

      <Footer />
    </div>
  );
}

export const getStaticPaths: GetStaticPaths = async () => {
  const paths = products.map((product) => ({
    params: { slug: product.slug },
  }));

  return {
    paths,
    fallback: 'blocking',
  };
};

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const slug = params?.slug as string;
  const product = getProductBySlug(slug);

  if (!product) {
    return {
      notFound: true,
    };
  }

  const category = getCategoryById(product.categoryId);
  const similarProducts = getSimilarProducts(product.id);

  if (!category) {
    return {
      notFound: true,
    };
  }

  return {
    props: {
      product,
      category,
      similarProducts,
    },
    revalidate: 600, // Перегенерация страницы каждые 10 минут
  };
}; 