"use client";
import React, { useEffect, useRef, useState } from "react";
import Link from "next/link";
import LanguageSwitcher from "./LanguageSwitcher";
import ProfileDropdown from "./ProfileDropdown";
import NotificationDropdown from "./NotificationDropdown";
import HeaderSearch from "./HeaderSearch";
import ProfileSideModal from "./ProfileSideModal";

import { usePathname, useRouter } from "next/navigation";
import { Home, Heart, Bell, MessageCircle, PlusCircle } from "lucide-react";
import { AiOutlineLogin } from "react-icons/ai";
import { TiContacts } from "react-icons/ti";
import DarkModeToggle from "../DarkModeToggle";
import Button from "../common/Button";
import { useAppSelector } from "@/app/store/hooks";
import { useTranslations } from "next-intl";
import { socket } from "@/app/(user)/chat/chatSocket";
import { IoIosArrowDown, IoIosArrowUp } from "react-icons/io";
import { RiFileList3Line } from "react-icons/ri";

export default function Header({ locale, className = "" }: any) {
  const [isOpen, setIsOpen] = useState(false);
  const t = useTranslations();
  const [isMobile, setIsMobile] = useState<boolean>(false);
  const dropdownRef = useRef(null);
  const { user } = useAppSelector((state) => state?.auth);
  const [open, setOpen] = useState(false);
  const toggleDropdown = () => setIsOpen((prev) => !prev);
  const pathname = usePathname();
  const router = useRouter();

  const [unreadCount, setUnreadCount] = useState(0);

  useEffect(() => {
    socket.auth = { token: user?.token };
    socket.connect();

    socket.on("connect", () => {
      // console.log("Connected to Socket", socket.id);
    });

    const handler = (data: any) => {
      const unreadCnt = data?.count?.totalUnreadConversations || 0;
      setUnreadCount(unreadCnt);
    };

    socket.on("chat_notification_count", handler);
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !(dropdownRef.current as any).contains(event.target)
      ) {
        setIsOpen(false);
      }
    };

    const handleCloseDropdown = () => {
      setIsOpen(false);
    };

    document.addEventListener("mousedown", handleClickOutside);
    window.addEventListener("closeProfileDropdown", handleCloseDropdown);

    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      window.removeEventListener("closeProfileDropdown", handleCloseDropdown);
      socket.off("chat_notification_count", handler);
    };
  }, []);
  const navItems = [
    {
      name: t("home"),
      icon: Home,
      href: "/",
      active: pathname === "/",
      badge: false,
    },
    {
      name: t("wishlist"),
      icon: Heart,
      href: "/wishlist",
      active: pathname === "/wishlist",
      badge: true,
    },
    {
      name: t("help"),
      icon: TiContacts,
      href: "/contact",
      active: pathname === "/contact",
      badge: false,
    },
    {
      name: t("login"),
      icon: AiOutlineLogin,
      href: "/login",
      active: pathname === "/login",
      badge: false,
    },
    {
      name: t("notifications"),
      icon: Bell,
      href: "/notifications",
      active: pathname === "/notifications",
      badge: true,
    },
    {
      name: t("chat1"),
      icon: MessageCircle,
      href: "/chat",
      active: pathname === "/chat",
      badge: true,
    },
  ];

  const notAllowedBottomHeader = [
    "/filters/products",
    "/services",
    "/jobs",
    "/community",
  ];


  return (
    <>
      <header
        className={`sticky px-6 py-3 md:py-2.5 shadow-headerShadow bg-white dark:bg-darkbg z-50 top-0 left-0 w-full transition-transform duration-300 border-b border-white dark:border-darkborder ${className}`}
      >
        <div className="max-w-w1660 mx-auto">
          <div className="flex items-center gap-6 justify-between rtl:gap-4">
            <div className="flex items-center gap-10 w-full 3xl:w-7/12">
              <Link
                href="/"
                aria-label="Home"
                className="text-2xl font-bold text-primary500 dark:text-white"
              >
                Kanzy
              </Link>
              <div className="hidden xl:flex w-full max-w-4xl">
                <HeaderSearch onClose={() => setOpen(false)} />
              </div>
            </div>
            <div className="flex items-center gap-3 3xl:w-5/12 justify-end max-lg:gap-2">
              <div className="flex xl:hidden" onClick={() => setOpen(true)}>
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    fillRule="evenodd"
                    clipRule="evenodd"
                    d="M5.85593 3.61739C7.1902 2.72585 8.75888 2.25 10.3636 2.25H10.3636C12.5154 2.25014 14.5791 3.105 16.1006 4.62655C17.6222 6.14811 18.4771 8.21174 18.4772 10.3635V10.3636C18.4772 11.9683 18.0013 13.537 17.1098 14.8713C16.2183 16.2055 14.9511 17.2455 13.4685 17.8596C11.986 18.4737 10.3546 18.6344 8.78071 18.3213C7.20683 18.0082 5.76113 17.2355 4.62642 16.1008C3.49171 14.9661 2.71897 13.5204 2.4059 11.9465C2.09284 10.3726 2.25352 8.74122 2.86761 7.25866C3.48171 5.77609 4.52165 4.50892 5.85593 3.61739ZM10.3635 3.75C9.05552 3.75001 7.77687 4.13789 6.68928 4.86459C5.60168 5.5913 4.754 6.6242 4.25343 7.83268C3.75287 9.04116 3.6219 10.3709 3.87708 11.6538C4.13227 12.9368 4.76215 14.1152 5.68708 15.0401C6.61201 15.965 7.79044 16.5949 9.07335 16.8501C10.3563 17.1053 11.686 16.9743 12.8945 16.4738C14.103 15.9732 15.1359 15.1255 15.8626 14.0379C16.5893 12.9503 16.9772 11.6717 16.9772 10.3636M10.3636 3.75C12.1176 3.75012 13.7997 4.44695 15.04 5.68721C16.2802 6.92748 16.9771 8.6096 16.9772 10.3636"
                    fill="#1E293B"
                    className="dark:fill-white"
                  />
                  <path
                    fillRule="evenodd"
                    clipRule="evenodd"
                    d="M15.3271 15.3251C15.62 15.0322 16.0949 15.0322 16.3878 15.3251L21.5304 20.4678C21.8233 20.7607 21.8233 21.2356 21.5304 21.5285C21.2375 21.8213 20.7626 21.8213 20.4697 21.5285L15.3271 16.3858C15.0342 16.0929 15.0342 15.618 15.3271 15.3251Z"
                    fill="#1E293B"
                    className="dark:fill-white"
                  />
                </svg>
              </div>
              {open && (
                <div className="fixed inset-0 z-50 bg-white flex flex-col dark:bg-card">
                  <div className="flex items-center justify-between px-6 py-4 shadow-headerShadow dark:bg-background">
                    <button
                      onClick={() => setOpen(false)}
                      className="rtl:rotate-180"
                      aria-label="close sidebar"
                    >
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          d="M18.7895 11.0066H7.61953L12.4995 6.12656C12.8895 5.73656 12.8895 5.09656 12.4995 4.70656C12.1095 4.31656 11.4795 4.31656 11.0895 4.70656L4.49953 11.2966C4.10953 11.6866 4.10953 12.3166 4.49953 12.7066L11.0895 19.2966C11.4795 19.6866 12.1095 19.6866 12.4995 19.2966C12.8895 18.9066 12.8895 18.2766 12.4995 17.8866L7.61953 13.0066H18.7895C19.3395 13.0066 19.7895 12.5566 19.7895 12.0066C19.7895 11.4566 19.3395 11.0066 18.7895 11.0066Z"
                          fill="#1E293B"
                          className="dark:fill-white"
                        />
                      </svg>
                    </button>
                    <div className="text-base text-neutrals800 font-semibold dark:text-white">
                      {t("header.search") || "Search"}
                    </div>
                    <div className="w-6"></div>
                  </div>
                   <div className="py-5 px-6 flex flex-col justify-between h-[calc(100vh-60px)]">
                    <HeaderSearch onClose={() => setOpen(false)} />
                  </div>
                </div>
              )}
              <LanguageSwitcher locale={locale} />
              <div
                className="flex md:hidden cursor-pointer"
                onClick={() => setIsMobile(true)}
              >
                <svg
                  width="24"
                  height="24"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M3 18H21V15.9998H3V18ZM3 12.9998H21V11.0002H3V12.9998ZM3 6V8.00016H21V6H3Z"
                    fill="#1E293B"
                    className="dark:fill-white"
                  />
                </svg>
              </div>
              <ProfileSideModal
                isMobile={isMobile}
                onClose={() => setIsMobile(false)}
              />
              <div className="hidden md:flex items-center gap-3 rtl:gap-2 max-lg:gap-2">
                <Link
                  className={`${pathname === "/wishlist" ? "active" : ""}`}
                  href="/wishlist"
                  aria-label="Wishlist"
                >
                  <svg
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                  >
                    <path
                      d="M16.5 3C14.76 3 13.09 3.81 12 5.09C10.91 3.81 9.24 3 7.5 3C4.42 3 2 5.42 2 8.5C2 12.28 5.4 15.36 10.55 20.04L12 21.35L13.45 20.03C18.6 15.36 22 12.28 22 8.5C22 5.42 19.58 3 16.5 3ZM12.1 18.55L12 18.65L11.9 18.55C7.14 14.24 4 11.39 4 8.5C4 6.5 5.5 5 7.5 5C9.04 5 10.54 5.99 11.07 7.36H12.94C13.46 5.99 14.96 5 16.5 5C18.5 5 20 6.5 20 8.5C20 11.39 16.86 14.24 12.1 18.55Z"
                      fill="#1E293B"
                      className="dark:fill-white"
                    />
                  </svg>
                </Link>
                {user ? (
                  <>
                    <NotificationDropdown />
                    <Link
                      href="/chat"
                      aria-label="Chat"
                      className={`relative ${pathname === "/chat" ? "active" : ""}`}
                    >
                      {unreadCount > 0 && (
                        <span
                          className="absolute -top-1.5 -right-1 bg-red-500 text-white text-[10px] font-semibold w-4 h-4 px-[6px] py-[2px] rounded-full shadow-sm leading-none min-w-[18px] flex items-center justify-center"
                          aria-label="unread count"
                        >
                          {unreadCount}
                        </span>
                      )}
                      <svg
                        width="24"
                        height="24"
                        viewBox="0 0 24 24"
                        fill="none"
                        xmlns="http://www.w3.org/2000/svg"
                      >
                        <path
                          fillRule="evenodd"
                          clipRule="evenodd"
                          d="M11.9921 3C6.99416 3 2.98499 6.95015 3.00004 11.7792L3.00005 11.7816C2.99999 13.4614 3.49098 15.1045 4.4124 16.5088C4.46503 16.5806 4.51426 16.655 4.55994 16.7315L4.56356 16.7375L4.56708 16.7437C4.64102 16.873 4.72871 17.0473 4.78914 17.2397C4.84444 17.4157 4.90814 17.7028 4.8249 18.0091L4.82403 18.0123L4.04982 20.8128L6.72863 19.846C6.99541 19.7363 7.28132 19.6803 7.56993 19.6814L7.56708 20.4313L7.56792 19.6814C7.56859 19.6814 7.56926 19.6814 7.56993 19.6814C7.83919 19.682 8.10608 19.7318 8.35742 19.8284L8.35851 19.8288C8.51054 19.8875 9.11616 20.1125 9.715 20.2801C10.3037 20.4449 11.3908 20.6447 12.1599 20.6447C17.1329 20.6447 20.9999 16.6518 21 11.7889C20.9998 11.1856 20.936 10.5838 20.8095 9.99391L20.8092 9.99234C19.9657 6.01596 16.3474 3 11.9921 3ZM1.50005 11.7827C1.48295 6.08891 6.19977 1.5 11.9921 1.5C17.0471 1.5 21.2839 5.00303 22.2764 9.68031C22.4248 10.3732 22.4998 11.0797 22.5 11.7883C22.5 17.4637 17.9774 22.1447 12.1599 22.1447C11.2133 22.1447 9.98483 21.9133 9.31072 21.7246C8.64793 21.5391 7.99375 21.2959 7.81907 21.2284C7.73838 21.1974 7.65268 21.1815 7.56624 21.1814L7.56423 21.1814C7.47098 21.181 7.37863 21.1996 7.29277 21.236L7.27407 21.2439L4.09313 22.3919C4.10134 22.3885 4.10952 22.3851 4.11768 22.3816L3.82083 21.6928L4.07543 22.3983L4.09313 22.3919C3.96107 22.446 3.82192 22.4811 3.67987 22.4959L3.63987 22.5001L3.59966 22.5C3.4409 22.4995 3.28382 22.4675 3.13751 22.4059C2.99121 22.3443 2.85858 22.2543 2.74731 22.141C2.63605 22.0278 2.54836 21.8936 2.48933 21.7462C2.4303 21.5989 2.40109 21.4412 2.40341 21.2825L2.40374 21.26L2.40542 21.2375C2.4131 21.1349 2.43136 21.0333 2.45991 20.9345L2.45857 20.9394L3.1814 21.1392L2.46194 20.9276C2.46126 20.9299 2.46058 20.9322 2.45991 20.9345L3.35756 17.6875C3.35773 17.6881 3.3579 17.6886 3.35806 17.6891C3.36431 17.709 3.36577 17.7185 3.36581 17.7185C3.36582 17.7185 3.36573 17.7178 3.3656 17.7164C3.36506 17.7107 3.36189 17.6729 3.37738 17.6159L4.10114 17.8125L3.37826 17.6127L3.37738 17.6159L3.35756 17.6875C3.34119 17.6361 3.30995 17.5678 3.26845 17.4945C3.26965 17.4964 3.27084 17.4984 3.27203 17.5004L3.91598 17.1159L3.26489 17.4882C3.26609 17.4903 3.26727 17.4924 3.26845 17.4945C3.24588 17.4571 3.22151 17.4208 3.19543 17.3858L3.18261 17.3686L3.17079 17.3507C2.08111 15.6981 1.50021 13.7622 1.50005 11.7827ZM1.50005 11.7827C1.50005 11.7831 1.50005 11.7835 1.50005 11.7839L2.25005 11.7816L1.50005 11.7815C1.50005 11.7819 1.50005 11.7823 1.50005 11.7827Z"
                          fill="#1E293B"
                          className="dark:fill-white"
                        />
                        <path
                          d="M7.56993 19.6814C7.28132 19.6803 6.99541 19.7363 6.72863 19.846L4.04982 20.8128L4.82403 18.0123L4.8249 18.0091C4.90814 17.7028 4.84444 17.4157 4.78914 17.2397C4.72871 17.0473 4.64102 16.873 4.56708 16.7437L4.56356 16.7375L4.55994 16.7315C4.51426 16.655 4.46503 16.5806 4.4124 16.5088C3.49098 15.1045 2.99999 13.4614 3.00005 11.7816L3.00004 11.7792C2.98499 6.95015 6.99416 3 11.9921 3C16.3474 3 19.9657 6.01596 20.8092 9.99234L20.8095 9.99391C20.936 10.5838 20.9998 11.1856 21 11.7889M7.56993 19.6814L7.56708 20.4313L7.56792 19.6814C7.56859 19.6814 7.56926 19.6814 7.56993 19.6814ZM7.56993 19.6814C7.83919 19.682 8.10608 19.7318 8.35742 19.8284L8.35851 19.8288C8.51054 19.8875 9.11616 20.1125 9.715 20.2801C10.3037 20.4449 11.3908 20.6447 12.1599 20.6447C17.1329 20.6447 20.9999 16.6518 21 11.7889M21 11.7889L21.75 11.7886M1.50005 11.7827C1.48295 6.08891 6.19977 1.5 11.9921 1.5C17.0471 1.5 21.2839 5.00303 22.2764 9.68031C22.4248 10.3732 22.4998 11.0797 22.5 11.7883C22.5 17.4637 17.9774 22.1447 12.1599 22.1447C11.2133 22.1447 9.98483 21.9133 9.31072 21.7246C8.64793 21.5391 7.99375 21.2959 7.81907 21.2284M1.50005 11.7827C1.50021 13.7622 2.08111 15.6981 3.17079 17.3507L3.18261 17.3686L3.19543 17.3858C3.22151 17.4208 3.24588 17.4571 3.26845 17.4945M1.50005 11.7827C1.50005 11.7831 1.50005 11.7835 1.50005 11.7839L2.25005 11.7816L1.50005 11.7815C1.50005 11.7819 1.50005 11.7823 1.50005 11.7827ZM7.81907 21.2284C7.81938 21.2286 7.81876 21.2283 7.81907 21.2284ZM7.81907 21.2284L8.08833 20.5284M7.81907 21.2284C7.73838 21.1974 7.65268 21.1815 7.56624 21.1814L7.56423 21.1814C7.47098 21.181 7.37863 21.1996 7.29277 21.236L7.27407 21.2439L4.09313 22.3919M4.09313 22.3919C4.10134 22.3885 4.10952 22.3851 4.11768 22.3816L3.82083 21.6928L4.07543 22.3983L4.09313 22.3919ZM4.09313 22.3919C3.96107 22.446 3.82192 22.4811 3.67987 22.4959L3.63987 22.5001L3.59966 22.5C3.4409 22.4995 3.28382 22.4675 3.13751 22.4059C2.99121 22.3443 2.85858 22.2543 2.74731 22.141C2.63605 22.0278 2.54836 21.8936 2.48933 21.7462C2.4303 21.5989 2.40109 21.4412 2.40341 21.2825L2.40374 21.26L2.40542 21.2375C2.4131 21.1349 2.43136 21.0333 2.45991 20.9345M2.45991 20.9345L2.45857 20.9394L3.1814 21.1392L2.46194 20.9276C2.46126 20.9299 2.46058 20.9322 2.45991 20.9345ZM2.45991 20.9345L3.35756 17.6875M3.35756 17.6875C3.35773 17.6881 3.3579 17.6886 3.35806 17.6891C3.36431 17.709 3.36577 17.7185 3.36581 17.7185C3.36582 17.7185 3.36573 17.7178 3.3656 17.7164C3.36506 17.7107 3.36189 17.6729 3.37738 17.6159M3.35756 17.6875L3.37738 17.6159M3.35756 17.6875C3.34119 17.6361 3.30995 17.5678 3.26845 17.4945M3.37738 17.6159L4.10114 17.8125L3.37826 17.6127L3.37738 17.6159ZM3.26845 17.4945C3.26965 17.4964 3.27084 17.4984 3.27203 17.5004L3.91598 17.1159L3.26489 17.4882C3.26609 17.4903 3.26727 17.4924 3.26845 17.4945Z"
                          stroke="#1E293B"
                          className="dark:stroke-white"
                          strokeWidth="0.2"
                          strokeMiterlimit="10"
                          strokeLinecap="round"
                        />
                      </svg>
                    </Link>
                  </>
                ) : null}
              </div>
              <div className="hidden lg:flex h-6 w-px bg-gray-300 dark:bg-darkborder" />
              <div className="hidden md:flex  items-center gap-4">
                {user ? (
                  <div className="relative" ref={dropdownRef}>
                    <div
                      onClick={toggleDropdown}
                      className="flex items-center gap-1 cursor-pointer"
                    >
                      <div className="w-9 h-9 rounded-full overflow-hidden cursor-pointer border-2 border-primary100 dark:border-darkborder max-lg:w-8 max-lg:h-8">
                        <img
                          src={`${process.env.NEXT_PUBLIC_API}/${user?.profile}`}
                          alt="Profile"
                          width={40}
                          height={40}
                          className="!w-9 h-9 rounded-full object-cover max-lg:!w-8 max-lg:!h-8"
                          onError={(e) => {
                            e.currentTarget.onerror = null;
                            e.currentTarget.src = "/profile-avatar.png";
                          }}
                        />
                      </div>
                      <p className="w-[calc(100%-40px)] flex items-center gap-1 font-semibold text-sm text-neutrals800 dark:text-white capitalize max-sm:hidden">
                        <span className="inline-block w-full truncate max-w-[70px] line-clamp-1">
                          {user?.username}
                        </span>
                        {isOpen ? (
                          <IoIosArrowUp
                            size={18}
                            className="transition-all duration-200 mt-1"
                          />
                        ) : (
                          <IoIosArrowDown
                            size={18}
                            className="transition-all duration-200 mt-1"
                          />
                        )}
                      </p>
                    </div>

                    {isOpen && (
                      <div className="absolute left-1/2 mt-2 min-w-64 bg-white border border-neutrals200 shadow-Shadow1 rounded-lg z-40 p-2 transform -translate-x-1/2 dark:bg-darkbg dark:border-darkborder">
                        <ProfileDropdown  />
                      </div>
                    )}
                  </div>
                ) : (
                  <>
                    <Link
                      href="/login"
                      className="text-md font-medium text-black  hover:text-primary800 text-nowrap dark:text-white"
                    >
                      {t("header.login") || "Login"}
                    </Link>
                  </>
                )}
                <Link
                  href="/listing/create"
                  className=" text-sm font-medium text-primary500 underline underline-offset-2 hover:text-primary800 text-nowrap dark:text-primary400"
                >
                  <span className="max-[800px]:hidden">
                    {t("header.post_a_list")}
                  </span>
                  <RiFileList3Line
                    size={24}
                    className="hidden max-[800px]:flex"
                  />
                </Link>
              </div>
              <Button
                label={t("request_a_product.title")}
                variant="outline"
                href="/request-a-product"
                className="hidden md:flex ms-1 leading-snug !px-2 text-sm"
              />
              <DarkModeToggle />
            </div>
          </div>
        </div>
      </header>

      {notAllowedBottomHeader.includes(pathname) ? null : (
        <div className="fixed bottom-0 left-0 w-full bg-white shadow-[0_-1px_10px_rgba(0,0,0,0.1)] z-40 pt-3 pb-2 block md:hidden border-t border-neutrals100 dark:bg-card dark:border-darkborder">
          <div className="relative flex items-center px-4">
            {/* Left icons */}
            {navItems.slice(0, 2).map((item) => (
              <NavIcon key={item.name} {...item} router={router} />
            ))}

            <div
              className="absolute -top-10 left-1/2 -translate-x-1/2 z-10"
              onClick={() => router.push("/listing/create")}
            >
              <div className="w-14 h-14 bg-primary500 rounded-full flex items-center justify-center shadow-navShadow dark:bg-primary400">
                <PlusCircle className="text-white w-8 h-8" />
              </div>
            </div>
            <div className="flex-grow" />

            {/* Right icons */}
            {!user &&
              navItems
                .slice(2, 4)
                .map((item) => (
                  <NavIcon key={item.name} {...item} router={router} />
                ))}

            {user &&
              navItems
                .slice(4)
                .map((item) => (
                  <NavIcon key={item.name} {...item} router={router} />
                ))}
          </div>
        </div>
      )}
    </>
  );
}

function NavIcon({ name, icon: Icon, active, badge, href, router }: any) {
  return (
    <div
      className="flex flex-col items-center text-center relative w-1/5"
      onClick={() => router.push(href)}
    >
      <div className="relative">
        <Icon
          className={`w-6 h-6 ${active ? "text-primary500 dark:text-primary400" : "text-neutrals500"
            }`}
        />
        {badge && (
          <span className="absolute -top-0 -right-[1px] w-3 h-3 border border-white bg-red-600 rounded-full text-white flex items-center justify-center text-[10px] dark:border-red-600" />
        )}
      </div>
      <span
        className={`text-[10px] font-medium mt-1 ${active ? "text-primary500 dark:text-primary400" : "text-neutrals500"
          }`}
      >
        {name}
      </span>
    </div>
  );
}
