"use client";

import { Bell, Search, User, Settings, LogOut, Menu, X } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SimpleTooltip } from "@/components/ui/tooltip";
import { useRouter } from "next/navigation";
import { useUserStore, useUIStore } from "@/store";
import { getInitials } from "@/lib/utils";
import { ThemeToggle } from "@/components/ui/theme-toggle";
import { useState } from "react";

export function Header() {
  const router = useRouter();
  const { email, displayName, clearUser } = useUserStore();
  const mobileSidebarOpen    = useUIStore((s) => s.mobileSidebarOpen);
  const setMobileSidebarOpen = useUIStore((s) => s.setMobileSidebarOpen);

  const [mobileSearchOpen, setMobileSearchOpen] = useState(false);

  const handleSignOut = () => {
    clearUser();
    // Clear all token storage locations
    sessionStorage.removeItem("auth_token");
    sessionStorage.removeItem("auth_email");
    document.cookie = "auth_token=; path=/; max-age=0";
    router.push("/login");
  };

  const initials = displayName ? getInitials(displayName) : email ? getInitials(email) : "U";

  return (
    <header className="flex h-16 items-center justify-between border-b border-gray-200 bg-white px-4 md:px-6 dark:border-gray-800 dark:bg-gray-900 shrink-0">

      {/* Left — hamburger (mobile) + search (desktop) */}
      <div className="flex items-center gap-3 flex-1 min-w-0">
        {/* Hamburger — mobile only */}
        <SimpleTooltip content="Toggle navigation">
          <button
            onClick={() => setMobileSidebarOpen(!mobileSidebarOpen)}
            className="flex md:hidden h-9 w-9 items-center justify-center rounded-lg text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800 shrink-0"
            aria-label="Toggle menu"
          >
            <Menu className="h-5 w-5" />
          </button>
        </SimpleTooltip>

        {/* Search — desktop */}
        <div className="relative hidden md:block w-72">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400 dark:text-gray-500" />
          <Input
            placeholder="Search meetings..."
            className="pl-9 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-100 dark:placeholder:text-gray-500"
          />
        </div>

        {/* Mobile search expanded */}
        {mobileSearchOpen && (
          <div className="flex md:hidden flex-1 items-center gap-2">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <Input
                placeholder="Search meetings..."
                className="pl-9 h-9"
                autoFocus
              />
            </div>
            <SimpleTooltip content="Close search">
              <button
                onClick={() => setMobileSearchOpen(false)}
                className="h-9 w-9 flex items-center justify-center rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-800 shrink-0"
              >
                <X className="h-4 w-4" />
              </button>
            </SimpleTooltip>
          </div>
        )}
      </div>

      {/* Right — actions */}
      <div className={`flex items-center gap-1.5 shrink-0 ${mobileSearchOpen ? "hidden" : "flex"}`}>
        {/* Search icon — mobile only */}
        <SimpleTooltip content="Search meetings">
          <button
            onClick={() => setMobileSearchOpen(true)}
            className="flex md:hidden h-9 w-9 items-center justify-center rounded-lg text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"
            aria-label="Search"
          >
            <Search className="h-5 w-5" />
          </button>
        </SimpleTooltip>

        {/* Dark mode toggle */}
        <ThemeToggle />

        {/* Notifications */}
        <SimpleTooltip content="View notifications">
          <Button variant="ghost" size="icon" className="relative dark:hover:bg-gray-800">
            <Bell className="h-5 w-5" />
            <span className="absolute right-2 top-2 h-2 w-2 rounded-full bg-blue-600" />
          </Button>
        </SimpleTooltip>

        {/* User menu */}
        <DropdownMenu>
          <SimpleTooltip content="Account menu">
            <DropdownMenuTrigger asChild>
              <button className="flex items-center gap-2 rounded-full pl-1 pr-1 sm:pr-2 py-1 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500">
                <Avatar className="h-8 w-8">
                  <AvatarFallback className="bg-gradient-to-br from-blue-500 to-indigo-600 text-white text-xs font-semibold">
                    {initials}
                  </AvatarFallback>
                </Avatar>
                <div className="hidden sm:block text-left">
                  <p className="text-sm font-medium text-gray-900 dark:text-gray-100 leading-none">{displayName || "User"}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 truncate max-w-[120px]">{email}</p>
                </div>
              </button>
            </DropdownMenuTrigger>
          </SimpleTooltip>

          <DropdownMenuContent align="end" className="w-56 dark:bg-gray-900 dark:border-gray-700">
            <DropdownMenuLabel className="pb-2">
              <div className="flex items-center gap-2.5">
                <Avatar className="h-9 w-9">
                  <AvatarFallback className="bg-gradient-to-br from-blue-500 to-indigo-600 text-white text-xs font-semibold">
                    {initials}
                  </AvatarFallback>
                </Avatar>
                <div className="min-w-0">
                  <p className="text-sm font-semibold text-gray-900 dark:text-gray-100 truncate">{displayName || "User"}</p>
                  <p className="text-xs text-gray-500 dark:text-gray-400 truncate">{email}</p>
                </div>
              </div>
            </DropdownMenuLabel>

            <DropdownMenuSeparator className="dark:bg-gray-700" />

            <DropdownMenuItem className="gap-2 cursor-pointer dark:hover:bg-gray-800" onClick={() => router.push("/profile")}>
              <User className="h-4 w-4 text-gray-500 dark:text-gray-400" />
              Profile
            </DropdownMenuItem>
            <DropdownMenuItem className="gap-2 cursor-pointer dark:hover:bg-gray-800" onClick={() => router.push("/settings")}>
              <Settings className="h-4 w-4 text-gray-500 dark:text-gray-400" />
              Settings
            </DropdownMenuItem>

            <DropdownMenuSeparator className="dark:bg-gray-700" />

            <DropdownMenuItem
              className="gap-2 cursor-pointer text-red-600 focus:text-red-600 focus:bg-red-50 dark:focus:bg-red-950"
              onClick={handleSignOut}
            >
              <LogOut className="h-4 w-4" />
              Sign out
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
