"use client";

import React, { useState } from "react";
import { useAppSelector } from "@/lib/store";
import { useLogout } from "@/modules/auth/hooks/auth.hooks";
import { Button } from "@/components/ui/button";
import {
  LogOut,
  Bell,
  Check,
  ChevronDown,
  User as UserIcon,
  Building2,
  Loader2,
} from "lucide-react";
import { useRouter, usePathname } from "next/navigation";
import { SidebarTrigger } from "@/components/ui/sidebar";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { useGetNotifications, useMarkNotificationAsRead, useUnreadCount } from "../../modules/notifications/hook/notification.hook"
import { formatDistanceToNow } from "date-fns";

const roleLabelMap: Record<string, string> = {
  SUPERADMIN: "Super Admin",
  ADMIN: "Admin",
  MANAGER: "Manager",
  EMPLOYEE: "Staff",
  CLIENT: "Client",
  PARTNER: "Partner",
};

export default function Header() {
  const { user } = useAppSelector((state) => state.auth);
  const { mutate: logout } = useLogout();
  const router = useRouter();
  const pathname = usePathname();

  const { data: unreadCount = 0 } = useUnreadCount();
  const { data, isLoading } = useGetNotifications({ page: 1, limit: 10 });
  const { mutate: markAsRead } = useMarkNotificationAsRead();
  const notifications = data?.data ?? [];


  const handleLogout = () =>
    logout(undefined, { onSuccess: () => router.replace("/login") });

  return (
    <header className="sticky top-0 z-40 flex h-16 w-full items-center justify-between border-b border-border bg-card/90 px-6 backdrop-blur-md">
      <div className="flex items-center gap-4">
        <SidebarTrigger className="text-muted-foreground hover:text-foreground" />
      </div>

        <div className="flex items-center gap-3">
        {/* Notifications */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="relative text-muted-foreground hover:text-foreground hover:bg-secondary rounded-xl"
            >
              <Bell className="h-4 w-4" />
              {unreadCount > 0 && (
                <span className="absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-[hsl(var(--warning))] ring-2 ring-background" />
              )}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-80 p-0">
            <div className="flex items-center justify-between border-b border-border px-4 py-3 bg-secondary/40">
              <span className="font-semibold text-sm">Notifications</span>
              {unreadCount > 0 && (
                <span className="text-xs text-primary flex items-center gap-1">
                  <Check className="h-3 w-3" /> {unreadCount} unread
                </span>
              )}
            </div>
            <div className="max-h-80 overflow-y-auto no-scrollbar divide-y divide-border/50">
              {isLoading ? (
                <div className="flex items-center justify-center py-8">
                  <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
                </div>
              ) : notifications.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-10 gap-2">
                  <Bell className="h-6 w-6 text-muted-foreground/30" />
                  <p className="text-xs text-muted-foreground">
                    No notifications yet
                  </p>
                </div>
              ) : (
                notifications.map((n) => {
                  const isUnread = n.status !== "READ";
                  return (
                    <button
                      key={n.id}
                      onClick={() => isUnread && markAsRead(n.id)}
                      className={`w-full text-left px-4 py-3 hover:bg-secondary/40 transition-colors ${
                        isUnread ? "bg-primary/5" : ""
                      }`}
                    >
                      <div className="flex justify-between items-start mb-1 gap-2">
                        <span
                          className={`text-sm font-medium ${
                            isUnread
                              ? "text-foreground"
                              : "text-muted-foreground"
                          }`}
                        >
                          {n.title}
                        </span>
                        {isUnread && (
                          <span className="w-2 h-2 rounded-full bg-primary flex-shrink-0 mt-1.5" />
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground line-clamp-2">
                        {n.message}
                      </p>
                      <p className="text-[10px] text-muted-foreground/50 mt-1">
                        {formatDistanceToNow(new Date(n.createdAt), {
                          addSuffix: true,
                        })}
                      </p>
                    </button>
                  );
                })
              )}
            </div>
          </DropdownMenuContent>
        </DropdownMenu>

        {/* User menu */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <button suppressHydrationWarning className="flex items-center gap-2 rounded-xl bg-background border border-border pl-2 pr-2.5 py-1 hover:bg-secondary/40 transition-colors">
              <div className="flex h-8 w-8 items-center justify-center rounded-lg overflow-hidden bg-primary/10 text-primary border border-primary/20 flex-shrink-0">
                {user?.avatarUrl ? (
                  <img src={user.avatarUrl} alt={user.name} className="w-full h-full object-cover" />
                ) : (
                  <UserIcon className="h-4 w-4" />
                )}
              </div>
              <div className="hidden sm:flex flex-col text-left">
                <span className="text-xs font-semibold text-foreground leading-tight">
                  {user?.name || "User"}
                </span>
                <span className="text-[10px] text-muted-foreground leading-tight">
                  {roleLabelMap[user?.role ?? ""] ?? ""}
                </span>
              </div>
              <ChevronDown className="h-3.5 w-3.5 text-muted-foreground hidden sm:block" />
            </button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-52">
            <DropdownMenuItem
              onClick={() => router.push("/profile?tab=profile")}
              className="cursor-pointer gap-2"
            >
              <UserIcon className="h-4 w-4" /> My Profile
            </DropdownMenuItem>
            {user?.role === "ADMIN" && (
              <DropdownMenuItem
                onClick={() => router.push("/profile?tab=organization")}
                className="cursor-pointer gap-2"
              >
                <Building2 className="h-4 w-4" /> My Organization
              </DropdownMenuItem>
            )}
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onClick={handleLogout}
              className="cursor-pointer gap-2 text-destructive focus:text-destructive"
            >
              <LogOut className="h-4 w-4" /> Logout
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  );
}
