"use client"

import { useEffect, useState } from 'react'
import { Button } from '@/components/Button/Button'
import styles from "./styles.module.scss"

type PopupButtonProps = {
  text: React.ReactNode,
  title: string,
  links: Link[],
  size?: 'lg' | 'md'
  schema?: 'base' | 'shade' | 'contrast'
}

export type Link = {
  id: string,
  text: string,
  href: string
}

export const PopupButton = ({size = "md", schema, text, links, title}: PopupButtonProps) => {

  const [isPopupOpen, setIsPopupOpen] = useState(false)

  useEffect(() => {
    if (!isPopupOpen) return

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setIsPopupOpen(false)
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [isPopupOpen])

  return (
    <div className={styles.container}>

      <Button size={size} schema={schema} onClick={() => setIsPopupOpen(true)}>
        {text}
      </Button>

      {isPopupOpen && (
        <div className={styles.popup}>
          <button
            type="button"
            aria-label="Close"
            className={styles.closeButton}
            onClick={() => setIsPopupOpen(false)}
          >
            ×
          </button>
          <div className={styles.popupTitle}>{title}</div>
          {links.map(link => (
            <div key={link.id}>
              <a
                href={link.href}
                onClick={() => setIsPopupOpen(false)}
                 className={styles.link}
                 target={"_blank"}>
                {link.text}</a>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}