import React, { useEffect, useRef, useState } from "react";
import IMAGES from "@/constants/images";
import Style from "./Header.module.css";
import Link from "next/link";
import { useSession } from "next-auth/react";
import Image from "next/image";
import {
  useGetDbTargetQuery,
  useSetDbTargetMutation,
} from "@/utils/Redux-Toolkit/services/DbTarget";
import { getDbLabel } from "@/utils/dbTargetLabels";
import dbStyles from "@/styles/modules/databaseTarget.module.css";
import ConfirmationPopup from "@/components/confirmationPopup/confirmationPopup";
import toast from "react-hot-toast";

const Header = () => {
  // Session
  const session = useSession();
  const adminDetail = session?.data?.user;
  const token = adminDetail?.token;
  const { data: dbTarget } = useGetDbTargetQuery(
    { token },
    { skip: !token, pollingInterval: 30000 }
  );
  const [setDbTarget, { isLoading: isSwitching }] = useSetDbTargetMutation();
  const activeDb = dbTarget?.data?.activeDb;
  const availableDbs = dbTarget?.data?.availableDbs || [];

  // State
  const [activeClass, setActiveClass] = useState(false);
  const [dbMenuOpen, setDbMenuOpen] = useState(false);
  const [pendingTarget, setPendingTarget] = useState<string | null>(null);

  // ref
  const modalRef = useRef<HTMLDivElement | null>(null);
  const notificationIcon = useRef<HTMLDivElement | null>(null);
  const dbMenuRef = useRef<HTMLDivElement | null>(null);

  // Hanfle modal open and close
  function handleClickOutside(event: MouseEvent) {
    if (
      modalRef.current &&
      notificationIcon.current &&
      !notificationIcon.current.contains(event.target as Node) &&
      !modalRef.current.contains(event.target as Node)
    ) {
      setActiveClass(false);
    }
  }

  // use effects
  useEffect(() => {
    if (activeClass) {
      document.addEventListener("mousedown", handleClickOutside);
    }

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

  useEffect(() => {
    if (!dbMenuOpen) return;

    function handleDbMenuOutside(event: MouseEvent) {
      if (
        dbMenuRef.current &&
        !dbMenuRef.current.contains(event.target as Node)
      ) {
        setDbMenuOpen(false);
      }
    }

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

  const confirmSwitch = async () => {
    if (!pendingTarget) return;
    try {
      const response = await setDbTarget({
        token,
        target: pendingTarget,
      }).unwrap();
      if (!response.status) {
        toast.error(response.message || "Failed to switch database.");
        setPendingTarget(null);
        return;
      }
      toast.success(`Switched to ${getDbLabel(response.data?.activeDb)}`);
      setPendingTarget(null);
      window.location.reload();
    } catch (err: unknown) {
      const message =
        err && typeof err === "object" && "data" in err
          ? (err as { data?: { message?: string } }).data?.message
          : undefined;
      toast.error(message || "Failed to persist database target.");
      setPendingTarget(null);
    }
  };

  return (
    <>
    <div className={Style.headerContainer}>
      <h1 className={Style.h1Style}>
        Welcome {adminDetail?.firstname ?? ""}{" "}
        {adminDetail?.lastname ?? "Admin"}!
      </h1>
      <div className={Style.rightSideHeaderContent}>
        {/* notification icon */}
        {/* <div className={Style.notificationIcon}>
          <div
            className={Style.notificationButtonAndHeading}
            onClick={() => {
              setActiveClass((prev) => !prev);
            }}
            ref={notificationIcon}
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
              <path d="M224 0c-17.7 0-32 14.3-32 32l0 19.2C119 66 64 130.6 64 208l0 18.8c0 47-17.3 92.4-48.5 127.6l-7.4 8.3c-8.4 9.4-10.4 22.9-5.3 34.4S19.4 416 32 416l384 0c12.6 0 24-7.4 29.2-18.9s3.1-25-5.3-34.4l-7.4-8.3C401.3 319.2 384 273.9 384 226.8l0-18.8c0-77.4-55-142-128-156.8L256 32c0-17.7-14.3-32-32-32zm45.3 493.3c12-12 18.7-28.3 18.7-45.3l-64 0-64 0c0 17 6.7 33.3 18.7 45.3s28.3 18.7 45.3 18.7s33.3-6.7 45.3-18.7z" />
            </svg>
            <p className={Style.notificationTitle}>Notification</p>
          </div>

          <div
            className={`${Style.notificationMainContainer} ${
              activeClass ? "" : Style.hide
            }`}
            ref={modalRef}
          >
            <div className={Style.notificationIndicator}></div>
            <div className={Style.notificationShortBox}>
              <div className={Style.notificationContainer}>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
                <div className={Style.NotificationCard}>
                  <div className={Style.leftSide}>
                    <div className={Style.notification_dot}></div>
                    <img
                      src="https://wait4me-api.thesuitchstaging2.com/src/services/uploads/images/10pearls_logo-1725366742020.jpg"
                      alt=""
                    />
                  </div>
                  <div className={Style.rightSideNotification}>
                    <div className={Style.groupOfHeadingAndPara}>
                      <h1>
                        {"Your assignment has been marked as completed."
                          .length > 54
                          ? `${"Your assignment has been marked as completed.".slice(
                              0,
                              54
                            )}...`
                          : "Your assignment has been marked as completed."}
                      </h1>
                      <p>
                        {"Your assignment 66c31a652359d890d46b4710 has been marked as completed."
                          .length > 44
                          ? `${"Your assignment 66c31a652359d890d46b4710 has been marked as completed.".slice(
                              0,
                              44
                            )}...`
                          : "Your assignment 66c31a652359d890d46b4710 has been marked as completed."}
                      </p>
                    </div>

                    <p className={Style.createdAt}>21/08/2024, 18:06:55</p>
                  </div>
                </div>
              </div>
              <Link
                href="/admin/notificationSettings"
                className={Style.viewAllNotifications}
              >
                VIEW ALL
              </Link>
            </div>
          </div>
        </div> */}

        {activeDb ? (
          <div className={dbStyles.headerDropdown} ref={dbMenuRef}>
            <button
              type="button"
              className={dbStyles.headerBadge}
              aria-haspopup="listbox"
              aria-expanded={dbMenuOpen}
              onClick={() => setDbMenuOpen((open) => !open)}
            >
              <span className={dbStyles.headerBadgeLabel}>DB</span>
              {getDbLabel(activeDb)}
              <svg
                className={`${dbStyles.headerChevron} ${
                  dbMenuOpen ? dbStyles.headerChevronOpen : ""
                }`}
                viewBox="0 0 12 8"
                width="12"
                height="8"
                aria-hidden="true"
              >
                <path
                  d="M1 1.5L6 6.5L11 1.5"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="1.6"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            </button>
            {dbMenuOpen ? (
              <div className={dbStyles.headerMenu} role="listbox">
                <p className={dbStyles.headerMenuHint}>
                  Switch the backend database. Users and assignments in the
                  other database will not appear until you switch back.
                </p>
                {availableDbs.length ? (
                  availableDbs.map((name) => {
                    const isActive = name === activeDb;
                    return (
                      <button
                        key={name}
                        type="button"
                        role="option"
                        aria-selected={isActive}
                        className={`${dbStyles.headerMenuItem} ${
                          isActive ? dbStyles.headerMenuItemActive : ""
                        }`}
                        disabled={isActive || isSwitching}
                        onClick={() => {
                          setDbMenuOpen(false);
                          setPendingTarget(name);
                        }}
                      >
                        <span className={dbStyles.headerMenuCopy}>
                          <span className={dbStyles.headerMenuTitle}>
                            {getDbLabel(name)}
                          </span>
                          <span className={dbStyles.headerMenuKey}>{name}</span>
                        </span>
                        {isActive ? (
                          <span className={dbStyles.headerMenuActive}>
                            Active
                          </span>
                        ) : null}
                      </button>
                    );
                  })
                ) : (
                  <p className={dbStyles.headerMenuEmpty}>
                    No other databases available.
                  </p>
                )}
              </div>
            ) : null}
          </div>
        ) : null}

        <Link href={"/admin/profile"} className={Style.rightSide}>
          <Image
            src={
              adminDetail?.image?.startsWith("https://")
                ? `${adminDetail?.image}`
                : IMAGES.profileImage
            }
            alt=""
            width={100}
            height={100}
            className={Style.imgSize}
          />
          <h1>
            {adminDetail?.firstname ?? ""} {adminDetail?.lastname ?? "Admin"}
          </h1>
        </Link>
      </div>
    </div>
      {pendingTarget ? (
        <ConfirmationPopup
          heading="Switch database?"
          title={`This will immediately point the whole backend at ${getDbLabel(
            pendingTarget
          )} (${pendingTarget}). Continue?`}
          acceptLabel="Switch"
          rejectLabel="Cancel"
          isLoaderShow={isSwitching}
          acceptedFunction={confirmSwitch}
          rejectedFunction={() => setPendingTarget(null)}
        />
      ) : null}
    </>
  );
};

export default Header;
