import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
  Outlet,
  Link,
  createRootRouteWithContext,
  useRouter,
  HeadContent,
  Scripts,
} from "@tanstack/react-router";
import { useState, type ReactNode } from "react";
import { Menu, X, Phone, ChevronDown } from "lucide-react";
import { ScrollToTop } from "@/components/scroll-to-top";
import { QuickContact } from "@/components/quick-contact";

import appCss from "../styles.css?url";

interface NavChild {
  label: string;
  to: string;
}

interface NavItem {
  label: string;
  to?: string;
  children?: NavChild[];
}

const NAV_ITEMS: NavItem[] = [
  { label: "Home", to: "/" },
  { label: "About Us", to: "/about" },
  {
    label: "Applications",
    children: [
      { label: "Humidification", to: "/humidification" },
      { label: "Commercial Outdoor Cooling", to: "/commercial-outdoor-cooling" },
      { label: "Industrial Outdoor Cooling", to: "/industrial-outdoor-cooling" },
      { label: "Residential Outdoor Cooling", to: "/residential-outdoor-cooling" },
      { label: "Dust Suppression", to: "/dust-suppression" },
      { label: "Animal Cooling", to: "/animal-cooling" },
      { label: "Air Cooler", to: "/air-cooler" },
      { label: "Professional Pre-Cooling System", to: "/professional-pre-cooling" },
    ],
  },
  {
    label: "Products",
    children: [
      { label: "Sanitization Booth", to: "/sanitization-booth" },
      { label: "Nozzles", to: "/nozzles" },
      { label: "Misting Pumps", to: "/misting-pumps" },
      { label: "Portable Misting Fans", to: "/portable-misting-fans" },
      { label: "Satellite Misting Fans", to: "/satellite-misting-fans" },
      { label: "Fittings & Tubing", to: "/misting-fittings-tubings" },
      { label: "Parts & Accessories", to: "/misting-systems-accessories" },
    ],
  },
  {
    label: "Solutions",
    children: [
      { label: "Misting Technology", to: "/misting-technology" },
      { label: "Misting Systems Design", to: "/misting-systems-design" },
      { label: "FAQ", to: "/faq" },
    ],
  },
  { label: "Projects", to: "/projects" },
  { label: "Enquiry", to: "/enquiry" },
  { label: "Contact Us", to: "/contact" },
  { label: "RENTAL", to: "/rental" },
];

function TopBar() {
  return (
    <div className="w-full bg-brand-red text-white text-sm">
      <div className="container-page flex flex-wrap items-center justify-end gap-6 py-2">
        <a href="tel:+97142515596" className="inline-flex items-center gap-2 hover:opacity-80">
          <Phone className="h-3.5 w-3.5" /> +971 4 251 5596
        </a>
        <a href="tel:+971552098628" className="inline-flex items-center gap-2 hover:opacity-80">
          <Phone className="h-3.5 w-3.5" /> +971 55 209 8628
        </a>
      </div>
    </div>
  );
}

function DesktopNavItem({ item }: { item: NavItem }) {
  if (!item.children) {
    return (
      <Link
        to={item.to as any}
        className="text-foreground/80 hover:text-brand-red transition-colors whitespace-nowrap"
        activeProps={{ className: "text-brand-red" }}
        activeOptions={{ exact: item.to === "/" }}
      >
        {item.label}
      </Link>
    );
  }

  return (
    <div className="group relative">
      <button className="inline-flex items-center gap-1 text-foreground/80 hover:text-brand-red transition-colors cursor-pointer whitespace-nowrap">
        {item.label}
        <ChevronDown className="h-3.5 w-3.5 transition-transform duration-200 group-hover:rotate-180" />
      </button>
      <div className="absolute left-1/2 -translate-x-1/2 top-full pt-3 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 pointer-events-none group-hover:pointer-events-auto">
        <div className="bg-white rounded-lg shadow-xl border min-w-[220px] py-2">
          {item.children.map((child) => (
            <a
              key={child.to}
              href={child.to}
              className="block px-5 py-2.5 text-sm text-foreground/80 hover:text-brand-red hover:bg-muted/50 transition-colors"
            >
              {child.label}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function MobileSubMenu({ item, onLinkClick }: { item: NavItem; onLinkClick: () => void }) {
  const [subOpen, setSubOpen] = useState(false);

  if (!item.children) {
    return (
      <Link
        to={item.to as any}
        onClick={onLinkClick}
        className="block text-foreground/80 hover:text-brand-red transition-colors"
        activeProps={{ className: "text-brand-red" }}
        activeOptions={{ exact: item.to === "/" }}
      >
        {item.label}
      </Link>
    );
  }

  return (
    <div>
      <button
        onClick={() => setSubOpen((v) => !v)}
        className="flex items-center justify-between w-full text-foreground/80 hover:text-brand-red transition-colors cursor-pointer"
      >
        {item.label}
        <ChevronDown
          className={`h-4 w-4 transition-transform duration-200 ${subOpen ? "rotate-180" : ""}`}
        />
      </button>
      <div
        className={`overflow-hidden transition-all duration-200 ${
          subOpen ? "max-h-96 opacity-100 mt-2" : "max-h-0 opacity-0"
        }`}
      >
        <div className="ml-4 border-l pl-4 space-y-2 pb-2">
          {item.children.map((child) => (
            <a
              key={child.to}
              href={child.to}
              onClick={onLinkClick}
              className="block text-sm text-foreground/70 hover:text-brand-red transition-colors"
            >
              {child.label}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
}

function Header() {
  const [open, setOpen] = useState(false);

  return (
    <header className="sticky top-0 z-50 bg-background/95 backdrop-blur border-b">
      <div className="container-page flex items-center justify-between h-20">
        <Link to="/" className="flex items-center shrink-0">
          <img src="/promist-logo.png" alt="Promist" className="h-10 w-auto" />
        </Link>
        <nav className="hidden lg:flex items-center gap-6 text-sm font-medium">
          {NAV_ITEMS.map((item) =>
            "children" in item && item.children ? (
              <DesktopNavItem key={item.label} item={item} />
            ) : (
              <Link
                key={item.to}
                to={item.to as any}
                className="text-foreground/80 hover:text-brand-red transition-colors whitespace-nowrap"
                activeProps={{ className: "text-brand-red" }}
                activeOptions={{ exact: item.to === "/" }}
              >
                {item.label}
              </Link>
            ),
          )}
        </nav>
        <button
          onClick={() => setOpen((v) => !v)}
          className="lg:hidden inline-flex items-center justify-center h-10 w-10 rounded-md border"
          aria-label="Toggle menu"
        >
          {open ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
        </button>
      </div>
      {open && (
        <div className="lg:hidden border-t">
          <div className="container-page py-4 flex flex-col gap-3">
            {NAV_ITEMS.map((item) => (
              <MobileSubMenu key={item.label} item={item} onLinkClick={() => setOpen(false)} />
            ))}
          </div>
        </div>
      )}
    </header>
  );
}

function Footer() {
  return (
    <footer className="mt-24 border-t bg-muted/40">
      <div className="container-page py-14 grid gap-10 md:grid-cols-4">
        {/* Brand */}
        <div>
          <div className="font-display text-2xl font-black">
            <span className="text-brand-blue">Pro</span>
            <span className="text-brand-red">mist</span>
          </div>
          <p className="mt-3 text-sm text-muted-foreground max-w-xs">
            Promist is a registered trademark &amp; A brand owned by{" "}
            <a
              href="https://profenuae.com"
              target="_blank"
              rel="noopener noreferrer"
              className="text-brand-red hover:underline"
            >
              Profen General Trading L.L.C
            </a>
          </p>
        </div>
        {/* Explore */}
        <div>
          <h4 className="text-xs uppercase tracking-widest text-brand-red font-semibold">Explore</h4>
          <ul className="mt-4 space-y-2 text-sm">
            <li><Link to="/about" className="hover:text-brand-red transition-colors">About</Link></li>
            <li><Link to="/applications" className="hover:text-brand-red transition-colors">Applications</Link></li>
            <li><Link to="/products" className="hover:text-brand-red transition-colors">Products</Link></li>
            <li><Link to="/solutions" className="hover:text-brand-red transition-colors">Solutions</Link></li>
            <li><Link to="/projects" className="hover:text-brand-red transition-colors">Projects</Link></li>
          </ul>
        </div>
        {/* Company */}
        <div>
          <h4 className="text-xs uppercase tracking-widest text-brand-red font-semibold">Company</h4>
          <ul className="mt-4 space-y-2 text-sm">
            <li><Link to="/enquiry" className="hover:text-brand-red transition-colors">Enquiry</Link></li>
            <li><Link to="/contact" className="hover:text-brand-red transition-colors">Contact</Link></li>
            <li><Link to="/rental" className="hover:text-brand-red transition-colors">Rental</Link></li>
          </ul>
        </div>
        {/* Contact */}
        <div>
          <h4 className="text-xs uppercase tracking-widest text-brand-red font-semibold">Contact</h4>
          <ul className="mt-4 space-y-2 text-sm text-muted-foreground">
            <li className="flex items-start gap-2">
              <span className="font-semibold text-foreground/60 shrink-0">Add:</span>
              <span>P.O. Box 181926, Dubai, United Arab Emirates</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="font-semibold text-foreground/60 shrink-0">Tel:</span>
              <span>+971 4 2515596</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="font-semibold text-foreground/60 shrink-0">Mob:</span>
              <span>+971 58 2055 252 / +971 50 9952 886</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="font-semibold text-foreground/60 shrink-0">Fax:</span>
              <span>+971 4 2857894</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="font-semibold text-foreground/60 shrink-0">Email:</span>
              <span className="space-x-1">
                <a href="mailto:info@promistcool.com" className="hover:text-brand-red transition-colors">info@promistcool.com</a>
                <span>, </span>
                <a href="mailto:sales@promistcool.com" className="hover:text-brand-red transition-colors">sales@promistcool.com</a>
              </span>
            </li>
            <li className="flex items-start gap-2 pt-2">
              <span className="font-semibold text-foreground/60 shrink-0">Call:</span>
              <span>+971 50 995 2886</span>
            </li>
          </ul>
        </div>
      </div>
      <div className="border-t">
        <div className="container-page py-5 text-xs text-muted-foreground flex flex-wrap justify-between gap-2">
          <span>&copy; 2026 Promist Misting Systems. All rights reserved.</span>
          <span>Humidity and Control</span>
        </div>
      </div>
    </footer>
  );
}

function NotFoundComponent() {
  return (
    <div className="flex min-h-[70vh] items-center justify-center px-4">
      <div className="max-w-md text-center">
        <h1 className="text-7xl font-black text-brand-red">404</h1>
        <h2 className="mt-4 text-xl font-semibold">Page not found</h2>
        <p className="mt-2 text-sm text-muted-foreground">
          The page you're looking for doesn't exist or has been moved.
        </p>
        <Link to="/" className="mt-6 inline-flex rounded-md bg-brand-red text-white px-5 py-2.5 text-sm font-medium hover:opacity-90">
          Go home
        </Link>
      </div>
    </div>
  );
}

function ErrorComponent({ error, reset }: { error: Error; reset: () => void }) {
  console.error(error);
  const router = useRouter();
  return (
    <div className="flex min-h-[70vh] items-center justify-center px-4">
      <div className="max-w-md text-center">
        <h1 className="text-xl font-semibold">This page didn't load</h1>
        <p className="mt-2 text-sm text-muted-foreground">Something went wrong. Try again or head home.</p>
        <div className="mt-6 flex justify-center gap-2">
          <button
            onClick={() => { router.invalidate(); reset(); }}
            className="rounded-md bg-brand-red text-white px-4 py-2 text-sm font-medium"
          >Try again</button>
          <a href="/" className="rounded-md border px-4 py-2 text-sm font-medium">Go home</a>
        </div>
      </div>
    </div>
  );
}

export const Route = createRootRouteWithContext<{ queryClient: QueryClient }>()({
  head: () => ({
    meta: [
      { charSet: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      { title: "Promist Misting Systems — Humidity and Control" },
      { name: "description", content: "High-pressure misting systems for outdoor cooling, humidification, dust suppression and sanitization in the UAE since 1979." },
      { property: "og:title", content: "Promist Misting Systems" },
      { property: "og:description", content: "High-pressure misting for cooling, humidification and dust suppression." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary_large_image" },
    ],
    links: [
      { rel: "stylesheet", href: appCss },
      { rel: "icon", href: "/favicon.png", type: "image/png" },
      { rel: "preconnect", href: "https://fonts.googleapis.com" },
      { rel: "preconnect", href: "https://fonts.gstatic.com", crossOrigin: "anonymous" },
      { rel: "stylesheet", href: "https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@300;400;500;600;700;800;900&display=swap" },
    ],
  }),
  shellComponent: RootShell,
  component: RootComponent,
  notFoundComponent: NotFoundComponent,
  errorComponent: ErrorComponent,
});

function RootShell({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <head><HeadContent /></head>
      <body>{children}<Scripts /></body>
    </html>
  );
}

function RootComponent() {
  const { queryClient } = Route.useRouteContext();
  return (
    <QueryClientProvider client={queryClient}>
      <TopBar />
      <Header />
      <main>
        <Outlet />
      </main>
      <Footer />
      <ScrollToTop />
      <QuickContact />
    </QueryClientProvider>
  );
}
