import { Meteor } from 'meteor/meteor';
import React, {useState, useRef, useEffect, Suspense} from 'react';
import { useTracker, useFind } from 'meteor/react-meteor-data/suspense';

// import { FilesCol } from '/imports/api/files.js';
import { useNavigate, Link } from 'react-router-dom';

import { Roles } from 'meteor/roles';
// import { useUserContext } from '/imports/api/contexts/AppContext';
// import { groupBy } from 'lodash';

//import Radium from 'radium';
import { useLongTap } from '../hooks';


const IndicadorMissatges = ({notif}) => {
  return <span style={{
    position: `relative`
  }}>
    {notif && <span className='fas fa-solid fa-envelope' />}
    <span style={{
      borderRadius: `50%`,
      background: notif ? `red` : ``,
      position: `absolute`,
      width: `.4em`,
      aspectRatio: `1 / 1`
    }}/>
  </span>;
};

const useLongPress = (mostraMenu, setMostraMenu) => {
  const [isPressed, setIsPressed] = useState(false);
  const [startTime, setStartTime] = useState(0);
  const [hasLongPressed, setHasLongPressed] = useState(false);

  const targetRef = useRef(null);


  const onPointerDown = (e) => {
    if (!isPressed) {
      setIsPressed(true);
      setStartTime(Date.now());
    }
  };

  const onPointerUp = () => {
    if (isPressed) {
      setIsPressed(false);
      // Clear any pending timeout
      // clearTimeout(timeoutId?.current);
    }
  };

  const onPointerMove = () => {
    if (!isPressed) return;
    // Check pointer position changes and update state if needed
    // You can implement your own logic here to detect movement
  };

  useEffect(() => {
    let timeoutId = undefined;

    if (isPressed) {
      timeoutId = setTimeout(() => {
        const duration = Date.now() - startTime;
        if (duration >= 500 && isPressed) {
          setHasLongPressed(true);
          setMostraMenu(true);
          
        }
      }, 500);
      // return () => clearTimeout(timeoutId);
    }

    return () => clearTimeout(timeoutId);
  }, [isPressed]);

  useEffect(() => {
    const handleDocumentClick = (e) => {
      if (targetRef.current && !targetRef.current.contains(e.target)) {
        setHasLongPressed(false);
        setIsPressed(false);
        setMostraMenu(false);
      }
    };

    document.addEventListener('click', handleDocumentClick);
    document.addEventListener('touchstart', handleDocumentClick);
    document.addEventListener('pointerdown', handleDocumentClick);

    return () => {
      document.removeEventListener('click', handleDocumentClick);
      document.removeEventListener('touchstart', handleDocumentClick);
      document.removeEventListener('pointerdown', handleDocumentClick);
    };
  }, [targetRef]);

  return {
    hasLongPressed,
    setHasLongPressed,
    onPointerDown,
    onPointerUp,
    onPointerMove,
    targetRef
  };
};


const UserStat = ({esAdministrador, setEsAdministrador}) => {
  
  // const [esAdministrador, setEsAdministrador] = useState(false);
  
  const [mostraMenu, setMostraMenu] = useState(false);
  const { hasLongPressed, setHasLongPressed, onPointerDown, onPointerUp, onPointerMove, targetRef } = useLongPress(mostraMenu, setMostraMenu);

  const u = useTracker("user", async () => await Meteor.userAsync());
  const userId = Meteor.userId();


  // useEffect(() => {
  //   (async () => {
  //       const comprovaAdmin = await Roles.userIsInRoleAsync(userId, ["admin"]);
  //       setEsAdministrador(comprovaAdmin);
  //   })();
  // }, [Meteor.userId()]);

  // const u = useUserContext();


  // console.log("UUU: ", u);

  const navigate = useNavigate();
  // const files = useTracker(() => {
  //   const filesHandle = Meteor.subscribe('files.avatar');
  // // const docsReadyYet = filesHandle.ready();
  //   const files = FilesCol?.find({"meta.userId": Meteor.userId()}, {sort: {name: 1}}).fetch(); // Meteor.userId() ?? "nop"
  
  //   return files;
  // });

// const uname = useTracker(() => Meteor.user({ fields: { 'username': 1 } })?.username );
  

  //const avatarLink = u.avatarLink;

  // alert("avLnk: ", u.profile.avatarLink);


  // if (hasLongPressed) {
  //   setMostraMenu(true);
  // }
  
  return <Suspense fallback="Carregant...">

    
    <div
      style={{
        // color: `lightblue`,
        
        top: `1em`,
        // right: `1em`,
        left: `1em`,
        cursor: `pointer`,
        background: `yellow`,
        border: `lightblue 3px solid`,
        //padding: `.15em`,
        borderRadius: `.7em`,
        fontWeight: `bold`,
        display: `inline-block`
      }}
      // onMouseEnter={ev => {
      //   setMostraMenu(true);
      // }}

      onPointerDown={onPointerDown}
      onPointerUp={onPointerUp}
      onPointerMove={onPointerMove}
      
      ref={targetRef}
      
    
      // // title="Logout"

      // onClick={ev => {
      //   ev.stopPropagation();
      //   ev.preventDefault();

      //   // console.log("u: ", u);

      //   navigate(`/${u.username}`);

      // }}

      
      // onPointerCancel={onPointerCancel}
      // onPointerOut={onPointerOut}
    >
      {/* <span onClick={() => setHasLongPressed(!hasLongPressed)}>
      {hasLongPressed ? 'Yes!' : 'No'}
      </span> */}
      { (u && esAdministrador) && <div style={{
          color: `red`,
          fontSize: `xx-small`,
          // textAlign: `right`
      }}>ADMIN</div> }
      <img
        style={{
          width: `3em`,
          height: `3em`,
          borderRadius: `50%`,
          overflow: `hidden`,
          verticalAlign: `middle`,
          margin: `.3em`,
          border: `solid 4px whitesmoke`
        }}
        src={u?.profile?.avatarLink}
      />

      <span style={{
        verticalAlign: `middle`,
        margin: `0.3em 0.3em 0.3em auto`
      }}>{u?.username}</span>

      <span
        style={{
          verticalAlign: `middle`,
          margin: `0.3em 0.3em 0.3em auto`,
          padding: `.2em`,
          // border: `2px solid grey`,
          color: `grey`,
          // borderRadius: `.3em`
        }}
        onClick={ev => {
          ev.preventDefault();
          ev.stopPropagation();

          alert("Click en missatges");
        }}
      >
        <IndicadorMissatges notif={false} />
      </span>
    </div>
    {
      mostraMenu &&
      <div style={{
          position: `absolute`,
          background: `white`,
          // right: `0`,
          left: 0,
          top: `5em`,
          padding: `.4em .5em`,
          border: `1px solid #aaa`,
          cursor: `pointer`,
          zIndex: `200`
        }}
        onMouseLeave={ev => {
          setMostraMenu(false);
        }}
      >
        {/* <Link to="/c/config"> */}
          <div className="menuOp" style={{
              padding: `.2em`
            }}
            onClick={ev => {
              //setEditaPerfil(true);
              ev.stopPropagation();
              ev.preventDefault();
              
              navigate(`/c/config`);

            }}
          >Configuración</div>
        {/* </Link> */}
        
        <div className="menuOp" style={{
          padding: `.2em`
        }}
        onClick={() => {
          Meteor.logout(err => {
            err && alert(`Problema: ${err}`);
          });
          navigate(`/`);
        }}
        >Cierra la sesión</div>
      </div>
    }
    <br /><br />
  </Suspense>;
};

export { UserStat };