import { GetStaticPaths, GetStaticProps } from "next"
import Head from "next/head"
import Image from "next/image"
import Link from "next/link"
import { useState } from "react"
import { Heart } from "lucide-react"
import Header from "../../components/Header"
import Footer from "../../components/Footer"
import { categories, getCategoryBySlug } from "../../data/categories"
import { Product, getProductsByCategory, formatPrice } from "../../data/products"
import { useRouter } from "next/router"
import { motion } from "framer-motion"

interface CategoryPageProps {
  category: {
    id: number
    name: string
    image: string
    url: string
    slug: string
    description: string
  }
  products: Product[]
}

export default function CategoryPage({ category, products }: CategoryPageProps) {
  const router = useRouter()
  const [hoveredProduct, setHoveredProduct] = useState<number | null>(null)
  const [favorites, setFavorites] = useState<number[]>([])

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

  // Функция для добавления/удаления товара из избранного
  const toggleFavorite = (id: number, e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setFavorites((prev) => (prev.includes(id) ? prev.filter((itemId) => itemId !== id) : [...prev, id]))
  }

  return (
    <div className="min-h-screen bg-white font-['Arimo']">
      <Head>
        <title>{category.name} | Brand Store</title>
        <link rel="icon" href="/favicon.ico" />
        <link href="https://fonts.googleapis.com/css2?family=Arimo:wght@400;500;600;700&display=swap" rel="stylesheet" />
      </Head>

      <Header />

      <main className="pt-24 pb-16 px-4 md:px-8">
        <div className="container mx-auto">
          <div className="relative mb-12 rounded-lg overflow-hidden h-64 md:h-80">
            <Image
              src={category.image}
              alt={category.name}
              fill
              className="object-cover"
            />
            <div className="absolute inset-0 bg-[#2B5F47]/50 flex items-center justify-center">
              <div className="text-center">
                <motion.h1 
                  initial={{ opacity: 0, y: -20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5 }}
                  className="text-3xl md:text-5xl font-bold mb-4 text-white"
                >
                  {category.name}
                </motion.h1>
                <motion.p
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  transition={{ duration: 0.5, delay: 0.2 }}
                  className="text-white/90 max-w-2xl mx-auto px-4"
                >
                  {category.description}
                </motion.p>
              </div>
            </div>
          </div>

          {products.length > 0 ? (
            <motion.div 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.3 }}
              className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6"
            >
              {products.map((product, index) => (
                <motion.div
                  key={product.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.5, delay: 0.1 * index }}
                  className="bg-white rounded-lg overflow-hidden shadow-md hover:shadow-lg transition-shadow"
                  onMouseEnter={() => setHoveredProduct(product.id)}
                  onMouseLeave={() => setHoveredProduct(null)}
                >
                  <Link href={`/product/${product.slug}`}>
                    <div className="relative h-64 w-full overflow-hidden">
                      <Image
                        src={product.images[0]}
                        alt={product.name}
                        fill
                        className="object-cover transition-transform duration-500 ease-in-out"
                        style={{
                          transform: hoveredProduct === product.id && product.images.length > 1 
                            ? 'scale(1.1)' 
                            : 'scale(1)'
                        }}
                      />
                      <button
                        onClick={(e) => toggleFavorite(product.id, e)}
                        className="absolute top-3 right-3 p-2 rounded-full bg-white/80 hover:bg-white transition-colors z-10"
                      >
                        <Heart 
                          className={`w-5 h-5 ${favorites.includes(product.id) ? 'fill-[#63823B] text-[#63823B]' : 'text-gray-600'}`} 
                        />
                      </button>
                    </div>
                    <div className="p-4">
                      <h3 className="text-lg font-medium text-[#2B5F47] mb-1">{product.name}</h3>
                      <p className="text-sm text-gray-600 mb-2 line-clamp-2">{product.description}</p>
                      <div className="flex justify-between items-center">
                        <span className="font-bold text-[#2B5F47]">{formatPrice(product.price)} ₽</span>
                        <span className="text-sm text-[#63823B]">
                          {product.inStock ? 'В наличии' : 'Нет в наличии'}
                        </span>
                      </div>
                    </div>
                  </Link>
                </motion.div>
              ))}
            </motion.div>
          ) : (
            <div className="text-center py-12">
              <p className="text-xl text-[#2B5F47] mb-4">В этой категории пока нет товаров</p>
              <Link href="/category" className="inline-block px-6 py-3 bg-[#63823B] text-white rounded-md hover:bg-[#2B5F47] transition-colors">
                Вернуться к категориям
              </Link>
            </div>
          )}
        </div>
      </main>

      <Footer />
    </div>
  )
}

export const getStaticPaths: GetStaticPaths = async () => {
  const paths = categories.map((category) => ({
    params: { slug: category.slug },
  }))

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

export const getStaticProps: GetStaticProps = async ({ params }) => {
  const slug = params?.slug as string
  const category = getCategoryBySlug(slug)

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

  const products = getProductsByCategory(category.id)

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