"use client";

import { Fragment, useEffect, useState } from "react";
import { Popover, PopoverPanel, Transition } from "@headlessui/react";
import { motion } from "framer-motion";
import { ChevronDown, ChevronRight } from "lucide-react";
// import { products } from "./data";
import { usePathname } from "next/navigation";
import Link from "next/link";
import { getProjectCategories, getServices } from "@/lib/api";
import { Spinner } from "../animation/spinner";

interface DesktopNavProps {
  isScrolled: boolean;
  activeSection?: string;
}

export function DesktopNav({ isScrolled }: DesktopNavProps) {
  const pathname = usePathname();

  return (
    <div className="hidden md:flex space-x-8">
      <NavLink href="/" isScrolled={isScrolled} isActive={pathname === "/"}>
        Home
      </NavLink>
      <NavLink
        href="/about"
        isScrolled={isScrolled}
        isActive={pathname === "/about"}
      >
        About
      </NavLink>
      {/* <ProductsMenu
        isScrolled={isScrolled}
        isActive={pathname === "/products"}
      /> */}
      <NavLink
        href="/products"
        isScrolled={isScrolled}
        isActive={pathname === "/products"}
      >
        Products
      </NavLink>
      <ServicesMenu
        isScrolled={isScrolled}
        isActive={pathname === "/services"}
      />
      <ProjectsMenu
        isScrolled={isScrolled}
        isActive={pathname.startsWith("/projects")}
      />
      <NavLink
        href="/blogs"
        isScrolled={isScrolled}
        isActive={pathname === "/blogs"}
      >
        Blogs
      </NavLink>
    </div>
  );
}

interface NavLinkProps {
  href: string;
  isScrolled: boolean;
  isActive: boolean;
  children: React.ReactNode;
}

function NavLink({ href, isActive, children }: NavLinkProps) {
  return (
    <Link
      href={href}
      className={`relative transition-colors ${"text-gray-900 hover:text-orange-600"} ${isActive ? "font-medium" : ""}`}
    >
      {children}
      {isActive && (
        <motion.div
          layoutId="activeSection"
          className={`absolute -bottom-1 left-0 right-0 h-0.5 ${"bg-orange-600"}`}
          transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
        />
      )}
    </Link>
  );
}

interface MenuButtonProps {
  isScrolled: boolean;
  isActive: boolean;
  isOpen: boolean;
  children: React.ReactNode;
}

function MenuButton({
  isScrolled,
  isActive,
  isOpen,
  children,
}: MenuButtonProps) {
  return (
    <Popover.Button
      className={`
        group inline-flex items-center text-base font-medium focus:outline-none
        ${isOpen ? "text-orange-600" : "text-gray-900 hover:text-orange-600"}
        ${isActive ? "font-medium" : ""}
      `}
    >
      <span>{children}</span>
      <ChevronDown
        className={`ml-2 h-5 w-5 transition-colors ${
          isOpen ? "text-orange-600" : "group-hover:text-orange-400"
        }`}
        aria-hidden="true"
      />
      {isActive && (
        <motion.div
          layoutId="activeSection"
          className={`absolute -bottom-1 left-0 right-0 h-0.5 ${
            isScrolled ? "bg-orange-600" : "bg-white"
          }`}
          transition={{ type: "spring", bounce: 0.2, duration: 0.6 }}
        />
      )}
    </Popover.Button>
  );
}

// function ProductsMenu({
//   isScrolled,
//   isActive,
// }: {
//   isScrolled: boolean;
//   isActive: boolean;
// }) {
//   return (
//     <Popover className="relative">
//       {({ open }) => (
//         <>
//           <MenuButton isScrolled={isScrolled} isActive={isActive} isOpen={open}>
//             Products
//           </MenuButton>

//           <Transition
//             as={Fragment}
//             enter="transition ease-out duration-200"
//             enterFrom="opacity-0 -translate-y-1"
//             enterTo="opacity-100 translate-y-0"
//             leave="transition ease-in duration-150"
//             leaveFrom="opacity-100 translate-y-0"
//             leaveTo="opacity-0 -translate-y-1"
//           >
//             <PopoverPanel className="fixed left-0 right-0 z-40 mt-3">
//               <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//                 <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
//                   <div className="relative grid grid-cols-3 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
//                     {products.categories.map((category) => (
//                       <div key={category.name}>
//                         <h3 className="text-base font-medium text-gray-900 mb-4">
//                           {category.name}
//                         </h3>
//                         <ul className="space-y-4">
//                           {category.items.map((item) => (
//                             <li key={item.name}>
//                               <a
//                                 href={item.href}
//                                 className="group flex items-start space-x-3"
//                               >
//                                 <ChevronRight className="h-5 w-5 text-orange-600 group-hover:text-orange-800" />
//                                 <div>
//                                   <p className="text-base font-medium text-gray-900 group-hover:text-orange-600">
//                                     {item.name}
//                                   </p>
//                                   <p className="mt-1 text-sm text-gray-500 group-hover:text-gray-900">
//                                     {item.description}
//                                   </p>
//                                 </div>
//                               </a>
//                             </li>
//                           ))}
//                         </ul>
//                       </div>
//                     ))}
//                   </div>
//                 </div>
//               </div>
//             </PopoverPanel>
//           </Transition>
//         </>
//       )}
//     </Popover>
//   );
// }

interface Service {
  id: number;
  name: string;
  description: string;
  banner: string;
}

function ServicesMenu({
  isScrolled,
  isActive,
}: {
  isScrolled: boolean;
  isActive: boolean;
}) {
  const [services, setServices] = useState<Service[] | undefined>(undefined);

  function truncateText(
    text: string,
    maxLength: number,
    ellipsis: string = "...",
  ): string {
    // Check if the text is already shorter than the max length
    if (text.length <= maxLength) {
      return text;
    }

    // Truncate the text and add the ellipsis
    return text.slice(0, maxLength) + ellipsis;
  }
  useEffect(() => {
    async function fetchServices() {
      const resp = await getServices();
      setServices(resp[0].services);
    }
    fetchServices();
  }, []);
  return (
    <Popover className="relative">
      {({ open }) => (
        <>
          <MenuButton isScrolled={isScrolled} isActive={isActive} isOpen={open}>
            Services
          </MenuButton>

          <Transition
            as={Fragment}
            enter="transition ease-out duration-200"
            enterFrom="opacity-0 -translate-y-1"
            enterTo="opacity-100 translate-y-0"
            leave="transition ease-in duration-150"
            leaveFrom="opacity-100 translate-y-0"
            leaveTo="opacity-0 -translate-y-1"
          >
            <PopoverPanel className="fixed left-0 right-0 z-40 mt-3">
              <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
                  <div className="relative grid grid-cols-3 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
                    {services && services.length > 0 ? (
                      services.map((service) => (
                        <Link
                          key={service.name}
                          href={`/services/${service.id.toString()}`}
                          className="group flex items-start space-x-3 p-4 hover:bg-gray-50 rounded-lg transition-colors"
                        >
                          <ChevronRight className="h-5 w-5 text-orange-600 group-hover:text-orange-800" />
                          <div>
                            <p className="text-base font-medium text-gray-900 group-hover:text-orange-600">
                              {service.name}
                            </p>
                            <p className="mt-1 text-sm text-gray-500 group-hover:text-gray-900">
                              {truncateText(service.description, 70)}
                            </p>
                          </div>
                        </Link>
                      ))
                    ) : (
                      <>
                        <Spinner />
                        <Spinner />
                        <Spinner />
                      </>
                    )}
                  </div>
                </div>
              </div>
            </PopoverPanel>
          </Transition>
        </>
      )}
    </Popover>
  );
}

interface ProjectMenuProps {
  name: string;
  description: string;
  slug: string;
}

function ProjectsMenu({
  isScrolled,
  isActive,
}: {
  isScrolled: boolean;
  isActive: boolean;
}) {
  const [projects, setProjects] = useState<ProjectMenuProps[] | undefined>(
    undefined,
  );
  useEffect(() => {
    const fetchProjects = async () => {
      const response = await getProjectCategories(1, 8);
      setProjects(response.data);
    };
    fetchProjects();
  }, []);
  console.log(projects);
  return (
    <Popover className="relative">
      {({ open }) => (
        <>
          <MenuButton isScrolled={isScrolled} isActive={isActive} isOpen={open}>
            Projects
          </MenuButton>

          <Transition
            as={Fragment}
            enter="transition ease-out duration-200"
            enterFrom="opacity-0 -translate-y-1"
            enterTo="opacity-100 translate-y-0"
            leave="transition ease-in duration-150"
            leaveFrom="opacity-100 translate-y-0"
            leaveTo="opacity-0 -translate-y-1"
          >
            <PopoverPanel className="fixed left-0 right-0 z-40 mt-3">
              <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
                  <div className="relative grid grid-cols-2 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
                    {projects && projects.length !== 0 ? (
                      projects.map((project) => (
                        <Link
                          key={project.name}
                          href={`/projects/${project.slug}`}
                          className="group flex items-start space-x-3 p-4 hover:bg-gray-50 rounded-lg transition-colors"
                        >
                          <ChevronRight className="h-5 w-5 text-orange-600 group-hover:text-orange-800" />
                          <div>
                            <p className="text-base font-medium text-gray-900 group-hover:text-orange-600">
                              {project.name}
                            </p>
                            <p className="mt-1 text-sm text-gray-500 group-hover:text-gray-900">
                              {project.description}
                            </p>
                          </div>
                        </Link>
                      ))
                    ) : (
                      <>
                        <Spinner />
                        <Spinner />
                      </>
                    )}

                    <Link
                      href={"/projects"}
                      className="group flex items-start space-x-3 p-4 hover:bg-gray-50 rounded-lg transition-colors"
                    >
                      <ChevronRight className="h-5 w-5 text-orange-600 group-hover:text-orange-800" />
                      <div>
                        <p className="text-base font-medium text-gray-900 group-hover:text-orange-600">
                          All Projects
                        </p>
                        <p className="mt-1 text-sm text-gray-500 group-hover:text-gray-900">
                          View all projects
                        </p>
                      </div>
                    </Link>
                  </div>
                </div>
              </div>
            </PopoverPanel>
          </Transition>
        </>
      )}
    </Popover>
  );
}

// function BlogsMenu({
//   isScrolled,
//   isActive,
// }: {
//   isScrolled: boolean;
//   isActive: boolean;
// }) {
//   return (
//     <Popover className="relative">
//       {({ open }) => (
//         <>
//           <MenuButton isScrolled={isScrolled} isActive={isActive} isOpen={open}>
//             Blogs
//           </MenuButton>

//           <Transition
//             as={Fragment}
//             enter="transition ease-out duration-200"
//             enterFrom="opacity-0 -translate-y-1"
//             enterTo="opacity-100 translate-y-0"
//             leave="transition ease-in duration-150"
//             leaveFrom="opacity-100 translate-y-0"
//             leaveTo="opacity-0 -translate-y-1"
//           >
//             <Popover.Panel className="fixed left-0 right-0 z-40 mt-3">
//               <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
//                 <div className="rounded-lg shadow-lg ring-1 ring-black ring-opacity-5 overflow-hidden">
//                   <div className="relative grid grid-cols-3 gap-6 bg-white px-5 py-6 sm:gap-8 sm:p-8">
//                     {blogs.map((blog) => (
//                       <div key={blog.name}>
//                         <h3 className="text-base font-medium text-gray-900 mb-4">
//                           {blog.name}
//                         </h3>
//                         <ul className="space-y-4">
//                           {blog.items.map((item) => (
//                             <li key={item.name}>
//                               <a
//                                 href={item.href}
//                                 className="group flex items-center space-x-3"
//                               >
//                                 <ChevronRight className="h-5 w-5 text-orange-600 group-hover:text-orange-800" />
//                                 <span className="text-base text-gray-900 group-hover:text-orange-600">
//                                   {item.name}
//                                 </span>
//                               </a>
//                             </li>
//                           ))}
//                         </ul>
//                       </div>
//                     ))}
//                   </div>
//                 </div>
//               </div>
//             </Popover.Panel>
//           </Transition>
//         </>
//       )}
//     </Popover>
//   );
// }
