import { PopoverField as PopoverFieldType, SchemaFieldProps } from '@vev/utils';
import React, { useRef, useState } from 'react';
import { SilkeBox } from '../../silke-box';
import { SilkeButton } from '../../silke-button';
import { SilkePopover } from '../../silke-popover';
import { SilkeText } from '../../silke-text';
import { SilkeSchemaFields } from '../silke-schema-fields';
import { SilkeSchemaContext, useSchemaContext } from '../silke-schema-context';
import { SilkeIcons } from '../../silke-icon';
import styles from './styles.scss';

/** Icon button that opens a popover with nested fields. Closes on outside click or Escape. */
export default function PopoverField({
  value = {},
  schema,
  disabled,
  readonly,
}: SchemaFieldProps<PopoverFieldType>) {
  const schemaContext = useSchemaContext();
  const [open, setOpen] = useState(false);
  const anchorRef = useRef<HTMLDivElement>(null);

  const icon = (schema.options?.icon || 'settings') as SilkeIcons;

  return (
    <SilkeBox ref={anchorRef}>
      <SilkeButton
        icon={icon}
        kind="ghost"
        size="s"
        disabled={disabled}
        onClick={() => setOpen((o) => !o)}
        title={schema.title}
      />
      {open && anchorRef.current && (
        <SilkePopover
          anchor={anchorRef}
          targetOrigin="top-right"
          zIndex={90}
          onRequestClose={() => setOpen(false)}
        >
          <SilkeSchemaContext context={schemaContext}>
            <SilkeBox column bg="neutral-5" className={styles.popoverFieldModal}>
              <SilkeBox pad="s" vAlign="center">
                <SilkeBox hPad="s" flex>
                  <SilkeText weight="strong">{schema.title || 'Settings'}</SilkeText>
                </SilkeBox>
                <SilkeButton icon="close" kind="ghost" onClick={() => setOpen(false)} />
              </SilkeBox>
              <SilkeBox hPad="m" gap="m" column>
                <SilkeSchemaFields
                  schema={schema.fields}
                  value={value}
                  disabled={disabled}
                  readonly={readonly}
                  noPad
                />
              </SilkeBox>
            </SilkeBox>
          </SilkeSchemaContext>
        </SilkePopover>
      )}
    </SilkeBox>
  );
}
