import React from "react"
import { Button } from "@/Components/UI/Button"
import { NavLink } from "@/Components/UI/NavLink"

import { Avatar, AvatarFallback, AvatarImage } from "@/Components/UI/Avatar"
import { Plus, FileText, Moon, Sun, Globe, ImageIcon, Bell, Settings, LogOut } from "lucide-react"
import {
  Breadcrumb,
  BreadcrumbList,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from "@/Components/UI/Breadcrumb"
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from "@/Components/UI/DropdownMenu"
import { Link } from '@inertiajs/react'
import { route } from "ziggy-js"
import { usePage, router } from '@inertiajs/react';
import { CountryFlag } from "@/Components/UI/CountryFlag"
import { useTheme } from "@/Contexts/ThemeContext";
import useTranslate from "@/hooks/useTranslate";


export default function HeaderNav({ breadcrumbs }) {

  const { theme, toggleTheme } = useTheme();

  const t = useTranslate();



  const { props } = usePage();
  const { filePaths, auth, languageProp, language } = props;


  const user = auth?.user;
  const avatarUrl = user?.avatar_url;

  const userProfileConfig = filePaths?.profile?.user || {};
  const [width, height] = (userProfileConfig.size || '150x150').split('x');

  const navItems = [
    {
      route: "user.post.create",
      icon: <Plus className="h-5 w-5" />,
    },
    {
      route: "user.gallery.index",
      icon: <ImageIcon className="h-5 w-5  dark:text-neutral-200" />,
    },
    {
      route: "user.template.index",
      icon: <FileText className="h-5 w-5  dark:text-neutral-200" />,
    },
  ]

  const handleLanguageChange = (code) => {
    if (!code) {
      return;
    }

    router.post(
      route("user.language.switch"),
      {
        code: code,
      },
      {
        preserveScroll: true,
      }
    );
  };

  const handleNotificationClick = (notificationId) => {
    if (notificationId) {
      // Mark notification as read
      router.post(
        route("user.read.notification"),
        { id: notificationId },
        {
          preserveScroll: true,
          onSuccess: () => {
            // Optionally refresh the page or update the notification state
          },
          onError: (errors) => {
            console.error('Failed to mark notification as read:', errors);
          }
        }
      );
    }
  };

  return (
    <header className="flex items-center justify-between h-16 pl-16 lg:pl-16 pr-6 bg-white dark:bg-zinc-900 border-b border-gray-200 dark:border-zinc-800">
      {/* Breadcrumbs - Hide on mobile, show on sm and up */}
      <div className="hidden sm:block">
        <Breadcrumb>
          <BreadcrumbList>
            {breadcrumbs.map((item, index) => (
              <React.Fragment key={item.label}>
                <BreadcrumbItem>
                  {item.href ? (
                    <BreadcrumbLink className="dark:text-neutral-200 text-xs sm:text-sm" href={item.href}>{item.label}</BreadcrumbLink>
                  ) : (
                    <BreadcrumbPage className="text-gray-500 dark:text-neutral-400 text-xs sm:text-sm">{item.label}</BreadcrumbPage>
                  )}
                </BreadcrumbItem>
                {index < breadcrumbs.length - 1 && <BreadcrumbSeparator className="dark:text-neutral-200" />}
              </React.Fragment>
            ))}
          </BreadcrumbList>
        </Breadcrumb>
      </div>

      {/* Mobile breadcrumb - Show only current page */}
      <div className="sm:hidden flex items-center lg:pl-12 pl-6">
        <span className="text-sm font-medium text-gray-700 dark:text-gray-200">
          {breadcrumbs[breadcrumbs.length - 1]?.label || "Dashboard"}
        </span>
      </div>

      <div className="flex items-center space-x-2 sm:space-x-4">

        {/* Nav Items - Hide on mobile */}
        <div className="hidden md:flex items-center space-x-4">
          {navItems.map((item, index) => (
            <NavLink
              key={index}
              href={route(item.route)}
              active={route().current(item.route)}
            >
              {item.icon}
            </NavLink>
          ))}
        </div>

        {/* Theme Toggle - Always visible */}
        <Button variant="ghost" size="icon" onClick={toggleTheme} className="h-8 w-8 sm:h-10 sm:w-10">
          {theme === "light" ? (
            <Moon className="h-4 w-4 sm:h-5 sm:w-5 text-gray-600 dark:text-neutral-200" />
          ) : (
            <Sun className="h-4 w-4 sm:h-5 sm:w-5 text-yellow-400" />
          )}
        </Button>

        {/* Language Dropdown - Hide on mobile */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="hidden sm:inline-flex">
              {language && <CountryFlag code={language.code} size="26px" round={true} /> || <Globe className="h-5 w-5 text-gray-600" />}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-40 max-h-36 overflow-y-auto" align="end" forceMount>
            {languageProp.map((language, index) => (

              <DropdownMenuItem
                key={index}
                className="flex items-center  text-gray-600 cursor-pointer hover:bg-gray-100 focus:bg-gray-100"
                onClick={() => handleLanguageChange(language.code)}
              >
                <CountryFlag code={language.code} size="20px" />
                {language.name}
              </DropdownMenuItem>
            ))}
          </DropdownMenuContent>
        </DropdownMenu>
        {/* Notification Dropdown */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="relative h-8 w-8 sm:h-10 sm:w-10">
              <Bell className="h-4 w-4 sm:h-5 sm:w-5 text-gray-600 dark:text-neutral-200" />
              {/* Notification badge */}
              {(props.unread_notifications_count > 0) && (
                <span className="absolute -top-0.5 -right-0.5 sm:-top-1 sm:-right-1 bg-red-500 text-white text-xs rounded-full h-4 w-4 sm:h-5 sm:w-5 flex items-center justify-center font-medium">
                  {props.unread_notifications_count > 9 ? '9+' : props.unread_notifications_count}
                </span>
              )}
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-72 sm:w-80 max-h-96 overflow-y-auto" align="end" forceMount>
            <DropdownMenuLabel className="px-4 py-3 border-b">
              <div className="flex items-center justify-between">
                <span className="font-semibold">{t("Notifications")}</span>
                {(props.unread_notifications_count > 0) && (
                  <span className="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded-full">
                    {props.unread_notifications_count} {t("new")}
                  </span>
                )}
              </div>
            </DropdownMenuLabel>
            
            {/* Notifications List */}
            {props.notifications && props.notifications.length > 0 ? (
              <>
                {props.notifications.slice(0, 5).map((notification, index) => (
                  <DropdownMenuItem 
                    key={notification.id || index}
                    className="flex flex-col items-start px-4 py-3 border-b last:border-b-0 cursor-pointer hover:bg-gray-50 focus:bg-gray-50"
                    onClick={() => handleNotificationClick(notification.id)}
                  >
                    <div className="flex items-start space-x-3 w-full">
                      <div className={`w-2 h-2 rounded-full flex-shrink-0 mt-2 ${
                        notification.is_read ? 'bg-gray-300' : 'bg-blue-500'
                      }`}></div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                          {notification.title || t("New Notification")}
                        </p>
                        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1 line-clamp-2">
                          {notification.message || notification.data?.message || t("You have a new notification")}
                        </p>
                        <p className="text-xs text-gray-400 mt-1">
                          {notification.created_at ? new Date(notification.created_at).toLocaleDateString() : t("Just now")}
                        </p>
                      </div>
                    </div>
                  </DropdownMenuItem>
                ))}
                
                {/* View All Notifications Link */}
                <DropdownMenuItem asChild>
                  <Link
                    href={route("user.notification") || "#"}
                    className="flex items-center justify-center px-4 py-3 text-sm text-primary font-medium hover:bg-gray-50 focus:bg-gray-50 no-underline border-t"
                  >
                    {t("View all notifications")}
                  </Link>
                </DropdownMenuItem>
              </>
            ) : (
              <div className="px-4 py-6 text-center text-gray-500 dark:text-gray-400">
                <Bell className="h-8 w-8 mx-auto mb-2 opacity-50" />
                <p className="text-sm">{t("No notifications yet")}</p>
                <p className="text-xs mt-1">{t("We'll notify you when something arrives!")}</p>
              </div>
            )}
          </DropdownMenuContent>
        </DropdownMenu>

        {/* Dropdown Menu for Avatar */}
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="relative h-8 w-8 rounded-full">
              <Avatar className="h-8 w-8">
                <AvatarImage src={avatarUrl} alt="User Avatar" />
                <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-bold text-sm">
                  {user?.name
                    ?.split(" ")
                    .map((n) => n[0])
                    .join("")
                    .toUpperCase()
                    .slice(0, 2) || "U"}
                </AvatarFallback>
              </Avatar>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent className="w-64" align="end" forceMount>
            <DropdownMenuLabel className="p-4">
              <div className="flex items-center space-x-2">
                <Avatar className="h-10 w-10">
                  <AvatarImage src={avatarUrl} alt="User Avatar" />
                  <AvatarFallback className="bg-gradient-to-br from-primary to-secondary text-white font-bold">
                    {user?.name
                      ?.split(" ")
                      .map((n) => n[0])
                      .join("")
                      .toUpperCase()
                      .slice(0, 2) || "U"}
                  </AvatarFallback>
                </Avatar>
                <div className="flex flex-col space-y-1">
                  <p className="text-sm leading-none">{user.name}</p>
                  <p className="text-xs leading-none text-muted-foreground">{user.email}</p>
                </div>
              </div>
            </DropdownMenuLabel>
            <DropdownMenuSeparator />

            <DropdownMenuItem asChild>
              <Link
                href={route("user.profile.settings")}
                method="get"
                className="flex items-center px-4 py-2 text-gray-600 cursor-pointer hover:bg-gray-100 focus:bg-gray-100 data-[highlighted]:bg-gray-100"
              >
                <Settings className="mr-2 h-4 w-4" />
                <span>Profile Setting</span>
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem asChild>
              <Link
                href={route("user.logout")}
                method="get"
                className="flex items-center px-4 py-2 text-red-500 cursor-pointer hover:bg-gray-100 focus:bg-gray-100 data-[highlighted]:bg-gray-100"
              >
                <LogOut className="mr-2 h-4 w-4" />
                <span>Logout</span>
              </Link>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      </div>
    </header>
  )
}