"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Link } from "react-router-dom";
import {
  Shield,
  ChevronDown,
  Heart,
  LogOut,
  Menu,
  Phone,
  Settings,
  User,
  UserCircle2,
  X,
} from "lucide-react";
import { usePublicSession } from "@/components/public/PublicSessionProvider";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { logoutAction } from "@/lib/auth-actions";
import { logoutPublicAction } from "@/lib/public-auth-actions";

const navItems = [
  { label: "Продажби", href: "/properties?deal=sale" },
  { label: "Наеми", href: "/properties?deal=rent" },
  { label: "Оценка", href: "/evaluate" },
  { label: "Контакти", href: "/contact" },
  { label: "Блог", href: "/blog" },
];

const Navbar = () => {
  const [mobileOpen, setMobileOpen] = useState(false);
  const router = useRouter();
  const { accountType, accountUser, adminUser, refreshSession, user } = usePublicSession();

  const publicAccountLinks = [
    { href: "/profile", label: "Профил", icon: UserCircle2 },
    { href: "/my-inquiries", label: "Направени запитвания", icon: User },
    { href: "/favorites", label: "Любими", icon: Heart },
  ];

  const adminAccountLinks = [
    { href: "/admin", label: "Админ панел", icon: Shield },
    { href: "/admin/settings", label: "Настройки", icon: Settings },
  ];

  const accountLinks = accountType === "admin" ? adminAccountLinks : publicAccountLinks;
  const firstName = accountUser?.fullName.split(" ")[0] || "потребител";

  const handleLogout = async () => {
    if (accountType === "admin") {
      await logoutAction();
      await refreshSession();
      setMobileOpen(false);
      router.push("/login");
      router.refresh();
      return;
    }

    await logoutPublicAction();
    await refreshSession();
    setMobileOpen(false);
    router.push("/");
    router.refresh();
  };

  return (
    <header className="fixed top-0 left-0 right-0 z-[60] bg-card/95 backdrop-blur-md border-b border-border/50">
      <div className="container mx-auto flex items-center justify-between h-[70px] px-4 lg:px-8">
        <Link to="/" className="flex items-center py-2">
          <img
            src="/brand/logo.png"
            alt="Greekdream.eu"
            className="h-[54px] w-auto object-contain"
            loading="eager"
          />
        </Link>

        <nav className="hidden lg:flex items-center gap-8">
          {navItems.map((item) => (
            <Link key={item.label} to={item.href} className="nav-link">
              {item.label}
            </Link>
          ))}
        </nav>

        <div className="hidden lg:flex items-center gap-4">
          <a href="tel:+359895352522" className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-primary transition-colors">
            <Phone className="w-4 h-4" />
            <span>+359 895 352 522</span>
          </a>
          {accountUser ? (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button className="flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-navy-light">
                  {adminUser ? <Shield className="w-4 h-4" /> : <User className="w-4 h-4" />}
                  <span>Здравейте, {firstName}</span>
                  <ChevronDown className="w-4 h-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-64">
                {accountLinks.map((item) => (
                  <DropdownMenuItem key={item.href} asChild>
                    <Link to={item.href} className="flex w-full items-center gap-2">
                      <item.icon className="h-4 w-4" />
                      <span>{item.label}</span>
                    </Link>
                  </DropdownMenuItem>
                ))}
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => void handleLogout()}>
                  <LogOut className="h-4 w-4" />
                  <span>Изход</span>
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          ) : (
            <Link to="/login" className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-primary text-primary-foreground text-sm font-medium hover:bg-navy-light transition-colors">
              <User className="w-4 h-4" />
              <span>Вход</span>
            </Link>
          )}
        </div>

        <button
          className="lg:hidden p-2 text-primary"
          onClick={() => setMobileOpen(!mobileOpen)}
        >
          {mobileOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
        </button>
      </div>

      {mobileOpen && (
        <div className="lg:hidden bg-card border-t border-border animate-fade-in">
          <nav className="flex flex-col p-4 gap-1">
            {navItems.map((item) => (
              <Link
                key={item.label}
                to={item.href}
                onClick={() => setMobileOpen(false)}
                className="px-4 py-3 rounded-lg text-sm font-medium text-foreground hover:bg-secondary transition-colors"
              >
                {item.label}
              </Link>
            ))}
            <div className="border-t border-border mt-2 pt-2">
              <a href="tel:+359895352522" className="flex items-center gap-2 px-4 py-3 text-sm text-muted-foreground">
                <Phone className="w-4 h-4" />
                +359 895 352 522
              </a>
              {accountUser ? (
                <div className="mt-1 space-y-1">
                  <div className="px-4 py-2 text-sm font-medium text-foreground">
                    Здравейте, {firstName}
                  </div>
                  {accountLinks.map((item) => (
                    <Link
                      key={item.href}
                      to={item.href}
                      onClick={() => setMobileOpen(false)}
                      className="flex items-center gap-2 px-4 py-3 rounded-lg text-sm font-medium text-foreground hover:bg-secondary transition-colors"
                    >
                      <item.icon className="w-4 h-4" />
                      {item.label}
                    </Link>
                  ))}
                  <button
                    type="button"
                    onClick={() => void handleLogout()}
                    className="w-full text-left flex items-center gap-2 px-4 py-3 rounded-lg text-sm font-medium text-foreground hover:bg-secondary transition-colors"
                  >
                    <LogOut className="w-4 h-4" />
                    Изход
                  </button>
                </div>
              ) : (
                <Link to="/login" onClick={() => setMobileOpen(false)} className="w-full mt-1 px-4 py-3 rounded-lg bg-primary text-primary-foreground text-sm font-medium text-center block">
                  Вход
                </Link>
              )}
            </div>
          </nav>
        </div>
      )}
    </header>
  );
};

export default Navbar;
