"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useRouter, useSearchParams } from "next/navigation";import { 
  LayoutDashboard, 
  ShoppingBag, 
  Heart, 
  User, 
  MapPin, 
  Key, 
  LogOut,
  Menu,
  X
} from "lucide-react";
import useAuth from "@/hooks/useAuth";

const MENU_ITEMS = [
  { key: "dashboard", label: "Dashboard", icon: <LayoutDashboard size={20} />, href: "/dashboard" },
  { key: "profile", label: "Profile", icon: <User size={20} />, href: "/dashboard/profile" },
  { key: "wishlist", label: "Wishlist", icon: <Heart size={20} />, href: "/dashboard/wishlist" },
  { key: "addresses", label: "Addresses", icon: <MapPin size={20} />, href: "/dashboard/addresses" },
  { key: "change-password", label: "Change Password", icon: <Key size={20} />, href: "/dashboard/change-password" },
];

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const { logout } = useAuth();
  const router = useRouter();
  const [activeTab, setActiveTab] = useState("dashboard");
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [customer, setCustomer] = useState<any>({
    name: "Abhijit Chatterjee",
    phone: "9942427247",
    email: "abhijit@example.com",
    avatar: "/images/user-2.jpg"
  });

  const getInitials = (name?: string) => {
  if (!name) return "U";

  return name
    .split(" ")
    .map((n) => n[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();
};

  const handleLogout = () => {
    logout()
    router.refresh();
  }

  useEffect(() => {
    const stored = localStorage.getItem("customer");
    if (stored) {
      setCustomer(JSON.parse(stored));
    }
    
    // Set active tab based on URL
    const path = pathname.split("/").pop();
    if (path && MENU_ITEMS.some(item => item.key === path)) {
      setActiveTab(path);
    } else if (pathname === "/dashboard") {
      setActiveTab("dashboard");
    }
  }, [pathname]);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Mobile Menu Overlay */}
      {mobileMenuOpen && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 z-40 md:hidden"
          onClick={() => setMobileMenuOpen(false)}
        />
      )}

      <div className="container px-3 mx-auto py-6 md:py-10">
        <div className="flex flex-wrap -mx-3 xl:-mx-4 2xl:-mx-6">
          
          {/* Sidebar */}
          <aside className={`
            2xl:w-3/12 xl:w-3/12 lg:w-3/12 md:w-5/12 sm:w-[320px] w-[280px]
            px-0 md:px-3 xl:px-4 2xl:px-6
            fixed md:static top-0 bottom-0 z-50 md:z-0
            transition-all duration-300 ease-in-out
            ${mobileMenuOpen ? 'left-0' : '-left-full md:left-0'}
          `}>
            <div className="w-full h-full bg-white flex flex-col p-6 2xl:p-8 md:shadow-lg md:rounded-xl overflow-y-auto">
              {/* Close button for mobile */}
              <button 
                className="absolute top-4 right-4 md:hidden text-gray-500 hover:text-gray-700 p-2 rounded-full hover:bg-gray-100"
                onClick={() => setMobileMenuOpen(false)}
              >
                <X size={24} />
              </button>

              {/* User Profile Section */}
              <div className="flex gap-3 items-center mb-6">
                <div className="group relative rounded-full min-w-12 xl:min-w-16 2xl:min-w-20 h-12 xl:h-16 2xl:h-20 overflow-hidden bg-gray-200">
                  {customer?.avatar ? (
                    <img 
                    src={customer?.avatar} 
                    alt={customer?.name}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).src = 'https://via.placeholder.com/80';
                    }}
                  />
                  ) : (
                    <div className="bg-primary w-full h-full flex items-center justify-center text-white">
                      {getInitials(customer?.name)}
                    </div>
                  )} 
                  <label className="opacity-0 group-hover:opacity-100 absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 text-white cursor-pointer transition duration-300">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" className="w-5 h-5" viewBox="0 0 16 16">
                      <path d="M15 12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h1.172a3 3 0 0 0 2.12-.879l.83-.828A1 1 0 0 1 6.827 3h2.344a1 1 0 0 1 .707.293l.828.828A3 3 0 0 0 12.828 5H14a1 1 0 0 1 1 1z"/>
                      <path d="M8 11a2.5 2.5 0 1 1 0-5 2.5 2.5 0 0 1 0 5m0 1a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7M3 6.5a.5.5 0 1 1-1 0 .5.5 0 0 1 1 0"/>
                    </svg>
                    <input type="file" className="hidden" accept="image/*" />
                  </label>
                </div>
                <div className="flex flex-col min-w-0">
                  <h3 className="text-base xl:text-lg 2xl:text-xl font-bold truncate">{customer?.name}</h3>
                  <p className="text-sm text-gray-500">{customer?.phone}</p>
                </div>
              </div>

              {/* Navigation Menu */}
              <ul className="flex-1 space-y-2">
                {MENU_ITEMS.map((item) => (
                  <li key={item.key}>
                    <Link
                      href={item.href}
                      onClick={() => {
                        setActiveTab(item.key);
                        setMobileMenuOpen(false);
                      }}
                      className={`flex items-center gap-3 px-4 py-2.5 font-semibold text-sm xl:text-base rounded-lg transition-all duration-300
                        ${activeTab === item.key 
                          ? 'bg-primary text-white shadow-md' 
                          : 'text-gray-700 hover:bg-primary hover:text-white'
                        }`}
                    >
                      {item.icon}
                      <span>{item.label}</span>
                    </Link>
                  </li>
                ))}
              </ul>

              {/* Logout Button */}
              <div className="pt-4 border-t border-gray-100 mt-4">
                <Link
                  href='/login'
                  onClick={handleLogout}
                  className="flex items-center gap-3 px-4 py-2.5 font-semibold text-sm xl:text-base rounded-lg text-gray-700 hover:bg-primary hover:text-white transition-all duration-300"
                >
                  <LogOut size={20} />
                  <span>Logout</span>
                </Link>
              </div>
            </div>
          </aside>

          {/* Main Content */}
          <main className="2xl:w-9/12 xl:w-9/12 lg:w-9/12 md:w-7/12 w-full px-3 xl:px-4 2xl:px-6">
            <div className="p-0">
              {/* Mobile Header */}
              <div className="pb-4 flex justify-between items-center md:hidden">
                <h1 className="text-xl font-semibold">Welcome Back 👋</h1>
                <button 
                  className="bg-secondary text-white w-10 h-10 rounded-full flex items-center justify-center shadow-md"
                  onClick={() => setMobileMenuOpen(true)}
                >
                  <Menu size={24} />
                </button>
              </div>

              {/* Child content (Dashboard, Profile, Addresses, etc.) */}
              {children}
            </div>
          </main>
        </div>
      </div>
    </div>
  );
}