import { Link, usePage } from "@inertiajs/react";
import { useState } from "react";
import { about, contact, home, products as productsRoute } from "@/routes";
import locale from "@/routes/locale";



export default function Header({ settings, products }: { settings: any, products: any }) {
  const { url } = usePage();
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);
  const currentPath = url.split("?")[0];
  const localeMatch = currentPath.match(/^\/(en|ar)(?=\/|$)/);
  const currentLocale = localeMatch?.[1] ?? "en";
  const isArabic = currentLocale === "ar";
  const targetLocale = isArabic ? "en" : "ar";
  const labels = isArabic
    ? {
        home: "الرئيسية",
        about: "عن الشركة",
        products: "المنتجات",
        contact: "تواصل معنا",
        menu: "القائمة",
        switchLanguage: "EN",
      }
    : {
        home: "Home",
        about: "About us",
        products: "Products",
        contact: "Contact us",
        menu: "Menu",
        switchLanguage: "AR",
      };
  const homeHref = home.url();
  const aboutHref = about.url();
  const productHref = productsRoute.url();
  const contactHref = contact.url();

  const linkBaseClass = "flex items-center gap-1 rounded-full px-3 py-1 transition-colors";
  const activeLinkClass = "bg-[#0B4B2A] text-white";
  const inactiveLinkClass = "text-slate-700 hover:text-[#0B4B2A]";
  const normalizePath = (path: string) => {
    const withoutLocale = path.replace(/^\/(en|ar)(?=\/|$)/, "") || "/";
    if (withoutLocale === "/") {
      return "/";
    }

    return withoutLocale.replace(/\/+$/, "");
  };
  const isActive = (href: string, exact = false) => {
    const current = normalizePath(currentPath);
    const target = normalizePath(href);

    if (exact) {
      return current === target;
    }

    return current === target || current.startsWith(`${target}/`);
  };

  return (
    <header className="sticky top-0 z-40 w-full border-b border-slate-200 bg-white">
      <div className="mx-auto flex w-full max-w-6xl items-center justify-between gap-6 px-6 py-2">
        <Link href={homeHref} className="flex items-center">
          <img src={settings.logo.image} alt={settings.logo.alt} className="h-14 w-auto" />
        </Link>

        <nav className="hidden items-center gap-5 text-md font-bold text-slate-700 md:flex" aria-label={labels.menu}>
          <Link
            href={homeHref}
            className={`${linkBaseClass} ${isActive(homeHref, true) ? activeLinkClass : inactiveLinkClass}`}
          >
            {labels.home}
          </Link>
          <Link
            href={aboutHref}
            className={`${linkBaseClass} ${isActive(aboutHref) ? activeLinkClass : inactiveLinkClass}`}
          >
            {labels.about}
          </Link>
          <div className="relative group">
            <Link
              href={productHref}
              className={`${linkBaseClass} ${isActive(productHref) ? activeLinkClass : inactiveLinkClass}`}
            >
              {labels.products}
              <svg
                viewBox="0 0 20 20"
                fill="currentColor"
                className="h-4 w-4 transition-transform group-hover:rotate-180"
                aria-hidden="true"
              >
                <path
                  fillRule="evenodd"
                  d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 10.94l3.71-3.71a.75.75 0 1 1 1.06 1.06l-4.24 4.24a.75.75 0 0 1-1.06 0L5.21 8.29a.75.75 0 0 1 .02-1.08Z"
                  clipRule="evenodd"
                />
              </svg>
            </Link>
            <div className="invisible absolute left-0 top-full z-10 mt-0 w-64 rounded-2xl border border-slate-200 bg-white p-2 text-sm text-slate-700 opacity-0 shadow-lg transition group-hover:visible group-hover:opacity-100">
              {products.map((product: any) => (
                <Link
                  key={product.id}
                  href={product.url}
                  className="block rounded-xl px-3 py-2 text-base font-medium text-slate-700 transition hover:bg-slate-50 hover:text-[#0B4B2A]"
                >
                  {product.title}
                </Link>
              ))}
            </div>
          </div>
          <Link
            href={contactHref}
            className={`${linkBaseClass} ${isActive(contactHref) ? activeLinkClass : inactiveLinkClass}`}
          >
            {labels.contact}
          </Link>
          <a href={locale.switch.url(targetLocale)} className="flex items-center gap-1 rounded-full px-3 py-1 transition-colors text-slate-700 hover:text-[#0B4B2A]">
            {labels.switchLanguage}
          </a>
        </nav>

        <button
          type="button"
          onClick={() => setIsMobileMenuOpen((isOpen) => !isOpen)}
          className="inline-flex h-10 items-center justify-center rounded-full border border-slate-200 px-4 text-sm font-medium text-[#0B4B2A] transition-colors hover:border-[#0B4B2A] hover:bg-[#0B4B2A] hover:text-white md:hidden"
          aria-label={labels.menu}
          aria-expanded={isMobileMenuOpen}
          aria-controls="mobile-menu"
        >
          {labels.menu}
        </button>
      </div>
      {isMobileMenuOpen && (
        <nav
          id="mobile-menu"
          className="border-t border-slate-200 px-6 py-4 md:hidden"
          aria-label={labels.menu}
        >
          <div className="flex flex-col gap-2 text-base font-semibold text-slate-700">
            <Link
              href={homeHref}
              className={`rounded-xl px-3 py-2 transition-colors ${isActive(homeHref, true) ? "bg-[#0B4B2A] text-white" : "hover:bg-slate-50 hover:text-[#0B4B2A]"}`}
              onClick={() => setIsMobileMenuOpen(false)}
            >
              {labels.home}
            </Link>
            <Link
              href={aboutHref}
              className={`rounded-xl px-3 py-2 transition-colors ${isActive(aboutHref) ? "bg-[#0B4B2A] text-white" : "hover:bg-slate-50 hover:text-[#0B4B2A]"}`}
              onClick={() => setIsMobileMenuOpen(false)}
            >
              {labels.about}
            </Link>
            <Link
              href={productHref}
              className={`rounded-xl px-3 py-2 transition-colors ${isActive(productHref) ? "bg-[#0B4B2A] text-white" : "hover:bg-slate-50 hover:text-[#0B4B2A]"}`}
              onClick={() => setIsMobileMenuOpen(false)}
            >
              {labels.products}
            </Link>
            <div className="ml-2 border-l border-slate-200 pl-2">
              {products.map((product: any) => (
                <Link
                  key={product.id}
                  href={product.url}
                  className="block rounded-xl px-3 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-50 hover:text-[#0B4B2A]"
                  onClick={() => setIsMobileMenuOpen(false)}
                >
                  {product.title}
                </Link>
              ))}
            </div>
            <Link
              href={contactHref}
              className={`rounded-xl px-3 py-2 transition-colors ${isActive(contactHref) ? "bg-[#0B4B2A] text-white" : "hover:bg-slate-50 hover:text-[#0B4B2A]"}`}
              onClick={() => setIsMobileMenuOpen(false)}
            >
              {labels.contact}
            </Link>
            <a
              href={locale.switch.url(targetLocale)}
              className="rounded-xl px-3 py-2 transition-colors hover:bg-slate-50 hover:text-[#0B4B2A]"
              onClick={() => setIsMobileMenuOpen(false)}
            >
              {labels.switchLanguage}
            </a>
          </div>
        </nav>
      )}
    </header>
  );
}
