"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ChevronRight, Home, X, Shield, Users, CreditCard, FileText, Layers, Settings } from "lucide-react";

interface SidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

export default function Sidebar({ isOpen, onClose }: SidebarProps) {
  const pathname = usePathname();
  const [expandedSections, setExpandedSections] = useState<string[]>([]);

  const toggleSection = (title: string) => {
    setExpandedSections((prev) =>
      prev.includes(title)
        ? prev.filter((t) => t !== title)
        : [...prev, title]
    );
  };

  const menuItems = [
    {
      title: "Tender",
      icon: <FileText className="w-5 h-5" />,
      children: [
        { title: "Landing Page", href: "/landing-page" },
        { title: "Add Tender", href: "/tenders/new" },
        { title: "All Tenders", href: "/tenders" },
        { title: "Categories", href: "/tender-categories" },
        { title: "Add Owner", href: "/tender-owners/create" },
        { title: "All Owners", href: "/tender-owners" },
      ],
    },
    {
      title: "Plans",
      icon: <Layers className="w-5 h-5" />,
      children: [
        { title: "All Plans", href: "/plans" },
        { title: "Add Plan", href: "/plans/create" },
        { title: "Categories", href: "/plans/categories" },
      ],
    },
    {
      title: "Finance",
      icon: <CreditCard className="w-5 h-5" />,
      children: [
        { title: "Applications", href: "/finance/requests" },
        { title: "Loan Products", href: "/finance/products" },
      ],
    },
    {
      title: "User Management",
      icon: <Users className="w-5 h-5" />,
      children: [
        { title: "All Users", href: "/users" },
        { title: "Verification", href: "/verification-requests" },
      ],
    },
    {
      title: "Settings",
      icon: <Settings className="w-5 h-5" />,
      children: [
        { title: "Admin Config", href: "/admin-configs" },
      ],
    },
  ];

  const isActive = (href: string) => {
    if (href === "/tenders/new" && pathname?.includes("/tenders/") && pathname !== "/tenders") return true;
    if (href === "/tender-categories" && pathname?.startsWith("/tender-categories")) return true;
    if (href === "/plans/categories" && pathname?.startsWith("/plans/categories")) return true;
    if (href === "/finance/products" && pathname?.startsWith("/finance")) return pathname === href;
    return pathname === href;
  };

  return (
    <>
      {/* Overlay */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-gray-900/50 backdrop-blur-sm z-40 lg:hidden transition-opacity duration-300"
          onClick={onClose}
        />
      )}

      {/* Sidebar */}
      <aside
        className={`fixed top-0 left-0 h-full bg-white shadow-2xl z-50 transform transition-transform duration-300 ease-in-out ${
          isOpen ? "translate-x-0" : "-translate-x-full"
        } lg:translate-x-0 lg:static lg:z-auto w-72 border-r border-gray-100 flex flex-col`}
      >
        {/* Header */}
        <div className="h-16 flex items-center justify-between px-6 bg-white border-b border-gray-100 shrink-0">
          <div className="flex items-center gap-3">
             <div className="w-8 h-8 rounded-lg bg-blue-600 flex items-center justify-center shadow-lg shadow-blue-600/30">
                <Shield className="w-5 h-5 text-white" />
             </div>
             <span className="text-xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent">
               CRM
             </span>
          </div>
          <button
            onClick={onClose}
            className="lg:hidden p-2 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-50 transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto py-6 px-4 space-y-1 custom-scrollbar">
          {menuItems.map((item) => {
            const isExpanded = expandedSections.includes(item.title);
            return (
              <div key={item.title} className="mb-2">
                <button
                  onClick={() => toggleSection(item.title)}
                  className={`w-full flex items-center justify-between px-3 py-2.5 rounded-xl transition-all duration-200 group ${
                    isExpanded ? "bg-gray-50 text-gray-900" : "text-gray-600 hover:bg-gray-50 hover:text-gray-900"
                  }`}
                >
                  <div className="flex items-center gap-3">
                    <span className={`transition-colors ${isExpanded ? "text-blue-600" : "text-gray-400 group-hover:text-blue-500"}`}>
                      {item.icon}
                    </span>
                    <span className="font-semibold text-sm tracking-wide">{item.title}</span>
                  </div>
                  <ChevronRight
                    className={`w-4 h-4 text-gray-400 transition-transform duration-200 ${
                      isExpanded ? "rotate-90 text-blue-600" : ""
                    }`}
                  />
                </button>

                {/* Submenu */}
                <div
                  className={`overflow-hidden transition-all duration-300 ease-in-out ${
                    isExpanded ? "max-h-96 opacity-100 mt-1" : "max-h-0 opacity-0"
                  }`}
                >
                  <ul className="space-y-1 pl-3">
                    {item.children?.map((child) => {
                      const active = isActive(child.href);
                      return (
                        <li key={child.title} className="relative">
                           {active && <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-6 bg-blue-600 rounded-r-full" />}
                          <Link
                            href={child.href}
                            onClick={onClose}
                            className={`flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 ml-2 ${
                              active
                                ? "bg-blue-50 text-blue-700 shadow-sm"
                                : "text-gray-500 hover:text-gray-900 hover:bg-gray-50/80"
                            }`}
                          >
                            <span className={`w-1.5 h-1.5 rounded-full transition-colors ${active ? "bg-blue-600" : "bg-gray-300"}`} />
                            {child.title}
                          </Link>
                        </li>
                      );
                    })}
                  </ul>
                </div>
              </div>
            );
          })}
        </nav>

        {/* Footer */}
        <div className="p-4 border-t border-gray-100 bg-gray-50/50 shrink-0">
          <Link
            href="/"
            className="flex items-center gap-3 px-4 py-3 rounded-xl bg-white border border-gray-200 shadow-sm hover:shadow-md hover:border-blue-200 group transition-all duration-200"
          >
            <Home className="w-5 h-5 text-gray-400 group-hover:text-blue-600 transition-colors" />
            <span className="text-sm font-semibold text-gray-700 group-hover:text-gray-900">
              Return Home
            </span>
          </Link>
        </div>
      </aside>
    </>
  );
}
interface SidebarProps {
  isOpen: boolean;
  onClose: () => void;
}


