// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import type { JSXElement } from "@coreai-ds/react-components";
import * as React from 'react';
import { useId } from "@coreai-ds/react-components";
import type { PositioningImperativeRef } from "@coreai-ds/react-components";
import { makeStyles } from "@coreai-ds/react-components";
import { useRestoreFocusTarget } from "@coreai-ds/react-components";
import { Button } from "@coreai-ds/react-components";
import { Popover } from "@coreai-ds/react-components";
import { PopoverSurface } from "@coreai-ds/react-components";

const useStyles = makeStyles({
    container: {
        display: 'flex',
        gap: '10px',
    },
    contentHeader: {
        marginTop: '0',
    },
});

export const WithoutTrigger = (): JSXElement => {
    const [open, setOpen] = React.useState(false);
    const headerId = useId();
    const buttonRef = React.useRef<HTMLButtonElement>(null);
    const positioningRef = React.useRef<PositioningImperativeRef>(null);
    const styles = useStyles();
    const restoreFocusTargetAttribute = useRestoreFocusTarget();
    React.useEffect(() => {
        if (buttonRef.current) {
            positioningRef.current?.setTarget(buttonRef.current);
        }
    }, [buttonRef, positioningRef]);
    return (<div className={styles.container}>
      <Button {...restoreFocusTargetAttribute} ref={buttonRef} onClick={() => setOpen(s => !s)}>
        Toggle popover
      </Button>
      <Popover onOpenChange={(e, data) => {
            if (e.target === buttonRef.current) {
                // Ignore events that are triggered by the button to avoid re-opening the popover
                return;
            }
            setOpen(data.open);
        }} trapFocus open={open} positioning={{ positioningRef }}>
        <PopoverSurface aria-labelledby={headerId}>
          <div>
            <h3 id={headerId} className={styles.contentHeader}>
              Popover content
            </h3>

            <div>This is some popover content</div>
          </div>

          <div>
            <Button>Action</Button>
            <Button>Action</Button>
          </div>
        </PopoverSurface>
      </Popover>
    </div>);
};

export default WithoutTrigger;
