import { InfoOutlined } from '@mui/icons-material';
import { Popper, Paper, Typography } from '@mui/material';
import { useState, useEffect } from 'react';
import InfoCard from '../info-card';

export type RequestInfo = {
  avatar: string;
  email: string;
  did: string;
};

export type RequestType = {
  requested_by: string;
};
type Props = {
  requestInfo?: RequestInfo;
  request?: RequestType;
};
export default function RequestInfoPopper({ requestInfo = undefined, request = undefined }: Props) {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);

  const handleClick = (e: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(anchorEl ? null : e.currentTarget);
  };

  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (anchorEl && !anchorEl.contains(e.target as Node) && !(e.target as Element).closest('.popper-content')) {
        setAnchorEl(null);
      }
    };

    const handleScroll = (e: Event) => {
      if (anchorEl && !(e.target as Element)?.closest('.popper-content')) {
        setAnchorEl(null);
      }
    };

    document.addEventListener('click', handleClickOutside);
    window.addEventListener('scroll', handleScroll, true);

    return () => {
      document.removeEventListener('click', handleClickOutside);
      window.removeEventListener('scroll', handleScroll, true);
    };
  }, [anchorEl]);

  return (
    <>
      <InfoOutlined
        fontSize="small"
        // @ts-ignore
        onClick={(e) => handleClick(e)}
        sx={{
          color: 'text.secondary',
          opacity: 0.6,
          cursor: 'pointer',
        }}
      />
      <Popper
        open={Boolean(anchorEl)}
        anchorEl={anchorEl}
        placement="right"
        sx={{
          zIndex: 1000,
          '@media (max-width: 600px)': {
            '& .MuiPaper-root': {
              width: 'calc(100vw - 32px)',
              maxWidth: 'none',
            },
          },
        }}
        modifiers={[
          {
            name: 'preventOverflow',
            options: {
              boundary: window,
              altAxis: true,
              padding: 16,
            },
          },
          {
            name: 'flip',
            options: {
              fallbackPlacements: ['bottom'],
            },
          },
          {
            name: 'matchWidth',
            enabled: true,
            fn: ({ state }) => {
              if (window.innerWidth <= 600) {
                state.styles.popper = {
                  ...state.styles.popper,
                  width: 'calc(100vw - 32px)',
                  maxWidth: 'none',
                };
              }
              return state;
            },
          },
        ]}>
        <Paper
          className="popper-content"
          elevation={3}
          sx={{
            p: 2,
            border: '1px solid',
            borderColor: 'divider',
            maxWidth: 360,
            '@media (max-width: 600px)': {
              maxWidth: 'none',
              margin: '0 auto',
            },
          }}>
          {requestInfo ? (
            <>
              <Typography
                variant="caption"
                sx={{
                  color: 'text.secondary',
                  mb: 1,
                  display: 'block',
                }}>
                Requested by:
              </Typography>
              <InfoCard
                logo={requestInfo.avatar}
                name={requestInfo.email}
                description={requestInfo.did || request?.requested_by}
                size={40}
              />
            </>
          ) : (
            <Typography>Requested by: {request?.requested_by || 'system'}</Typography>
          )}
        </Paper>
      </Popper>
    </>
  );
}
