"use client";

import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { motion } from "framer-motion";
import { ArrowRight, ExternalLink } from "lucide-react";
// import Banner from "@/components/banner";
import Pagination from "@/components/pagination";
import LoadingSpinner from "@/components/loading-spinner";
import { getProjectCategories } from "@/lib/api";
import Image from "next/image";

interface ProjectCategory {
  id: string;
  name: string;
  slug: string;
  description: string;
  image: string | null;
}

interface PaginationMeta {
  current_page: number;
  per_page: number;
  total: number;
  last_page: number;
}

export default function ProjectsPage() {
  const searchParams = useSearchParams();
  const page = Number.parseInt(searchParams.get("page") || "1");
  const perPage = 9; // Number of categories per page

  const [categories, setCategories] = useState<ProjectCategory[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        setLoading(true);
        const response = await getProjectCategories(page, perPage);
        setCategories(response.data);
        setMeta(response.meta);
        setError(null);
      } catch (err) {
        setError("Failed to load project categories. Please try again later.");
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchCategories();
  }, [page, perPage]);

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1,
      },
    },
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: {
        type: "spring",
        stiffness: 100,
        damping: 12,
      },
    },
  };

  const getColorForCategory = (index: number) => {
    const colors = [
      "from-orange-500 to-red-500",
      "from-blue-500 to-indigo-600",
      "from-emerald-500 to-teal-600",
      "from-purple-500 to-pink-500",
      "from-amber-500 to-yellow-500",
      "from-cyan-500 to-blue-500",
      "from-rose-500 to-red-600",
    ];
    return colors[index % colors.length];
  };

  return (
    <div className="pb-16 min-h-screen">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
          className="text-center mb-16 pt-12"
        >
          <h1 className="text-4xl font-bold text-gray-900 sm:text-5xl">
            Our Projects
          </h1>
          <div className="w-24 h-1 bg-gradient-to-r from-orange-500 to-red-500 mx-auto my-6 rounded-full"></div>
          <p className="mt-4 text-xl text-gray-600 max-w-3xl mx-auto">
            Explore our extensive portfolio of electrical projects across
            various industries and sectors
          </p>
        </motion.div>

        {loading ? (
          <LoadingSpinner />
        ) : error ? (
          <div className="text-center py-12">
            <div className="bg-red-50 p-6 rounded-lg max-w-2xl mx-auto">
              <h3 className="text-lg font-medium text-red-800 mb-2">
                Error Loading Categories
              </h3>
              <p className="text-red-700">{error}</p>
              <button
                onClick={() => window.location.reload()}
                className="mt-4 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
              >
                Try Again
              </button>
            </div>
          </div>
        ) : categories.length === 0 ? (
          <div className="text-center py-12">
            <div className="bg-orange-50 p-6 rounded-lg max-w-2xl mx-auto">
              <h3 className="text-lg font-medium text-orange-800 mb-2">
                No Project Categories Found
              </h3>
              <p className="text-orange-700">
                There are currently no project categories available.
              </p>
            </div>
          </div>
        ) : (
          <>
            <motion.div
              variants={containerVariants}
              initial="hidden"
              animate="visible"
              className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"
            >
              {categories.map((category, index) => (
                <motion.div
                  key={category.id}
                  variants={itemVariants}
                  whileHover={{
                    y: -8,
                    transition: { duration: 0.2 },
                  }}
                  className="group h-full"
                >
                  <div className="relative h-full overflow-hidden backdrop-blur-sm bg-white/80 rounded-xl shadow-md border border-gray-100 transition-all duration-300 hover:shadow-xl">
                    {/* Decorative gradient bar */}
                    <div
                      className={`h-2 w-full bg-gradient-to-r from-red-700 to-orange-500`}
                    ></div>

                    {/* Card content */}
                    <div className="p-6 h-full flex flex-col">
                      <div className="flex items-start justify-between mb-4">
                        <div
                          className={`w-14 h-14 rounded-lg flex items-center justify-center bg-gradient-to-r from-red-700 to-orange-500 text-white shadow-md`}
                        >
                          {category.image ? (
                            <Image
                              src={
                                `${process.env.NEXT_PUBLIC_API_URL}/storage/${category.image}` ||
                                "/placeholder.svg"
                              }
                              alt={category.name}
                              width={40}
                              height={40}
                              className="object-cover rounded-lg"
                            />
                          ) : (
                            <span className="text-2xl font-bold">
                              {category.name.charAt(0)}
                            </span>
                          )}
                        </div>

                        <motion.div
                          initial={{ opacity: 0.5, scale: 0.8 }}
                          whileHover={{
                            opacity: 1,
                            scale: 1.1,
                            rotate: 5,
                            transition: { duration: 0.2 },
                          }}
                          className="w-8 h-8 flex items-center justify-center rounded-full bg-gray-50 text-gray-400 group-hover:text-gray-600"
                        >
                          <ExternalLink size={14} />
                        </motion.div>
                      </div>

                      <h3 className="text-xl font-semibold text-gray-900 mb-2 group-hover:text-orange-600 transition-colors">
                        {category.name}
                      </h3>

                      <p className="text-gray-600 flex-grow mb-4">
                        {category.description}
                      </p>

                      <div className="mt-auto">
                        <Link
                          href={`/projects/${category.slug}`}
                          className="inline-flex items-center text-sm font-medium text-orange-600 group-hover:text-orange-700"
                        >
                          <motion.div
                            whileHover={{ x: 5 }}
                            className="flex items-center"
                          >
                            View Projects
                            <ArrowRight
                              size={16}
                              className="ml-1 opacity-0 group-hover:opacity-100 transition-opacity"
                            />
                          </motion.div>
                        </Link>
                      </div>
                    </div>

                    {/* Decorative corner accent */}
                    <div
                      className={`absolute -bottom-6 -right-6 w-12 h-12 rounded-full bg-gradient-to-br ${getColorForCategory(
                        index,
                      )} opacity-20`}
                    ></div>
                  </div>
                </motion.div>
              ))}
            </motion.div>

            {meta && (
              <Pagination
                currentPage={meta.current_page}
                lastPage={meta.last_page}
                perPage={meta.per_page}
                total={meta.total}
                baseUrl="/projects"
              />
            )}
          </>
        )}
      </div>
    </div>
  );
}
