"use client"

import { useReducer } from "react"
import Link from "next/link"
import Image from "next/image"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Menu, X, Phone, ChevronDown } from "lucide-react"
import { GetFreeMachineModal } from "@/components/get-free-machine-modal"
import { Cart } from "@/components/cart"
import { CartButton } from "@/components/cart-button"
import { MobileCartButton } from "@/components/mobile-cart-button"
import { cn } from "@/lib/utils"

// Header state types following Vercel React Best Practices
type HeaderState = {
  isMenuOpen: boolean
  isWhoWeServeOpen: boolean
  isVendingMachinesOpen: boolean
  isFoodBeverageOpen: boolean
  isServicesOpen: boolean
  isBlogPostsOpen: boolean
  isAboutOpen: boolean
  isModalOpen: boolean
  isCartOpen: boolean
}

type HeaderAction =
  | { type: "TOGGLE_MENU" }
  | { type: "TOGGLE_WHO_WE_SERVE" }
  | { type: "TOGGLE_VENDING_MACHINES" }
  | { type: "TOGGLE_FOOD_BEVERAGE" }
  | { type: "TOGGLE_SERVICES" }
  | { type: "TOGGLE_BLOG_POSTS" }
  | { type: "TOGGLE_ABOUT" }
  | { type: "SET_MODAL"; value: boolean }
  | { type: "SET_CART"; value: boolean }

const closedGroups = {
  isWhoWeServeOpen: false,
  isVendingMachinesOpen: false,
  isFoodBeverageOpen: false,
  isServicesOpen: false,
  isBlogPostsOpen: false,
  isAboutOpen: false,
}

// Reducer for header state - consolidates related mobile menu states
function headerReducer(state: HeaderState, action: HeaderAction): HeaderState {
  switch (action.type) {
    case "TOGGLE_MENU":
      return state.isMenuOpen
        ? { ...state, isMenuOpen: false, ...closedGroups }
        : { ...state, isMenuOpen: true, ...closedGroups }
    case "TOGGLE_WHO_WE_SERVE":
      return {
        ...state,
        ...closedGroups,
        isWhoWeServeOpen: !state.isWhoWeServeOpen,
      }
    case "TOGGLE_VENDING_MACHINES":
      return {
        ...state,
        ...closedGroups,
        isVendingMachinesOpen: !state.isVendingMachinesOpen,
      }
    case "TOGGLE_FOOD_BEVERAGE":
      return {
        ...state,
        ...closedGroups,
        isFoodBeverageOpen: !state.isFoodBeverageOpen,
      }
    case "TOGGLE_SERVICES":
      return {
        ...state,
        ...closedGroups,
        isServicesOpen: !state.isServicesOpen,
      }
    case "TOGGLE_BLOG_POSTS":
      return {
        ...state,
        ...closedGroups,
        isBlogPostsOpen: !state.isBlogPostsOpen,
      }
    case "TOGGLE_ABOUT":
      return {
        ...state,
        ...closedGroups,
        isAboutOpen: !state.isAboutOpen,
      }
    case "SET_MODAL":
      return { ...state, isModalOpen: action.value }
    case "SET_CART":
      return { ...state, isCartOpen: action.value }
    default:
      return state
  }
}

export function Header() {
  const [state, dispatch] = useReducer(headerReducer, {
    isMenuOpen: false,
    isWhoWeServeOpen: false,
    isVendingMachinesOpen: false,
    isFoodBeverageOpen: false,
    isServicesOpen: false,
    isBlogPostsOpen: false,
    isAboutOpen: false,
    isModalOpen: false,
    isCartOpen: false,
  })

  const whoWeServeItems = [
    { label: "Warehouses", href: "/warehouses" },
    { label: "Auto Repair", href: "/auto-repair" },
    { label: "Gyms", href: "/gyms" },
    { label: "Community Centers", href: "/community-centers" },
    { label: "Dance Studios", href: "/dance-studios" },
    { label: "Car Washes", href: "/car-washes" },
  ]

  const vendingMachinesItems = [
    { label: "Machines We Use", href: "/vending-machines/machines-we-use" },
    {
      label: "Machines for Sale in Utah",
      href: "/vending-machines/machines-for-sale",
    },
    { label: "Vending Machine Manuals", href: "/manuals" },
  ]

  const foodBeverageItems = [
    { label: "Healthy Options", href: "/food-and-beverage/healthy-options" },
    {
      label: "Traditional Options",
      href: "/food-and-beverage/traditional-options",
    },
    {
      label: "Food & Beverage Suppliers",
      href: "/food-and-beverage/suppliers",
    },
  ]

  const servicesItems = [
    { label: "All Services", href: "/services" },
    { label: "Vending Machine Repairs", href: "/services/repairs" },
    { label: "Vending Machine Moving Services", href: "/services/moving" },
    { label: "Vending Machine Parts", href: "/services/parts" },
    { label: "Vending Machine Manuals", href: "/manuals" },
  ]

  const blogPostsItems = [
    { label: "Seaga HY900 Support", href: "/seaga-hy900-support" },
  ]

  const aboutItems = [
    { label: "About Us", href: "/about-us" },
    { label: "Reviews", href: "/reviews" },
    { label: "FAQs", href: "/about/faqs" },
  ]

  const desktopLinkClassName =
    "rounded-full px-3 py-2 text-sm font-medium text-foreground transition hover:text-primary focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/15"
  const mobileLinkClassName =
    "flex min-h-11 items-center rounded-[1rem] px-4 text-sm font-medium text-foreground transition hover:bg-primary/6 hover:text-primary focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/15"
  const mobileGroupButtonClassName =
    "flex min-h-11 items-center justify-between rounded-[1rem] px-4 text-sm font-medium text-foreground transition hover:bg-primary/6 hover:text-primary focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/15"
  const desktopDropdownClassName =
    "rounded-[1.25rem] border border-border/60 bg-[linear-gradient(180deg,rgba(255,255,255,0.98),rgba(255,251,243,0.96))] p-2 shadow-[0_22px_55px_rgba(15,23,42,0.12)]"

  return (
    <header className="sticky top-0 z-40 w-full border-b border-border/50 bg-white/92 shadow-[0_10px_35px_rgba(15,23,42,0.06)] backdrop-blur supports-[backdrop-filter]:bg-white/80">
      <div className="mx-auto w-full max-w-[var(--public-shell-max)] px-4 sm:px-5 lg:px-6">
        <div className="flex h-[var(--header-height)] items-center justify-between gap-3 lg:gap-6">
          {/* Logo */}
          <Link
            href="/"
            className="flex min-w-0 flex-shrink-0 items-center gap-2 rounded-full"
          >
            <Image
              src="/rmv-logo.png"
              alt="Rocky Mountain Vending"
              width={220}
              height={55}
              className="h-12 sm:h-14 w-auto object-contain"
              priority
            />
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden flex-1 items-center justify-center gap-1 md:flex lg:gap-2">
            <Link href="/" className={desktopLinkClassName}>
              Home
            </Link>

            {/* Who We Serve Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger
                className={cn(
                  desktopLinkClassName,
                  "gap-1.5 data-[state=open]:text-primary"
                )}
              >
                Who We Serve
                <ChevronDown className="h-4 w-4" aria-hidden="true" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="start"
                className={cn("w-56", desktopDropdownClassName)}
              >
                {whoWeServeItems.map((item) => (
                  <DropdownMenuItem
                    key={item.href}
                    asChild
                    className="rounded-xl px-3 py-2.5"
                  >
                    <Link href={item.href}>{item.label}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Vending Machines Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger
                className={cn(
                  desktopLinkClassName,
                  "gap-1.5 data-[state=open]:text-primary"
                )}
              >
                Vending Machines
                <ChevronDown className="h-4 w-4" aria-hidden="true" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="start"
                className={cn("w-64", desktopDropdownClassName)}
              >
                {vendingMachinesItems.map((item) => (
                  <DropdownMenuItem
                    key={item.href}
                    asChild
                    className="rounded-xl px-3 py-2.5"
                  >
                    <Link href={item.href}>{item.label}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Food and Beverage Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger
                className={cn(
                  desktopLinkClassName,
                  "gap-1.5 whitespace-nowrap data-[state=open]:text-primary"
                )}
              >
                Food & Beverage
                <ChevronDown className="h-4 w-4" aria-hidden="true" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="start"
                className={cn("w-64", desktopDropdownClassName)}
              >
                {foodBeverageItems.map((item) => (
                  <DropdownMenuItem
                    key={item.href}
                    asChild
                    className="rounded-xl px-3 py-2.5"
                  >
                    <Link href={item.href}>{item.label}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Services Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger
                className={cn(
                  desktopLinkClassName,
                  "gap-1.5 data-[state=open]:text-primary"
                )}
              >
                Services
                <ChevronDown className="h-4 w-4" aria-hidden="true" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="start"
                className={cn("w-72", desktopDropdownClassName)}
              >
                {servicesItems.map((item) => (
                  <DropdownMenuItem
                    key={item.href}
                    asChild
                    className="rounded-xl px-3 py-2.5"
                  >
                    <Link href={item.href}>{item.label}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* Blog Posts Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger
                className={cn(
                  desktopLinkClassName,
                  "gap-1.5 data-[state=open]:text-primary"
                )}
              >
                Blog Posts
                <ChevronDown className="h-4 w-4" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="start"
                className={cn("w-56", desktopDropdownClassName)}
              >
                {blogPostsItems.map((item) => (
                  <DropdownMenuItem
                    key={item.href}
                    asChild
                    className="rounded-xl px-3 py-2.5"
                  >
                    <Link href={item.href}>{item.label}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* About Us Dropdown */}
            <DropdownMenu>
              <DropdownMenuTrigger
                className={cn(
                  desktopLinkClassName,
                  "gap-1.5 data-[state=open]:text-primary"
                )}
              >
                About Us
                <ChevronDown className="h-4 w-4" />
              </DropdownMenuTrigger>
              <DropdownMenuContent
                align="start"
                className={cn("w-56", desktopDropdownClassName)}
              >
                {aboutItems.map((item) => (
                  <DropdownMenuItem
                    key={item.href}
                    asChild
                    className="rounded-xl px-3 py-2.5"
                  >
                    <Link href={item.href}>{item.label}</Link>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            <Link href="/products" className={desktopLinkClassName}>
              Products
            </Link>
            <Link href="/service-areas" className={desktopLinkClassName}>
              Service Areas
            </Link>
            <Link href="/contact-us" className={desktopLinkClassName}>
              Contact Us
            </Link>
          </nav>

          {/* Desktop CTA */}
          <div className="hidden flex-shrink-0 items-center gap-2 md:flex lg:gap-3">
            <CartButton
              onClick={() => dispatch({ type: "SET_CART", value: true })}
            />
            <a
              href="tel:+14352339668"
              className="inline-flex min-h-11 items-center gap-2 rounded-full border border-border/60 bg-white px-4 text-sm font-medium text-foreground transition hover:border-primary/35 hover:text-primary"
            >
              <Phone className="h-4 w-4 flex-shrink-0" />
              <span className="hidden lg:inline">(435) 233-9668</span>
            </a>
            <Button
              onClick={() => dispatch({ type: "SET_MODAL", value: true })}
              className="h-11 whitespace-nowrap rounded-full bg-primary px-5 hover:bg-primary/90"
              size="lg"
            >
              Get Free Machine
            </Button>
          </div>

          {/* Mobile Menu Button */}
          <button
            className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-border/60 bg-white text-foreground transition hover:border-primary/35 hover:text-primary focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-primary/15 md:hidden"
            onClick={() => dispatch({ type: "TOGGLE_MENU" })}
            aria-label="Toggle menu"
            aria-expanded={state.isMenuOpen}
          >
            {state.isMenuOpen ? (
              <X className="h-6 w-6" />
            ) : (
              <Menu className="h-6 w-6" />
            )}
          </button>
        </div>

        {/* Mobile Navigation */}
        {state.isMenuOpen && (
          <nav className="border-t border-border/40 py-5 md:hidden">
            <div className="rounded-[1.5rem] border border-border/60 bg-white/95 p-3 shadow-[0_18px_48px_rgba(15,23,42,0.08)]">
              <div className="flex flex-col gap-2">
                <Link
                  href="/"
                  className={mobileLinkClassName}
                  onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                >
                  Home
                </Link>

                {/* Who We Serve Mobile Section */}
                <div className="flex flex-col gap-2 rounded-[1.25rem] border border-border/50 bg-muted/20 p-2">
                  <button
                    onClick={() => dispatch({ type: "TOGGLE_WHO_WE_SERVE" })}
                    className={mobileGroupButtonClassName}
                    aria-label="Who We Serve menu"
                    aria-expanded={state.isWhoWeServeOpen}
                    aria-haspopup="true"
                  >
                    Who We Serve
                    <ChevronDown
                      className={`h-4 w-4 transition-transform ${state.isWhoWeServeOpen ? "rotate-180" : ""}`}
                      aria-hidden="true"
                    />
                  </button>
                  {state.isWhoWeServeOpen && (
                    <div className="flex flex-col gap-2 border-l border-border/60 pl-4">
                      {whoWeServeItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={mobileLinkClassName}
                          onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                {/* Vending Machines Mobile */}
                <div className="flex flex-col gap-2 rounded-[1.25rem] border border-border/50 bg-muted/20 p-2">
                  <button
                    onClick={() =>
                      dispatch({ type: "TOGGLE_VENDING_MACHINES" })
                    }
                    className={mobileGroupButtonClassName}
                    aria-label="Vending Machines menu"
                    aria-expanded={state.isVendingMachinesOpen}
                    aria-haspopup="true"
                  >
                    Vending Machines
                    <ChevronDown
                      className={`h-4 w-4 transition-transform ${state.isVendingMachinesOpen ? "rotate-180" : ""}`}
                      aria-hidden="true"
                    />
                  </button>
                  {state.isVendingMachinesOpen && (
                    <div className="flex flex-col gap-2 border-l border-border/60 pl-4">
                      {vendingMachinesItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={mobileLinkClassName}
                          onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                {/* Food and Beverage Mobile */}
                <div className="flex flex-col gap-2 rounded-[1.25rem] border border-border/50 bg-muted/20 p-2">
                  <button
                    onClick={() => dispatch({ type: "TOGGLE_FOOD_BEVERAGE" })}
                    className={mobileGroupButtonClassName}
                    aria-label="Food & Beverage menu"
                    aria-expanded={state.isFoodBeverageOpen}
                    aria-haspopup="true"
                  >
                    Food & Beverage
                    <ChevronDown
                      className={`h-4 w-4 transition-transform ${state.isFoodBeverageOpen ? "rotate-180" : ""}`}
                      aria-hidden="true"
                    />
                  </button>
                  {state.isFoodBeverageOpen && (
                    <div className="flex flex-col gap-2 border-l border-border/60 pl-4">
                      {foodBeverageItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={mobileLinkClassName}
                          onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                {/* Services Mobile */}
                <div className="flex flex-col gap-2 rounded-[1.25rem] border border-border/50 bg-muted/20 p-2">
                  <button
                    onClick={() => dispatch({ type: "TOGGLE_SERVICES" })}
                    className={mobileGroupButtonClassName}
                    aria-label="Services menu"
                    aria-expanded={state.isServicesOpen}
                    aria-haspopup="true"
                  >
                    Services
                    <ChevronDown
                      className={`h-4 w-4 transition-transform ${state.isServicesOpen ? "rotate-180" : ""}`}
                      aria-hidden="true"
                    />
                  </button>
                  {state.isServicesOpen && (
                    <div className="flex flex-col gap-2 border-l border-border/60 pl-4">
                      {servicesItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={mobileLinkClassName}
                          onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                {/* Blog Posts Mobile */}
                <div className="flex flex-col gap-2 rounded-[1.25rem] border border-border/50 bg-muted/20 p-2">
                  <button
                    onClick={() => dispatch({ type: "TOGGLE_BLOG_POSTS" })}
                    className={mobileGroupButtonClassName}
                    aria-label="Blog Posts menu"
                    aria-expanded={state.isBlogPostsOpen}
                    aria-haspopup="true"
                  >
                    Blog Posts
                    <ChevronDown
                      className={`h-4 w-4 transition-transform ${state.isBlogPostsOpen ? "rotate-180" : ""}`}
                      aria-hidden="true"
                    />
                  </button>
                  {state.isBlogPostsOpen && (
                    <div className="flex flex-col gap-2 border-l border-border/60 pl-4">
                      {blogPostsItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={mobileLinkClassName}
                          onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                {/* About Us Mobile */}
                <div className="flex flex-col gap-2 rounded-[1.25rem] border border-border/50 bg-muted/20 p-2">
                  <button
                    onClick={() => dispatch({ type: "TOGGLE_ABOUT" })}
                    className={mobileGroupButtonClassName}
                    aria-label="About menu"
                    aria-expanded={state.isAboutOpen}
                    aria-haspopup="true"
                  >
                    About Us
                    <ChevronDown
                      className={`h-4 w-4 transition-transform ${state.isAboutOpen ? "rotate-180" : ""}`}
                      aria-hidden="true"
                    />
                  </button>
                  {state.isAboutOpen && (
                    <div className="flex flex-col gap-2 border-l border-border/60 pl-4">
                      {aboutItems.map((item) => (
                        <Link
                          key={item.href}
                          href={item.href}
                          className={mobileLinkClassName}
                          onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                        >
                          {item.label}
                        </Link>
                      ))}
                    </div>
                  )}
                </div>

                <Link
                  href="/products"
                  className={mobileLinkClassName}
                  onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                >
                  Products
                </Link>
                <Link
                  href="/service-areas"
                  className={mobileLinkClassName}
                  onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                >
                  Service Areas
                </Link>
                <Link
                  href="/contact-us"
                  className={mobileLinkClassName}
                  onClick={() => dispatch({ type: "TOGGLE_MENU" })}
                >
                  Contact Us
                </Link>

                <div className="mt-3 flex flex-col gap-3 border-t border-border/40 pt-4">
                  <MobileCartButton
                    onClick={() => {
                      dispatch({ type: "TOGGLE_MENU" })
                      dispatch({ type: "SET_CART", value: true })
                    }}
                  />
                  <a
                    href="tel:+14352339668"
                    className="inline-flex min-h-11 items-center justify-center gap-2 rounded-full border border-border/60 bg-white px-4 text-sm font-medium text-foreground transition hover:border-primary/35 hover:text-primary"
                  >
                    <Phone className="h-4 w-4" />
                    <span>(435) 233-9668</span>
                  </a>
                  <Button
                    onClick={() => {
                      dispatch({ type: "TOGGLE_MENU" })
                      dispatch({ type: "SET_MODAL", value: true })
                    }}
                    className="h-11 w-full rounded-full bg-primary hover:bg-primary/90"
                  >
                    Get Free Machine
                  </Button>
                </div>
              </div>
            </div>
          </nav>
        )}
      </div>
      <GetFreeMachineModal
        open={state.isModalOpen}
        onOpenChange={(value) => dispatch({ type: "SET_MODAL", value })}
      />
      <Cart
        isOpen={state.isCartOpen}
        onClose={() => dispatch({ type: "SET_CART", value: false })}
      />
    </header>
  )
}
