import React, { useState, useEffect } from 'react';
import './Header.css';
import moment from "moment";
import { getCookie } from 'react-use-cookie';
import { useHistory } from "react-router-dom";

import Header_MySy_Logo from '../../img_new_design_2025/header_mysy_logo.png';
import Header_User from '../../img_new_design_2025/header_user.png';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Button from '@mui/material/Button';
import { useCookies } from "react-cookie";


import CancelPresentationIcon from '@mui/icons-material/CancelPresentation';
import { makeStyles } from "@material-ui/core/styles";
import Paper from '@material-ui/core/Paper';
import Draggable from 'react-draggable';
import { IconButton } from '@material-ui/core';


function PaperComponent(props) {
  return (
    <Draggable
      handle="#draggable-dialog-title"
      cancel={'[class*="MuiDialogContent-root"]'}
    >
      <Paper {...props} />
    </Draggable>
  );
}

const useStyles = makeStyles((theme) => ({

  dialog: {
    position: 'absolute',
    // left: 10,
    top: 400
  },
 
  paper: {
    overflowY: 'unset',
  },
  customizedButton: {
    position: 'absolute',
    left: '98%',
    top: '-3%',
    backgroundColor: 'lightgray',
    color: 'gray',
  },
}));

const Header = () => {
  const history = useHistory();
  const classes = useStyles();
  const [userconnected, setuserconnected] = useState("0");
  const [someoneconnected, setsomeoneconnected] = useState("0");
  const [partnerconnected, setpartnerconnected] = useState("0");
  const stored_user = getCookie('tokenmysych');
  const stored_part = getCookie('tokenmysypart');
  const [cookie, setCookie, removeCookie] = useCookies(['tokenmysych'], { path: '/' });
  const [partcookie, setpartCookie, removepartCookie] = useCookies(['tokenmysypart'], { path: '/' });
  const [PartnerMenu, setPartnerMenu] = React.useState(null);
  const [AccountMenu, setAccountMenu] = React.useState(null);
  const [ProduitMenu, setproduitMenu] = React.useState(null);

  useEffect(() => {
    var local_user_connect = 0;
    var local_part_connect = 0;

    if (typeof (stored_user) === "undefined" || String(stored_user) === '') {
      setuserconnected("0");
      local_user_connect = 0;
    } else {
      setuserconnected("1");
      setsomeoneconnected("1");
      local_user_connect = 1;
      //alert(" user connected OK");
    }

    if (typeof (stored_part) === "undefined" || String(stored_part) === '') {
      setpartnerconnected("0");
      local_part_connect = 0;
    } else {
      setpartnerconnected("1");
      setsomeoneconnected("1");
      local_part_connect = 1;
      //alert(" partner connected OK");
    }

  }, []);

  const handleAccountCreation = () => {
    setAccountMenu(null);
    history.push("/signup/")
  };


  const handleMyAccount = () => {
    setAccountMenu(null);
    history.push("/mysy-user-account")
  };

  const handleAccountConnexion = () => {
    setAccountMenu(null);
    history.push("/signin/")
  };


  const handleMyPartnerAccount = () => {
    setAccountMenu(null);
    history.push("/Partner")
  };


  function handleAccountConnexion_v2() {

    if (String(userconnected) === String("1")) {
      handleMyAccount();
    }
    else if (String(partnerconnected) === String("1")) {
      handleMyPartnerAccount();
    }
  }

  const [Dialog_1_open, setDialog_1_open] = React.useState(false);
  const Dialog_1_handleClose = () => {
  };

  const Dialog_1_handleClose_buton = () => {
    setDialog_1_open(false);
  };

  function part_logout_confirmation() {
    /* si c'est une connexion partner qui est active */

    if (typeof (stored_part) != "undefined") {
      const stored_cookie = getCookie('tokenmysypart');
      var acces_right_token_name = stored_cookie + "_uar";

      setpartCookie("tokenmysypart", "", { path: '/' });
      setpartCookie(acces_right_token_name, "", { path: '/' });
      removeCookie(acces_right_token_name, { path: '/' });


      setpartCookie("mysy_session_display_view", "", { path: '/' });
      setpartCookie("mysy_menu_gauche_reduit", "", { path: '/' });
      setpartCookie("mysy_catalog_data_row_grouped_by", "", { path: '/' });

      removeCookie("tokenmysypart", { path: '/' });
      removeCookie("mysy_session_display_view", { path: '/' });
      removeCookie("mysy_menu_gauche_reduit", { path: '/' });
      removeCookie("mysy_catalog_data_row_grouped_by", { path: '/' });


    }
    setsomeoneconnected("0");
    setDialog_1_open(false);
    history.push("/recherche-formation");
  }

  function user_logout_confirmation() {
    /* si c'est une connexion partner qui est active */
    if (typeof (stored_user) != "undefined") {
      const stored_cookie = getCookie('tokenmysych');
      var acces_right_token_name = stored_cookie + "_uar";

      setpartCookie("tokenmysych", "", { path: '/' });
      setpartCookie(acces_right_token_name, "", { path: '/' });
      removeCookie(acces_right_token_name, { path: '/' });

      removeCookie("tokenmysych", { path: '/' });


    }
    history.push("/intranet");
  }

  return (
    <div className='header_automatic_files'>

      {/***   GESTION Deconnexion */}
      <Dialog
        open={Dialog_1_open}
        // onClose={Dialog_1_handleClose}
        className="displaypartnersession"
        static
        onClose={() => null}

        PaperProps={{


          className: classes.paper, // Apply the paper style
          style: {
            overflowY: 'unset',
            position: 'absolute',
            top: '7rem',
            margin: "2px",
          },
        }}
        hideBackdrop={true}
        disableScrollLock
        classes={{
          paper: classes.dialog
        }}

        PaperComponent={PaperComponent}
        aria-labelledby="draggable-dialog-title"
      >

        <DialogTitle style={{ cursor: 'move', fontFamily:"DM Sans"}} id="draggable-dialog-title" >MySy Information</DialogTitle>
        <DialogContent className="DialogContent_width">
          <DialogContentText>
            Confirmez la deconnexion  <br />


          </DialogContentText>

        </DialogContent>

        <DialogActions>

          <IconButton
            //autoFocus
            onClick={Dialog_1_handleClose_buton}
            color="primary"
            className={classes.customizedButton}
          >
            <CancelPresentationIcon />
          </IconButton>

          <div className="div_row">
            <div className="div_row_gauche">
              <Button

                onClick={(e) => {
                  if (partnerconnected && String(partnerconnected) === '1')
                    part_logout_confirmation();

                  if (userconnected && String(userconnected) === '1')
                    user_logout_confirmation();

                }}

                className="bton_enreg_dialog">Deconnexion</Button>
            </div>
            <div className="div_row_droite" style={{ "textAlign": 'center' }}>
              <Button onClick={Dialog_1_handleClose_buton} className="bton_annule_dialog" >Annuler</Button>
            </div>
          </div>

        </DialogActions>
      </Dialog>

      {/***  Fin GESTION Deconnexion */}

      <header className="header_new_2025">
        <div className="header-content">
          <div className="logo-menu">
            <img src={Header_MySy_Logo} alt="Logo MySy" className="logo" style={{ cursor: 'pointer' }} onClick={(e) => {
              // e.preventDefault();
              history.push("/");
            }} />

            <nav className="menu-list">
              <a href="/apropos" className="menu-link">À propos</a>
              <a href="/fonctionnalites" className="menu-link">Fonctionnalités</a>
              <a href="#" className="menu-link">
                <nav onClick={(e) => {
                  history.push("/tarif/#debut");
                  // window.open("/tarif/#debut", "_self");
                }}>Tarifs </nav>
              </a>
              <a href="/Recherche-Article-formation" className="menu-link">Blog</a>
              <div className="separator"></div>
              <a href="/marketplace" className="menu-link">Marketplace</a>
            </nav>
          </div>

          <div className="cta-login">
            <div className="cta-buttons">
              <button className="btn btn-primary" onClick={(e) => {
                e.preventDefault();
                var date2 = new Date();
                const format2 = "YYYY-MM";
                var dateTime2 = moment(date2).format(format2);
                window.open(
                  "https://calendly.com/mysytraining/demo-mysy-training-solution?month=" + String(dateTime2),
                  '_blank'
                );
              }}>Réserver une démo</button>

            </div>
            <div className="cta-buttons hide_on_mobile">
              {String(someoneconnected) !== String("1") && <button className="btn btn-secondary" onClick={handleAccountCreation}>Créer un compte</button>}

              {String(someoneconnected) === String("1") && <button className="btn btn-secondary" onClick={handleAccountConnexion_v2}>Mon compte</button>}

            </div>
            <div className="separator hide_on_mobile"></div>
            {String(someoneconnected) !== String("1") && <div className="login-link hide_on_mobile" onClick={handleAccountConnexion}>
              <img src={Header_User} alt="User icon" className="user-icon hide_on_mobile" />
              <span className='hide_on_mobile'>Connexion</span>
            </div>}

            {String(someoneconnected) === String("1") && <div className="login-link hide_on_mobile" onClick={(e) => setDialog_1_open(true)}>
              <img src={Header_User} alt="User icon" className="user-icon hide_on_mobile" />
              <span className='hide_on_mobile'>Deconnexion</span>
            </div>}

          </div>
        </div >
      </header >
    </div >
  );
};

export default Header;

