import { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { Star } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/utils";
import { notFound } from "next/navigation";

const petConfig: Record<string, { name: string; emoji: string; hero: string; description: string; color: string; subcategories: { label: string; href: string; icon: string }[] }> = {
  dog: {
    name: "Dog",
    emoji: "🐕",
    hero: "https://images.pexels.com/photos/1108099/pexels-photo-1108099.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750",
    description: "Everything your best friend needs — from premium nutrition to cozy beds and interactive toys.",
    color: "from-amber-500 to-orange-600",
    subcategories: [
      { label: "Food & Nutrition", href: "/shop?pet=dog&category=Food+%26+Nutrition", icon: "🍖" },
      { label: "Toys & Enrichment", href: "/shop?pet=dog&category=Toys+%26+Enrichment", icon: "🎾" },
      { label: "Health & Wellness", href: "/shop?pet=dog&category=Health+%26+Wellness", icon: "💊" },
      { label: "Grooming", href: "/shop?pet=dog&category=Grooming", icon: "🛁" },
      { label: "Beds & Furniture", href: "/shop?pet=dog&category=Beds+%26+Furniture", icon: "🛏️" },
      { label: "Travel & Accessories", href: "/shop?pet=dog&category=Travel+%26+Accessories", icon: "🚗" },
    ],
  },
  cat: {
    name: "Cat",
    emoji: "🐈",
    hero: "https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750",
    description: "From gourmet meals to climbing towers and cozy hideaways — keep your feline purring.",
    color: "from-purple-500 to-indigo-600",
    subcategories: [
      { label: "Food & Nutrition", href: "/shop?pet=cat&category=Food+%26+Nutrition", icon: "🐟" },
      { label: "Toys & Enrichment", href: "/shop?pet=cat&category=Toys+%26+Enrichment", icon: "🧶" },
      { label: "Health & Wellness", href: "/shop?pet=cat&category=Health+%26+Wellness", icon: "💊" },
      { label: "Grooming", href: "/shop?pet=cat&category=Grooming", icon: "✨" },
      { label: "Beds & Furniture", href: "/shop?pet=cat&category=Beds+%26+Furniture", icon: "🏠" },
      { label: "Litter & Accessories", href: "/shop?pet=cat&category=Travel+%26+Accessories", icon: "🪣" },
    ],
  },
  bird: {
    name: "Bird",
    emoji: "🦜",
    hero: "https://images.pexels.com/photos/1661179/pexels-photo-1661179.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750",
    description: "Seeds, toys, cages, and accessories to keep your feathered companion happy and healthy.",
    color: "from-green-500 to-teal-600",
    subcategories: [
      { label: "Food & Seeds", href: "/shop?pet=bird&category=Food+%26+Nutrition", icon: "🌾" },
      { label: "Cages & Habitats", href: "/shop?pet=bird&category=Beds+%26+Furniture", icon: "🏠" },
      { label: "Toys & Perches", href: "/shop?pet=bird&category=Toys+%26+Enrichment", icon: "🪶" },
      { label: "Health & Wellness", href: "/shop?pet=bird&category=Health+%26+Wellness", icon: "💊" },
    ],
  },
  fish: {
    name: "Fish & Aquatic",
    emoji: "🐠",
    hero: "https://images.pexels.com/photos/128756/pexels-photo-128756.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750",
    description: "Aquariums, filters, food, and décor — everything for a thriving underwater world.",
    color: "from-blue-500 to-cyan-600",
    subcategories: [
      { label: "Food & Nutrition", href: "/shop?pet=fish&category=Food+%26+Nutrition", icon: "🦐" },
      { label: "Tanks & Aquariums", href: "/shop?pet=fish&category=Beds+%26+Furniture", icon: "🐚" },
      { label: "Filters & Pumps", href: "/shop?pet=fish&category=Technology", icon: "⚙️" },
      { label: "Décor & Plants", href: "/shop?pet=fish&category=Toys+%26+Enrichment", icon: "🌿" },
    ],
  },
  small: {
    name: "Small Pets",
    emoji: "🐹",
    hero: "https://images.pexels.com/photos/4588065/pexels-photo-4588065.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750",
    description: "Hamsters, rabbits, guinea pigs, and more — food, habitats, and accessories for small companions.",
    color: "from-pink-500 to-rose-600",
    subcategories: [
      { label: "Food & Hay", href: "/shop?pet=small&category=Food+%26+Nutrition", icon: "🥕" },
      { label: "Habitats & Cages", href: "/shop?pet=small&category=Beds+%26+Furniture", icon: "🏡" },
      { label: "Toys & Exercise", href: "/shop?pet=small&category=Toys+%26+Enrichment", icon: "🎡" },
      { label: "Bedding & Litter", href: "/shop?pet=small&category=Grooming", icon: "🪵" },
    ],
  },
};

interface PageProps {
  params: Promise<{ pet: string }>;
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { pet } = await params;
  const config = petConfig[pet];
  if (!config) return { title: "Not Found" };
  return {
    title: `${config.name} Supplies – Americas.Pet`,
    description: config.description,
  };
}

export default async function PetCategoryPage({ params }: PageProps) {
  const { pet } = await params;
  const config = petConfig[pet];
  if (!config) notFound();

  const products = await prisma.product.findMany({
    where: { petType: pet, active: true },
    orderBy: { rating: "desc" },
    take: 8,
  });

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero */}
      <div className={`relative bg-gradient-to-br ${config.color} text-white py-20 overflow-hidden`}>
        <div className="absolute inset-0 opacity-20">
          <Image src={config.hero} alt={config.name} fill className="object-cover" />
        </div>
        <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <span className="text-5xl mb-4 block">{config.emoji}</span>
          <h1 className="text-4xl md:text-5xl font-bold mb-4">{config.name} Supplies</h1>
          <p className="text-lg text-white/90 max-w-2xl mx-auto">{config.description}</p>
          <Link href={`/shop?pet=${pet}`} className="inline-block mt-6 bg-white text-gray-900 font-semibold px-6 py-3 rounded-full hover:bg-gray-100 transition-colors">
            Shop All {config.name} Products →
          </Link>
        </div>
      </div>

      {/* Subcategories */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-8 relative z-10">
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3">
          {config.subcategories.map((sub) => (
            <Link key={sub.label} href={sub.href} className="bg-white rounded-2xl p-4 text-center shadow-sm border border-gray-100 hover:shadow-md hover:border-primary-200 transition-all group">
              <span className="text-2xl mb-2 block">{sub.icon}</span>
              <span className="text-xs font-medium text-gray-700 group-hover:text-primary-600">{sub.label}</span>
            </Link>
          ))}
        </div>
      </div>

      {/* Top Products */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
        <div className="flex items-center justify-between mb-8">
          <h2 className="text-2xl font-bold text-gray-900">Top Rated {config.name} Products</h2>
          <Link href={`/shop?pet=${pet}`} className="text-sm font-medium text-primary-600 hover:text-primary-700">
            View All →
          </Link>
        </div>

        {products.length === 0 ? (
          <div className="text-center py-12 bg-white rounded-2xl border border-gray-100">
            <p className="text-gray-500">No products available yet. Check back soon!</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-5">
            {products.map((product) => {
              const images = (() => { try { return JSON.parse(product.images); } catch { return []; } })();
              return (
                <Link key={product.id} href={`/shop/${product.id}`} className="bg-white rounded-2xl overflow-hidden shadow-sm border border-gray-100 hover:shadow-md transition-shadow group">
                  <div className="relative aspect-square bg-gray-100">
                    {images[0] && (
                      <Image src={images[0]} alt={product.name} fill className="object-cover group-hover:scale-105 transition-transform" />
                    )}
                    {product.salePrice && (
                      <span className="absolute top-3 left-3 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full">
                        SALE
                      </span>
                    )}
                  </div>
                  <div className="p-4">
                    <h3 className="font-medium text-gray-900 text-sm line-clamp-2 mb-2">{product.name}</h3>
                    <div className="flex items-center gap-1 mb-2">
                      <Star className="h-3.5 w-3.5 fill-yellow-400 text-yellow-400" />
                      <span className="text-xs text-gray-500">{product.rating} ({product.reviewCount})</span>
                    </div>
                    <div className="flex items-center gap-2">
                      {product.salePrice ? (
                        <>
                          <span className="font-bold text-red-600">{formatPrice(product.salePrice)}</span>
                          <span className="text-xs text-gray-400 line-through">{formatPrice(product.price)}</span>
                        </>
                      ) : (
                        <span className="font-bold text-gray-900">{formatPrice(product.price)}</span>
                      )}
                    </div>
                  </div>
                </Link>
              );
            })}
          </div>
        )}
      </div>

      {/* Insurance CTA */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16">
        <div className={`bg-gradient-to-br ${config.color} rounded-3xl p-10 text-white text-center`}>
          <h3 className="text-2xl font-bold mb-3">Protect Your {config.name} with Insurance</h3>
          <p className="text-white/80 mb-6 max-w-lg mx-auto">Accidents and illnesses happen. Get peace of mind with comprehensive pet insurance starting at $19.99/month.</p>
          <Link href="/insurance" className="inline-block bg-white text-gray-900 font-semibold px-6 py-3 rounded-full hover:bg-gray-100 transition-colors">
            Explore Insurance Plans
          </Link>
        </div>
      </div>
    </div>
  );
}
