/**
 *
 * Global header component
 */

import React, { useState, useEffect, useContext,useRef } from "react";

import { animationControls, motion, useAnimation } from "framer-motion";

import {
  boxVariants,
} from "./animations"

import { GlobalContext } from "./../../Store";

import { Link, useLocation } from "react-router-dom";

import { Typography, Avatar ,Input} from "antd";



import ProgressBar from "../progress-bar/progress-bar"; // Adjust the path as needed

import { Button } from "../../elements";



import GenericHeader from "../header/generic-header";

import {
  MenuOutlined,
  UserOutlined,
  SettingOutlined,
} from "@ant-design/icons";

import { Drawer } from "antd";

import { ReloadOutlined, SearchOutlined } from "@ant-design/icons";

import SideMenu from "./../sidemenu/sidemenu";

import "./global-header.scss";

import LanguageSwitcher from "../language-switcher/language-switcher";

import { useTranslation } from "react-i18next";


import BorderStyle from "pdf-lib/cjs/core/annotation/BorderStyle";

import SettingsUtil from "../../../utils/settings.utils";
import { SpotlightSearch } from "..";



const { Title } = Typography;




export default function GlobalHeader({
  loading,
  appSettings,
  children,
  isConnected,
  history,
  modules = [],
  sidemenu = [],
  reload,
  meta = {},
  ...props
}) {

  let location = useLocation();
  // let location = {};



  const { isMobile, user = { locations: [] }, kiosk, state } = useContext(GlobalContext);



  const [visible, setVisible] = useState(false);

  // Variable to handle toggling of menu
  const [collapsed, setCollapsed] = useState(false);
  // varibale handle branch switcher

 

  // const [searchModalVisible, setSearchModalVisible] = useState(false);


  const { globalCustomerHeader = () => { } } = appSettings;

  const { t, i18n } = useTranslation();

  const spotlightRef = useRef();

  useEffect(() => {

    setTimeout(() => {

      i18n.changeLanguage(localStorage.selectedLanguage);

    }, 0)


  }, []);
 
  


  /**
   * Function to handle toggling of menu
   */

  const toggleCollapsed = () => {
    setVisible(true);

    collapsed === true ? setCollapsed(false) : setCollapsed(true);
  };

  const openSearchModal = () => {
    //  input to avoid typing
    SettingsUtil.openSpotlightModal();
  };
  
 
  

  /**
   * Function to remove toggling on mobile view
   */
  const hideToggle = () => {
    setVisible(true);

    setCollapsed(false);
  };

  /**
   * onClose Function
   */

  const onClose = () => {
    setVisible(false);
  };

  // const { model = {} } = menu;

  const { model: BaseModel = {}, menu = {} } = meta;

  const { model = {} } = menu;

  //Animations//
  const boxControls = useAnimation();

  async function animate() {
    await boxControls.start("entered");

    //await boxControls.start("show");
  }

  useEffect(() => {

    animate();
  }, [])

  useEffect(() => {

  }, [state.theme]);

 
  
  
  


  return (
    <div
      className={`global-header ${process.env.REACT_APP_THEME}  ${isConnected && !kiosk ? "connected" : ""
        }`}
      style={{

        // background: state.theme.colors.bodyBackground,

        height: 10,

      }}
    >
      {/* <MenuOutlined style={{left:'1%',top:'1%', fontSize:18, position:'absolute', zIndex:999}} onClick={showSidebar}/> */}

      <div className="layout-content">
        <div

          //whileHover="hover"
          //whileTap="tap"
          className={`left-bar ${!isConnected && !isMobile ? "" : "hide"}${!collapsed ? "open" : "close"}${kiosk && !isConnected ? "kioskon" : ""}`}
          style={{ background: state.theme.colors.leftSectionBackground }}
        >

          {!isMobile && !isConnected ? (
            <motion.div
              variants={boxVariants}
              initial={["entering"]}
              animate={boxControls}
              className={`sidebar-container ${!collapsed ? "open" : "close"}${kiosk ? "" : "kioskon"}`}

            >

              <SideMenu
                // isOpen={isOpen}
                collapsed={collapsed}
                setCollapsed={setCollapsed}
                loading={loading}
                appSettings={appSettings}
                callback={onClose}
                modules={modules}
                history={history}
              />

            </motion.div>
          ) : (
            <Drawer
              placement="left"
              onClose={onClose}
              visible={visible}
              className="side-drawer-content"
            >
              <div
                className={`sidebar-container ${!collapsed ? "open" : "close"}`}
              >
                <SideMenu
                  // isOpen={isOpen}
                  collapsed={collapsed}
                  setCollapsed={setCollapsed}
                  loading={loading}
                  appSettings={appSettings}
                  callback={onClose}
                  modules={modules}
                  history={history}
                />
              </div>
            </Drawer>
          )}
        </div>

        {/* Right Section of the Component Loader */}
        <div className={`right-section ${!collapsed ? "open" : "close"} ${kiosk ? "kioskon" : ""}`} style={{ background: state.theme.colors.bodyBackground }}>
          {/* For not connected section */}
          {!isConnected && !kiosk ? (

            <div className={`page-wrapper ${!collapsed ? "open" : "close"}`}
            // style={{ background: state.theme.colors.headerBg }}
            >
              {/*  */}
              <div className="page-header-name">

                <ProgressBar isLoading={loading} />

                <span type
                  onClick={!isMobile ? toggleCollapsed : hideToggle}
                  className="toggle-box toggle-menu"
                >
                  <MenuOutlined />

                </span>

                {/* Back Button */}
                {location.pathname !== "/" ? (
                  <span
                    className="toggle-box"
                    onClick={() => {
                      history && history.goBack();
                    }}
                  >
                    <GenericHeader />
                  </span>
                ) : null}
                {/* Back Button Ends */}


                {location.pathname !== "/" ? (
                  <h4 className="menu-caption header-caption" style={{ color: state.theme.colors.headerColor }}>
                    {menu.caption}
                  </h4>
                ) : null}
              </div>

              {/* Page Menu Actions */}
              
              {user.role || user.id ? (
                <div className="page-menu">
                               {/* Search Input in header start */}
                    <div>
                    <Input
                            placeholder="Search (Shift + F)"
                            prefix={<SearchOutlined />}
                            onClick={openSearchModal}
                          
                            readOnly
                            style={{ width: 250 }}
                          />
                    

                      <SpotlightSearch ref={(elem) => SettingsUtil.registerModal(elem)}  props={props}/>
                    
                    </div>
                    {/* Search Input in header start */}

                  {/** branchswitcher Option  */}
                  <div className="branch-switcher">{globalCustomerHeader()}</div>


                  {/* Search Option */}

                  {/* <ModalSearch /> */}

                  {/* Search Option Ends */}

                  {/* Configurator Actions */}
                  {user.isAdmin ? (
                    <>
                      {/* Models */}
                      {menu && menu.id ? (
                        <Link to={`/menus/${menu.id}`}>

                          <Button type="default" size={"small"} icon={<SettingOutlined />}>

                          </Button>
                        </Link>
                      ) : null}
                      {/* Models Ends */}
                    </>
                  ) : null}
                  {/* Configurator Actions Ends */}

                 




                  {/* Reload Button */}

                  <Button onClick={reload} icon={<ReloadOutlined />} type="default" size={"small"} >

                  </Button>

                  {/* Reload Button Ends */}

                  {/** Switch Languages starts */}
                  {process.env.REACT_APP_ENABLE_LANGUAGE_SWITCHER ? <LanguageSwitcher /> : null}
                  {/** Switch Languages ends */}

                  {/* User Profile */}
                  <div style={{ padding: "10px" }}>
                    <ProfileAvatar />
                    <span style={{ color: state.theme.colors.colorText }}> {user.name} </span>
                  </div>
                  {/* User Profile Ends */}
                </div>
              ) : null}

              {/* Page Menu Actions Ends */}
            </div>
          ) : null}

          {/* The children is rendered */}
          {children}
          {/* The children is rendered */}
        </div>
        {/* Right Section of the Component Loader Ends */}
      </div>
    </div>
  );
}


/**
 * 
 * @returns 
 */
function ProfileAvatar() {

  const { user = { locations: [] } } = useContext(GlobalContext);

  useEffect(() => { }, []);

  return (
    <Link className="profile-avatar" to="/profile">
      {user.photograph ? (
        <>
          <img
            className="profile-picture"
            src={user.photograph}
            alt={"user photograph"}
          />
        </>
      ) : (
        <Avatar shape="square" size="small" icon={<UserOutlined />} />
      )}

      {/* {user.name} */}
    </Link>
  );
}