import React, { useState, useEffect, useRef } from "react";
import { CgLogOut } from "react-icons/cg";
import { MdKeyboardArrowDown } from "react-icons/md";
import Image from "next/image";
import Link from "next/link";
import { signOut } from "next-auth/react";
import Cookies from "js-cookie";
import axios from "axios";
import { useSelector } from "react-redux";
import styles from "@/styles/common/small.module.css";
import { userActivity } from "@/components/commonFunctions/userActivity";
import { RootState } from "@/Redux/store";
import jwt from "jsonwebtoken";

export default function Navbar() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const toggleDropdown = () => {
    setIsOpen(!isOpen);
  };

  const handleClickOutside = (event: MouseEvent) => {
    if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
      setIsOpen(false);
    }
  };

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const token: any = Cookies.get("jazz_admin_token");

  const decodedToken = jwt.decode(token);

  const userId = decodedToken ? decodedToken.sub : null;

  const Log_out = (source: any, userAgent: any) => {
    userActivity(
      userId,
      "admin",
      "Log_out",
      {
        pageVisit: `/`,
      },
      navigator.userAgent
    );
  };

  const handleLogout = async () => {
    const authToken = Cookies.get("jazz_token");
    const adminauthToken = Cookies.get("jazz_admin_token");

    try {
      const axiosInstance = axios.create({
        baseURL: "https://api.jazzagain.com/public/index.php",
        headers: {
          Authorization: `Bearer ${authToken}`,
        },
      });

      // Make the API call to log the user out
      const response = await axiosInstance.get("/api/admin/logout");

      // Remove the token from the cookie
      Cookies.remove("jazz_token");
      Cookies.remove("jazz_admin_token");

      // Sign out using NextAuth
      await signOut({ callbackUrl: "/auth/login" });

      // Log user activity
      const userAgent = navigator.userAgent;
      Log_out("admin", userAgent);

      // Redirect to the login page
      window.location.href = "/admin/login";
    } catch (error) {
      console.error("Error logging out:", error);
    }
  };

  return (
    <div className="flex px-[3rem] items-center justify-between">
      <Link href="/" className="flex justify-center my-3">
        <Image
          src="/images/jazzagian-logo.png"
          width={100}
          height={100}
          alt="JazzAgain Logo"
          className="w-20"
        />
      </Link>

      <div>
        <div className="flex relative" onClick={toggleDropdown} ref={dropdownRef}>
          <div className="flex items-center text-right h-9 rounded-3xl border border-gray-600">
            <div className="w-1/2">
              <div className="w-full ps-[2px]">
                <div className="rounded-full h-[30px] w-[30px] flex justify-center items-center" style={{ backgroundColor: "#fde3cf" }}>
                  <svg viewBox="64 64 896 896" focusable="false" data-icon="user" width="1em" height="1em" fill="#f56a00" aria-hidden="true"><path d="M858.5 763.6a374 374 0 00-80.6-119.5 375.63 375.63 0 00-119.5-80.6c-.4-.2-.8-.3-1.2-.5C719.5 518 760 444.7 760 362c0-137-111-248-248-248S264 225 264 362c0 82.7 40.5 156 102.8 201.1-.4.2-.8.3-1.2.5-44.8 18.9-85 46-119.5 80.6a375.63 375.63 0 00-80.6 119.5A371.7 371.7 0 00136 901.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8 2-77.2 33-149.5 87.8-204.3 56.7-56.7 132-87.9 212.2-87.9s155.5 31.2 212.2 87.9C779 752.7 810 825 812 902.2c.1 4.4 3.6 7.8 8 7.8h60a8 8 0 008-8.2c-1-47.8-10.9-94.3-29.5-138.2zM512 534c-45.9 0-89.1-17.9-121.6-50.4S340 407.9 340 362c0-45.9 17.9-89.1 50.4-121.6S466.1 190 512 190s89.1 17.9 121.6 50.4S684 316.1 684 362c0 45.9-17.9 89.1-50.4 121.6S557.9 534 512 534z"></path></svg>
                </div>
              </div>
            </div>
            <MdKeyboardArrowDown className="ms-[2px]" size={25} />
          </div>
          {isOpen && (
            <div className="absolute w-64 right-0 top-[2rem] z-[9999]">
              <div className={`p-2 mt-2 text-left bg-white border border-zinc-300 rounded shadow-lg`}>
                <ul>
                  <li>
                    <button className="flex gap-2 items-center hover:bg-neutral-100 rounded w-full p-1" onClick={handleLogout}>
                      <CgLogOut size={20} className={`text-[#FF332B] ${styles.icon}`} />
                      <span>Logout</span>
                    </button>
                  </li>
                </ul>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}