"use client";

import { Button } from "@/components/ui/button";
import { Link, usePathname, useRouter } from "@/i18n/routing";
import { useUserStore } from "@/store/userStore";
import { DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu";
import { Bell, ChevronDown, Globe, Menu, Moon, Sun } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useTheme } from "next-themes";
import Image from "next/image";
import * as React from "react";
import { Avatar, AvatarFallback, AvatarImage } from "../ui/avatar";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from "../ui/dropdown-menu";

interface DashboardHeaderProps {
  onMenuClick?: () => void;
}

function firstChar(input: string | null | undefined): string {
  if (!input) return "";
  const trimmed = input.trim();
  if (!trimmed) return "";
  return [...trimmed][0]?.toUpperCase() ?? "";
}

export function DashboardHeader({ onMenuClick }: DashboardHeaderProps = {}) {
  const { theme, setTheme } = useTheme();
  const t = useTranslations("dashboard.header");
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const [mounted, setMounted] = React.useState(false);
  const [isPending, startTransition] = React.useTransition();
  const targetLocale = locale === "ar" ? "en" : "ar";
  const targetLocaleIcon =
    targetLocale === "en"
      ? "/images/login/icons/en-flag.svg"
      : "/images/login/icons/sa-flag.svg";

  const user = useUserStore((state) => state.user);
  const logout = useUserStore((state) => state.logout);

  const profile = user?.profile ?? user ?? null;

  const firstName: string = profile?.first_name ?? "";
  const lastName: string = profile?.last_name ?? "";
  const fullName = [firstName, lastName].filter(Boolean).join(" ").trim();
  const displayName = fullName || profile?.name || profile?.email || t("userName");

  const rawRole = profile?.role ?? profile?.role_name ?? null;
  const role: string =
    typeof rawRole === "string"
      ? rawRole
      : rawRole && typeof rawRole === "object"
        ? rawRole[locale] ?? rawRole.en ?? rawRole.ar ?? rawRole.name ?? ""
        : "";
  const displayRole = role || t("userRole");

  const avatarSrc: string | null =
    profile?.image ?? profile?.avatar ?? profile?.photo ?? null;

  const initials =
    `${firstChar(firstName)}${firstChar(lastName)}` ||
    firstChar(displayName) ||
    t("userInitials");

  React.useEffect(() => {
    setMounted(true);
  }, []);

  const handleLogout = React.useCallback(() => {
    logout();
    router.replace("/login");
  }, [logout, router]);

  const switchLocale = () => {
    startTransition(() => {
      router.replace(pathname, { locale: targetLocale });
    });
  };

  if (!mounted) {
    return null;
  }

  return (
    <header className="flex h-[72px] items-center justify-between border-b border-border bg-card px-4 sm:px-6">
      <Button
        variant="ghost"
        size="icon"
        className="h-10 w-10 rounded-xl lg:hidden"
        onClick={onMenuClick}
        aria-label={t("openMenu")}
      >
        <Menu className="h-5 w-5" />
      </Button>

      <div className="flex flex-1 justify-end items-center gap-2 sm:gap-3">

        <Button
          variant="outline"
          size="icon"
          className="relative h-10 w-10 rounded-xl border-border text-muted-foreground hover:bg-accent hover:text-foreground active:bg-interactive-active"
        >
          <Bell className="h-5 w-5" />
          <span className="absolute right-[7px] top-[6px] h-1.5 w-1.5 rounded-full bg-red-500" />
        </Button>

        <Button
          variant="outline"
          size="icon"
          onClick={switchLocale}
          disabled={isPending}
          aria-label={targetLocale === "en" ? t("english") : t("arabic")}
          className="h-10 w-10 rounded-xl border-border hover:bg-accent active:bg-interactive-active disabled:opacity-70"
        >
          <Image
            src={targetLocaleIcon}
            alt=""
            width={22}
            height={16}
            className="h-4 w-[22px] object-contain"
          />
        </Button>

        <Button
          variant="outline"
          size="icon"
          className="h-10 w-10 rounded-xl border-border text-muted-foreground hover:bg-accent hover:text-foreground active:bg-interactive-active"
          onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
        >
          {theme === "dark" ? (
            <Sun className="h-5 w-5" />
          ) : (
            <Moon className="h-5 w-5" />
          )}
        </Button>

        <Button
          asChild
          variant="outline"
          size="icon"
          className="h-10 w-10 rounded-xl border-border text-muted-foreground hover:bg-accent hover:text-foreground active:bg-interactive-active"
        >
          <Link href="/" target="_blank" rel="noopener noreferrer">
            <Globe className="h-5 w-5" />
          </Link>
        </Button>
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              className="h-auto gap-2 rounded-xl px-2 py-1 hover:bg-accent active:bg-interactive-active"
            >

              <div className="relative">
                <Avatar className="h-10 w-10 border border-border">
                  {avatarSrc ? (
                    <AvatarImage
                      key={avatarSrc}
                      src={avatarSrc}
                      alt={displayName}
                    />
                  ) : null}
                  <AvatarFallback>{initials}</AvatarFallback>
                </Avatar>
                <div className="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border-2 border-white bg-green-500" />
              </div>
              <div className="hidden  sm:flex sm:flex-col sm:gap-1">
                <span className="text-[13px] font-bold leading-none text-foreground">
                  {displayName}
                </span>
                <span className="text-[10px] leading-none text-muted-foreground">
                  {displayRole}
                </span>
              </div>
              <ChevronDown className="h-4 w-4 text-foreground" />

            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="start" className="w-48">
            <DropdownMenuItem
              className="cursor-pointer hover:bg-accent active:bg-interactive-active text-foreground"
              onClick={() => router.push("/dashboard/profile")}
            >
              {t("profile")}
            </DropdownMenuItem>
            <DropdownMenuItem
              className="cursor-pointer hover:bg-accent active:bg-interactive-active text-foreground"
              onClick={() => router.push("/dashboard/settings")}
            >
              {t("settings")}
            </DropdownMenuItem>
            <DropdownMenuItem
              className="text-red-500 cursor-pointer hover:bg-accent active:bg-interactive-active"
              onClick={handleLogout}
            >
              {t("logout")}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
