"use client";

import { useState } from "react";
import Header from "@/app/components/Header";
import Footer from "@/app/components/Footer";
// import { useRouter } from "next/navigation";
import { useGetTenderCategoriesQuery } from "@/redux/apis/tenderApi";
import { sortCategories } from "@/lib/constants/categoryOrder";
import { motion, AnimatePresence } from "framer-motion";
import Link from "next/link";
import { Tender } from "@/lib/api";

interface TenderCategory {
  name: string;
  description: string;
  tenderCount?: number;
  tenders?: Tender[];
}

export default function CategoriesPage() {
  const [searchQuery, setSearchQuery] = useState("");
  // const router = useRouter();
  const { data: categoriesData } = useGetTenderCategoriesQuery({});

  const iconMap: Record<string, string> = {
    "EPC Tenders": "🏗️",
    "Supply Tenders": "📦",
    "Residence EPC Tenders": "🏠",
    "Commercial EPC Tenders": "🏢",
    "Industrial EPC Tenders": "🏭",
    "Street Light EPC Tenders": "💡",
    "O & M Tenders": "🔧",
    "Solar Water Hiter Tenders": "🚿",
    "Manpower Supply Tenders": "👥",
    "Machinery Supply Tenders": "⚙️",
    "JV Tenders": "🤝",
    "Finance Tenders": "💰",
    "EV Charger": "⚡",
    "EV Battery": "🔋",
    "Sub-Tenders": "📋"
  };

  const colorThemes = [
    { color: "from-green-500 to-green-600", bgColor: "bg-green-50", iconBg: "bg-green-100" },
    { color: "from-orange-500 to-orange-600", bgColor: "bg-orange-50", iconBg: "bg-orange-100" },
    { color: "from-yellow-500 to-yellow-600", bgColor: "bg-yellow-50", iconBg: "bg-yellow-100" },
    { color: "from-blue-500 to-blue-600", bgColor: "bg-blue-50", iconBg: "bg-blue-100" },
    { color: "from-red-500 to-red-600", bgColor: "bg-red-50", iconBg: "bg-red-100" },
    { color: "from-indigo-500 to-indigo-600", bgColor: "bg-indigo-50", iconBg: "bg-indigo-100" },
    { color: "from-teal-500 to-teal-600", bgColor: "bg-teal-50", iconBg: "bg-teal-100" },
    { color: "from-cyan-500 to-cyan-600", bgColor: "bg-cyan-50", iconBg: "bg-cyan-100" },
    { color: "from-purple-500 to-purple-600", bgColor: "bg-purple-50", iconBg: "bg-purple-100" },
    { color: "from-rose-500 to-rose-600", bgColor: "bg-rose-50", iconBg: "bg-rose-100" },
  ];

  const categoryDataList = (categoriesData?.data as TenderCategory[]) || [];
  const sortedNames = sortCategories(categoryDataList.map((c) => c.name));

  const categories = sortedNames.map((name, index) => {
    const original = categoryDataList.find((c) => c.name === name);
    const theme = colorThemes[index % colorThemes.length];

    return {
      icon: iconMap[name] || "📄",
      title: name,
      description: original?.description || "Find tenders in this category",
      count: original?.tenderCount || original?.tenders?.length || 0,
      ...theme,
      tag: name.split(" ")[0], // Simple tag derivation
    };
  });

  const filteredCategories = categories.filter((category) =>
    category.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
    category.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
    category.tag.toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-green-50/30 overflow-x-hidden w-full max-w-full">
      <Header />

      {/* Hero Section */}
      <section className="relative pt-24 sm:pt-28 pb-12 overflow-hidden">
        {/* Background Pattern */}
        <div className="absolute inset-0 opacity-5">
          <div className="absolute inset-0" style={{
            backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23000000' fill-opacity='1'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
          }}></div>
        </div>

        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
          <motion.div
            initial={{ opacity: 0, y: 30 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.8 }}
            className="text-center mb-8"
          >
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="inline-block mb-4"
            >
              <span className="px-4 py-2 bg-green-100 text-green-700 rounded-full text-sm font-semibold">
                Explore Opportunities
              </span>
            </motion.div>
            <h1 className="text-4xl sm:text-5xl lg:text-6xl font-bold text-gray-900 mb-4 bg-clip-text text-transparent bg-gradient-to-r from-gray-900 via-green-700 to-gray-900">
              Tender Categories
            </h1>
            <p className="text-lg sm:text-xl text-gray-600 max-w-3xl mx-auto leading-relaxed">
              Discover solar energy tenders across multiple categories. Find opportunities that match your expertise and business needs.
            </p>
          </motion.div>

          {/* Search Bar */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="max-w-2xl mx-auto mb-12"
          >
            <div className="relative">
              <input
                type="text"
                placeholder="Search categories..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full px-6 py-4 pl-14 bg-white/80 backdrop-blur-sm border-2 border-gray-200 rounded-2xl shadow-lg focus:outline-none focus:border-green-500 focus:ring-4 focus:ring-green-500/20 transition-all text-gray-900 text-lg"
              />
              <div className="absolute left-5 top-1/2 -translate-y-1/2">
                <svg className="w-6 h-6 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </div>
              {searchQuery && (
                <button
                  onClick={() => setSearchQuery("")}
                  className="absolute right-4 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              )}
            </div>
          </motion.div>
        </div>
      </section>

      {/* Categories Grid */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 sm:pb-20">
        <AnimatePresence mode="wait">
          {filteredCategories.length === 0 ? (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="text-center py-16"
            >
              <div className="text-6xl mb-4">🔍</div>
              <p className="text-xl text-gray-600">No categories found matching your search.</p>
            </motion.div>
          ) : (
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6 lg:gap-8"
            >
              {filteredCategories.map((category, index) => (
                <motion.div
                  key={category.title}
                  initial={{ opacity: 0, y: 30, scale: 0.9 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.9 }}
                  transition={{
                    delay: index * 0.1,
                    type: "spring",
                    stiffness: 100,
                    damping: 15
                  }}
                  whileHover={{
                    y: -8,
                    scale: 1.02,
                    transition: { duration: 0.2 }
                  }}
                  whileTap={{ scale: 0.98 }}
                  className="group relative"
                >
                  <div className="relative h-full bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 overflow-hidden border border-gray-100">
                    {/* Gradient Background */}
                    <div className={`absolute inset-0 bg-gradient-to-br ${category.color} opacity-0 group-hover:opacity-5 transition-opacity duration-300`}></div>

                    {/* Content */}
                    <div className="relative p-6">
                      {/* Icon */}
                      <motion.div
                        whileHover={{ rotate: [0, -10, 10, -10, 0], scale: 1.1 }}
                        transition={{ duration: 0.5 }}
                        className={`inline-flex items-center justify-center w-16 h-16 ${category.iconBg} rounded-2xl mb-4 group-hover:scale-110 transition-transform duration-300`}
                      >
                        <span className="text-3xl">{category.icon}</span>
                      </motion.div>

                      {/* Tag */}
                      <div className="mb-3">
                        <span className={`inline-block px-3 py-1 text-xs font-semibold rounded-full ${category.bgColor} text-gray-700`}>
                          {category.tag}
                        </span>
                      </div>

                      {/* Title */}
                      <h3 className="text-xl font-bold text-gray-900 mb-2 group-hover:text-green-600 transition-colors">
                        {category.title}
                      </h3>

                      {/* Count Badge */}
                      <div className="flex items-center gap-2 mb-4">
                        <div className={`h-2 w-2 rounded-full bg-gradient-to-r ${category.color}`}></div>
                        <span className="text-sm font-semibold text-gray-600">{category.count} Active Tenders</span>
                      </div>

                      {/* Description */}
                      <p className="text-gray-600 mb-6 leading-relaxed text-sm line-clamp-3">
                        {category.description}
                      </p>

                      {/* Button */}
                      <Link href="/tenders">
                        <motion.button
                          whileHover={{ scale: 1.05 }}
                          whileTap={{ scale: 0.95 }}
                          className={`w-full px-4 py-3 bg-gradient-to-r ${category.color} text-white rounded-xl font-semibold shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center gap-2 group/btn`}
                        >
                          <span>View Tenders</span>
                          <motion.svg
                            className="w-5 h-5"
                            fill="none"
                            stroke="currentColor"
                            viewBox="0 0 24 24"
                            initial={{ x: 0 }}
                            whileHover={{ x: 5 }}
                            transition={{ type: "spring", stiffness: 400, damping: 17 }}
                          >
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 7l5 5m0 0l-5 5m5-5H6" />
                          </motion.svg>
                        </motion.button>
                      </Link>
                    </div>

                    {/* Decorative Corner */}
                    <div className={`absolute top-0 right-0 w-24 h-24 bg-gradient-to-br ${category.color} opacity-0 group-hover:opacity-10 transition-opacity duration-300 rounded-bl-full`}></div>
                  </div>
                </motion.div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>

        {/* Stats Section */}
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true }}
          transition={{ delay: 0.5 }}
          className="mt-16 bg-gradient-to-r from-green-600 to-green-700 rounded-3xl p-8 sm:p-12 text-white shadow-2xl"
        >
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-8 text-center">
            <div>
              <div className="text-4xl sm:text-5xl font-bold mb-2">1,260+</div>
              <div className="text-green-100 text-lg">Total Tenders</div>
            </div>
            <div>
              <div className="text-4xl sm:text-5xl font-bold mb-2">12</div>
              <div className="text-green-100 text-lg">Categories</div>
            </div>
            <div>
              <div className="text-4xl sm:text-5xl font-bold mb-2">36</div>
              <div className="text-green-100 text-lg">Districts Covered</div>
            </div>
          </div>
        </motion.div>
      </main>

      <Footer />
    </div>
  );
}

