// "use client";

// import { useEffect, useState } from "react";
// import { useRouter, usePathname, useSearchParams } from "next/navigation";
// import Link from "next/link";
// import { ChevronLeft, ArrowRight, ExternalLink } from "lucide-react";
// import { motion } from "framer-motion";
// import LoadingSpinner from "@/components/loading-spinner";
// import Pagination from "@/components/pagination";
// import { getProjectsByCategory } from "@/lib/api";
// import Image from "next/image";
// import truncate from "html-truncate";

// interface Project {
//   id: string;
//   name: string;
//   description: string;
//   category_id: string;
//   image?: string;
//   images?: { id: string; url: string }[];
// }

// interface ProjectCategory {
//   id: string;
//   name: string;
//   slug: string;
//   description: string;
//   image?: string;
// }

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

// interface ProjectCategoryContentProps {
//   category: ProjectCategory;
//   categoryId: string;
//   initialPage: number;
// }

// export default function ProjectCategoryContent({
//   category,
//   categoryId,
//   initialPage,
// }: ProjectCategoryContentProps) {
//   const router = useRouter();
//   const pathname = usePathname();
//   const searchParams = useSearchParams();

//   const [projects, setProjects] = useState<Project[]>([]);
//   const [meta, setMeta] = useState<PaginationMeta | null>(null);
//   const [loading, setLoading] = useState(true);
//   const [error, setError] = useState<string | null>(null);
//   const [currentPage, setCurrentPage] = useState(initialPage);

//   const truncateText = (html: string, maxLength: number) => {
//     return truncate(html, maxLength);
//   };
//   console.log(projects, setCurrentPage);

//   useEffect(() => {
//     const fetchProjects = async () => {
//       try {
//         setLoading(true);
//         const response = await getProjectsByCategory(
//           categoryId,
//           currentPage,
//           9,
//         );
//         setProjects(response.data);
//         setMeta(response.meta);
//         setError(null);
//       } catch (err) {
//         setError("Failed to load projects. Please try again later.");
//         console.error(err);
//       } finally {
//         setLoading(false);
//       }
//     };

//     fetchProjects();
//   }, [categoryId, currentPage]);

//   // Update URL when page changes
//   useEffect(() => {
//     const params = new URLSearchParams(searchParams);
//     if (currentPage === 1) {
//       params.delete("page");
//     } else {
//       params.set("page", currentPage.toString());
//     }

//     const newUrl = `${pathname}${params.toString() ? `?${params.toString()}` : ""}`;
//     router.replace(newUrl, { scroll: false });
//   }, [currentPage, pathname, router, searchParams]);

//   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,
//       },
//     },
//   };

//   // Function to get a gradient based on index
//   const getGradient = (index: number) => {
//     const gradients = [
//       "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",
//     ];
//     return gradients[index % gradients.length];
//   };

//   // Get project image
//   const getProjectImage = (project: Project) => {
//     if (project.image) {
//       return project.image;
//     } else if (project.images && project.images.length > 0) {
//       return project.images[0].url;
//     }
//     return null;
//   };

//   return (
//     <div className="pb-16 min-h-screen bg-gradient-to-b from-white to-gray-50">
//       <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//         <motion.div
//           initial={{ opacity: 0, x: -20 }}
//           animate={{ opacity: 1, x: 0 }}
//           transition={{ duration: 0.5 }}
//           className="mb-8 pt-8"
//         >
//           <Link
//             href="/projects"
//             className="inline-flex items-center text-orange-600 hover:text-orange-800 transition-colors group"
//           >
//             <motion.div whileHover={{ x: -3 }} whileTap={{ scale: 0.95 }}>
//               <ChevronLeft className="mr-1 h-5 w-5 group-hover:mr-2 transition-all" />
//             </motion.div>
//             <span>Back to All Projects</span>
//           </Link>
//         </motion.div>

//         <motion.div
//           initial={{ opacity: 0, y: 20 }}
//           animate={{ opacity: 1, y: 0 }}
//           transition={{ duration: 0.6 }}
//           className="mb-16 relative"
//         >
//           <div className="absolute inset-0 bg-gradient-to-r from-orange-500 to-red-500 opacity-10 rounded-xl transform -rotate-1"></div>
//           <div className="relative backdrop-blur-sm bg-white/80 p-8 rounded-xl shadow-lg border border-orange-100">
//             <div className="flex flex-col md:flex-row md:items-center gap-6">
//               {category.image && (
//                 <div className="flex-shrink-0">
//                   <div className="w-20 h-20 rounded-lg overflow-hidden shadow-md border-2 border-orange-100">
//                     <Image
//                       src={category.image || "/placeholder.svg"}
//                       alt={category.name}
//                       width={80}
//                       height={80}
//                       className="w-full h-full object-cover"
//                     />
//                   </div>
//                 </div>
//               )}

//               <div>
//                 <h1 className="text-3xl font-bold text-gray-900 sm:text-4xl">
//                   {category.name}
//                 </h1>
//                 <div className="w-20 h-1 bg-gradient-to-r from-orange-500 to-red-500 my-4 rounded-full"></div>
//                 <p className="text-lg text-gray-600 max-w-3xl">
//                   {category.description}
//                 </p>
//                 {meta && (
//                   <div className="mt-4 flex items-center text-sm text-gray-500">
//                     <span className="font-medium text-orange-600 mr-2">
//                       {meta.total}
//                     </span>
//                     projects in this category
//                   </div>
//                 )}
//               </div>
//             </div>
//           </div>
//         </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 Projects
//               </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>
//         ) : projects.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 Projects Found
//               </h3>
//               <p className="text-orange-700">
//                 There are currently no projects in this category.
//               </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"
//             >
//               {projects.map((project, index) => {
//                 const projectImage = getProjectImage(project);

//                 return (
//                   <motion.div
//                     key={project.id}
//                     variants={itemVariants}
//                     whileHover={{
//                       y: -8,
//                       transition: { duration: 0.2 },
//                     }}
//                     className="group h-full"
//                   >
//                     <Link
//                       href={`/projects/${categoryId}/${project.id}`}
//                       className="block 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">
//                         {/* Project Image */}
//                         {projectImage ? (
//                           <div className="w-full h-48 relative overflow-hidden">
//                             <Image
//                               src={projectImage || "/placeholder.svg"}
//                               alt={project.name}
//                               fill
//                               className="object-cover transition-transform group-hover:scale-105"
//                               sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
//                             />
//                             <div
//                               className={`absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity`}
//                             ></div>
//                           </div>
//                         ) : (
//                           <div
//                             className={`h-2 w-full bg-gradient-to-r ${getGradient(index)}`}
//                           ></div>
//                         )}

//                         {/* Card content */}
//                         <div className="p-6 h-full flex flex-col">
//                           {!projectImage && (
//                             <div className="flex items-start justify-between mb-4">
//                               <div
//                                 className={`w-12 h-12 rounded-lg flex items-center justify-center bg-gradient-to-br ${getGradient(
//                                   index,
//                                 )} text-white shadow-md overflow-hidden`}
//                               >
//                                 <span className="text-lg font-bold">
//                                   {project.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">
//                             {project.name}
//                           </h3>

//                           <div
//                             className="text-gray-600 flex-grow mb-4 leading-relaxed break-words"
//                             style={{
//                               WebkitBoxOrient: "vertical",
//                             }}
//                             dangerouslySetInnerHTML={{
//                               __html: truncateText(project.description, 120),
//                             }}
//                           />

//                           <div className="mt-auto">
//                             <motion.div
//                               whileHover={{ x: 5 }}
//                               className="flex items-center text-sm font-medium text-orange-600 group-hover:text-orange-700"
//                             >
//                               View project details
//                               <ArrowRight
//                                 size={16}
//                                 className="ml-1 opacity-0 group-hover:opacity-100 transition-opacity"
//                               />
//                             </motion.div>
//                           </div>
//                         </div>

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

//             {meta && (
//               <Pagination
//                 currentPage={meta.current_page}
//                 lastPage={meta.last_page}
//                 perPage={meta.per_page}
//                 total={meta.total}
//                 baseUrl={`/projects/${categoryId}`}
//               />
//             )}
//           </>
//         )}

//         <motion.div
//           initial={{ opacity: 0 }}
//           animate={{ opacity: 1 }}
//           transition={{ delay: 0.8, duration: 0.5 }}
//           className="mt-16 text-center"
//         >
//           <Link href="/projects">
//             <motion.button
//               whileHover={{
//                 scale: 1.05,
//                 boxShadow: "0 10px 25px -5px rgba(249, 115, 22, 0.4)",
//               }}
//               whileTap={{ scale: 0.95 }}
//               className="px-6 py-3 bg-gradient-to-r from-orange-500 to-red-500 text-white font-medium rounded-lg shadow-md hover:shadow-lg transition-all"
//             >
//               Explore More Project Categories
//             </motion.button>
//           </Link>
//         </motion.div>
//       </div>
//     </div>
//   );
// }

"use client";

import { useEffect, useState } from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";
import Link from "next/link";
import { ChevronLeft, ArrowRight, ExternalLink } from "lucide-react";
import { motion } from "framer-motion";
import LoadingSpinner from "@/components/loading-spinner";
import Pagination from "./pagination";
import { getProjectCategory } from "@/lib/api";
import Image from "next/image";
import truncate from "html-truncate";

interface Project {
  id: string;
  name: string;
  description: string;
  category_id: string;
  image?: string;
  images?: { id: string; url: string }[];
}

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

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

interface ProjectCategoryContentProps {
  category: ProjectCategory;
  categoryId: string;
  initialPage: number;
  params: string;
}

export default function ProjectCategoryContent({
  category,
  categoryId,
  initialPage,
  params,
}: ProjectCategoryContentProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const [projects, setProjects] = useState<Project[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState(initialPage);

  const truncateText = (html: string, maxLength: number) => {
    return truncate(html, maxLength);
  };
  // Remove debug console.log

  useEffect(() => {
    const fetchProjects = async () => {
      try {
        setLoading(true);
        const response = await getProjectCategory(params, currentPage, 9);
        console.log(response.data);
        setProjects(response.data);
        setMeta(response.meta);
        setError(null);
      } catch (err) {
        setError("Failed to load projects. Please try again later.");
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, [categoryId, currentPage]);

  // Update URL when page changes
  useEffect(() => {
    const params = new URLSearchParams(searchParams);
    if (currentPage === 1) {
      params.delete("page");
    } else {
      params.set("page", currentPage.toString());
    }

    const newUrl = `${pathname}${params.toString() ? `?${params.toString()}` : ""}`;
    router.replace(newUrl, { scroll: false });
  }, [currentPage, pathname, router, searchParams]);

  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,
      },
    },
  };

  // Function to get a gradient based on index
  const getGradient = (index: number) => {
    const gradients = [
      "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",
    ];
    return gradients[index % gradients.length];
  };

  // Get project image
  const getProjectImage = (project: Project) => {
    if (project.image) {
      return project.image;
    } else if (project.images && project.images.length > 0) {
      return project.images[0].url;
    }
    return null;
  };

  return (
    <div className="pb-16 min-h-screen bg-gradient-to-b from-white to-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          transition={{ duration: 0.5 }}
          className="mb-8 pt-8"
        >
          <Link
            href="/projects"
            className="inline-flex items-center text-orange-600 hover:text-orange-800 transition-colors group"
          >
            <motion.div whileHover={{ x: -3 }} whileTap={{ scale: 0.95 }}>
              <ChevronLeft className="mr-1 h-5 w-5 group-hover:mr-2 transition-all" />
            </motion.div>
            <span>Back to All Projects</span>
          </Link>
        </motion.div>

        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
          className="mb-16 relative"
        >
          <div className="absolute inset-0 bg-gradient-to-r from-orange-500 to-red-500 opacity-10 rounded-xl transform -rotate-1"></div>
          <div className="relative backdrop-blur-sm bg-white/80 p-8 rounded-xl shadow-lg border border-orange-100">
            <div className="flex flex-col md:flex-row md:items-center gap-6">
              {category.image && (
                <div className="flex-shrink-0">
                  <div className="w-20 h-20 rounded-lg overflow-hidden shadow-md border-2 border-orange-100">
                    <Image
                      src={category.image || "/placeholder.svg"}
                      alt={category.name}
                      width={80}
                      height={80}
                      className="w-full h-full object-cover"
                    />
                  </div>
                </div>
              )}

              <div>
                <h1 className="text-3xl font-bold text-gray-900 sm:text-4xl">
                  {category.name}
                </h1>
                <div className="w-20 h-1 bg-gradient-to-r from-orange-500 to-red-500 my-4 rounded-full"></div>
                <p className="text-lg text-gray-600 max-w-3xl">
                  {category.description}
                </p>
                {meta && (
                  <div className="mt-4 flex items-center text-sm text-gray-500">
                    <span className="font-medium text-orange-600 mr-2">
                      {meta.total}
                    </span>
                    projects in this category
                  </div>
                )}
              </div>
            </div>
          </div>
        </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 Projects
              </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>
        ) : projects.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 Projects Found
              </h3>
              <p className="text-orange-700">
                There are currently no projects in this category.
              </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"
            >
              {projects.map((project, index) => {
                const projectImage = getProjectImage(project);

                return (
                  <motion.div
                    key={project.id}
                    variants={itemVariants}
                    whileHover={{
                      y: -8,
                      transition: { duration: 0.2 },
                    }}
                    className="group h-full"
                  >
                    <Link
                      href={`/projects/${categoryId}/${project.id}`}
                      className="block 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">
                        {/* Project Image */}
                        {projectImage ? (
                          <div className="w-full h-48 relative overflow-hidden">
                            <Image
                              src={projectImage || "/placeholder.svg"}
                              alt={project.name}
                              fill
                              className="object-cover transition-transform group-hover:scale-105"
                              sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
                            />
                            <div
                              className={`absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity`}
                            ></div>
                          </div>
                        ) : (
                          <div
                            className={`h-2 w-full bg-gradient-to-r ${getGradient(index)}`}
                          ></div>
                        )}

                        {/* Card content */}
                        <div className="p-6 h-full flex flex-col">
                          {!projectImage && (
                            <div className="flex items-start justify-between mb-4">
                              <div
                                className={`w-12 h-12 rounded-lg flex items-center justify-center bg-gradient-to-br ${getGradient(
                                  index,
                                )} text-white shadow-md overflow-hidden`}
                              >
                                <span className="text-lg font-bold">
                                  {project.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">
                            {project.name}
                          </h3>

                          <div
                            className="text-gray-600 flex-grow mb-4 leading-relaxed break-words"
                            style={{
                              WebkitBoxOrient: "vertical",
                            }}
                            dangerouslySetInnerHTML={{
                              __html: truncateText(project.description, 120),
                            }}
                          />

                          <div className="mt-auto">
                            <motion.div
                              whileHover={{ x: 5 }}
                              className="flex items-center text-sm font-medium text-orange-600 group-hover:text-orange-700"
                            >
                              View project details
                              <ArrowRight
                                size={16}
                                className="ml-1 opacity-0 group-hover:opacity-100 transition-opacity"
                              />
                            </motion.div>
                          </div>
                        </div>

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

            {meta && (
              <Pagination
                currentPage={meta.current_page}
                lastPage={meta.last_page}
                perPage={meta.per_page}
                total={meta.total}
                baseUrl={`/projects/${categoryId}`}
                onPageChange={(page) => setCurrentPage(page)}
              />
            )}
          </>
        )}

        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.8, duration: 0.5 }}
          className="mt-16 text-center"
        >
          <Link href="/projects">
            <motion.button
              whileHover={{
                scale: 1.05,
                boxShadow: "0 10px 25px -5px rgba(249, 115, 22, 0.4)",
              }}
              whileTap={{ scale: 0.95 }}
              className="px-6 py-3 bg-gradient-to-r from-orange-500 to-red-500 text-white font-medium rounded-lg shadow-md hover:shadow-lg transition-all"
            >
              Explore More Project Categories
            </motion.button>
          </Link>
        </motion.div>
      </div>
    </div>
  );
}
