/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import {
  useEffect,
  useRef,
  useState,
} from "react";
import { Link, router, usePage } from "@inertiajs/react";

import styles from "./nav.module.scss";

import { HiMenuAlt3 } from "react-icons/hi";
import { IoNotificationsOutline } from "react-icons/io5";
import { MdLogout } from "react-icons/md";

import MobileSidebar from "../MobileSidebar";
// import ThemeToggle from "@/components/shared/Themetoggle";

const DashboardNavbar = () => {
  const [showMobileNav, setShowMobileNav] =
    useState(false);

  const [showDropdown, setShowDropdown] =
    useState(false);

  const [
    showNotificationDropdown,
    setShowNotificationDropdown,
  ] = useState(false);

  const {
    auth,
    navbarNotifications,
  } = usePage().props as any;

  const dropdownRef =
    useRef<HTMLDivElement>(null);

  const notificationRef =
    useRef<HTMLDivElement>(null);

  const unreadCount =
    navbarNotifications?.unread_count || 0;

  const recentNotifications =
  navbarNotifications?.recent || [];


 const getInitials = (name = "") => {
    return name
      .trim()
      .split(" ")
      .filter(Boolean)
      .slice(0, 2)
      .map((word) => word[0])
      .join("")
      .toUpperCase();
  };

  const toggleMobileSidebar = () => {
    setShowMobileNav((prev) => !prev);
  };

  const toggleDropdown = () => {
    setShowDropdown((prev) => !prev);

    if (showNotificationDropdown) {
      setShowNotificationDropdown(false);
    }
  };

  const toggleNotifications = () => {
    setShowNotificationDropdown(
      (prev) => !prev
    );

    if (showDropdown) {
      setShowDropdown(false);
    }
  };

  const handleLogout = () => {
    router.post("/logout");
  };
  
  const closeAllDropdowns = () => {
  setShowDropdown(false)
  setShowNotificationDropdown(false)
}
  useEffect(() => {
    const handleClickOutside = (
      event: MouseEvent
    ) => {
      const target =
        event.target as Node;

      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(
          target
        )
      ) {
        setShowDropdown(false);
      }

      if (
        notificationRef.current &&
        !notificationRef.current.contains(
          target
        )
      ) {
        setShowNotificationDropdown(
          false
        );
      }
    };

    document.addEventListener(
      "mousedown",
      handleClickOutside
    );

    return () => {
      document.removeEventListener(
        "mousedown",
        handleClickOutside
      );
    };
  }, []);

  useEffect(() => {
  setShowDropdown(false)
  setShowNotificationDropdown(false)
}, [])

  return (
    <>
      {showMobileNav && (
        <MobileSidebar
          closeBar={
            toggleMobileSidebar
          }
          user={auth?.user}
        />
      )}

      <nav className={styles.nav}>
        {/* LEFT */}

        <div className={styles.left}>
          {/* <span
            className={
              styles.welcomeText
            }
          >
            Welcome back,
          </span> */}

          <h4
            className={
              styles.userName
            }
          >
            Welcome back,
            {/* {auth?.user
              ?.username || "Investor"} */}
          </h4>
        </div>

        {/* RIGHT */}

        <div className={styles.right}>
          {/* <ThemeToggle /> */}

          {/* NOTIFICATIONS */}

          <div
            className={
              styles.notificationWrapper
            }
            ref={notificationRef}
          >
            <button
              type="button"
              className={
                styles.iconBtn
              }
              onClick={
                toggleNotifications
              }
            >
              <IoNotificationsOutline
                size={22}
              />

              {unreadCount > 0 && (
                <span
                  className={
                    styles.badge
                  }
                >
                  {unreadCount >
                  99
                    ? "99+"
                    : unreadCount}
                </span>
              )}
            </button>

            {showNotificationDropdown && (
              <div
                className={
                  styles.notificationDropdown
                }
              >
                <div
                  className={
                    styles.notificationDropdown__header
                  }
                >
                  <div>
                    <h5>
                      Notifications
                    </h5>

                    <p>
                      Recent account
                      activity
                    </p>
                  </div>

                  <Link
                    href="/dashboard/notifications"
                     onClick={closeAllDropdowns}
                  >
                    View All
                  </Link>
                </div>

                {recentNotifications?.length >
                0 ? (
                  <div
                    className={
                      styles.notificationDropdown__list
                    }
                  >
                    {recentNotifications.map(
                      (
                        item: any
                      ) => (
                        <Link
                          key={
                            item.id
                          }
                          href="/dashboard/notifications"
                           onClick={closeAllDropdowns}
                          className={
                            styles.notificationItem
                          }
                        >
                          <div
                            className={
                              styles.notificationItem__top
                            }
                          >
                            <h6>
                              {
                                item.title
                              }
                            </h6>

                            {!item.read_at && (
                              <span
                                className={
                                  styles.notificationDot
                                }
                              />
                            )}
                          </div>

                          <p>
                            {
                              item.message
                            }
                          </p>
                        </Link>
                      )
                    )}
                  </div>
                ) : (
                  <div
                    className={
                      styles.notificationEmpty
                    }
                  >
                    <IoNotificationsOutline
                      size={28}
                    />

                    <p>
                      No recent
                      notifications
                    </p>
                  </div>
                )}
              </div>
            )}
          </div>

          {/* PROFILE */}

          <div
            className={
              styles.avatarWrapper
            }
            ref={dropdownRef}
          >
            <button
              type="button"
              onClick={
                toggleDropdown
              }
              className={
                styles.avatarSection
              }
            >
              <div
                className={
                  styles.avatar
                }
              >
                {getInitials(auth?.user?.name)}
              </div>

              <div
                className={
                  styles.userDetails
                }
              >
                <span
                  className={
                    styles.username
                  }
                >
                  {
                    auth?.user
                      ?.firstName
                  }
                </span>

                {/* <small>
                  Investor
                </small> */}
              </div>
            </button>

            {showDropdown && (
              <div
                className={
                  styles.dropdown
                }
              >
                <div
                  className={
                    styles.dropdownHeader
                  }
                >
                  <div
                    className={
                      styles.dropdownAvatar
                    }
                  >
                    {getInitials(auth?.user?.name)}
                  </div>

                  <div
                    className={
                      styles.userInfo
                    }
                  >
                    <span
                      className={
                        styles.name
                      }
                    >
                      {
                        auth
                          ?.user
                          ?.firstName
                      }{" "}
                      {
                        auth
                          ?.user
                          ?.lastName
                      }
                    </span>

                    <span
                      className={
                        styles.email
                      }
                    >
                      {
                        auth
                          ?.user
                          ?.email
                      }
                    </span>
                  </div>
                </div>

                <div
                  className={
                    styles.dropdownLinks
                  }
                >
                  <Link
                    href="/dashboard/account"
                     onClick={closeAllDropdowns}
                    className={
                      styles.dropdownLink
                    }
                  >
                    Account
                  </Link>

                  <Link
                    href="/dashboard/kyc"
                     onClick={closeAllDropdowns}
                    className={
                      styles.dropdownLink
                    }
                  >
                    KYC Verification
                  </Link>

                  <Link
                    href="/dashboard/contact-us"
                     onClick={closeAllDropdowns}
                    className={
                      styles.dropdownLink
                    }
                  >
                    Contact Support
                  </Link>

                  <Link
                    href="/dashboard/notifications"
                     onClick={closeAllDropdowns}
                    className={
                      styles.dropdownLink
                    }
                  >
                    Notifications
                  </Link>

                  <button
                    type="button"
                    onClick={
                      handleLogout
                    }
                    className={
                      styles.logoutBtn
                    }
                  >
                    <MdLogout />

                    Logout
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* MOBILE MENU */}

          <button
            type="button"
            className={`${styles.iconBtn} ${styles.hamburger}`}
            onClick={
              toggleMobileSidebar
            }
          >
            <HiMenuAlt3 size={22} />
          </button>
        </div>
      </nav>
    </>
  );
};

export default DashboardNavbar;