'use client'

import type * as React from 'react'
import type { LinkButtonProps } from './link-button'
import type { LinkMainProps } from './link-main'
import type { BaseUIEvent } from '@base-ui/react'
import { Popover, PopoverContent, PopoverTrigger } from '@admin/components/ui/popover'
import { LinkIcon } from 'lucide-react'
import { useCallback, useState } from 'react'
import { LinkButton } from './link-button'
import { LinkMain } from './link-main'

export interface LinkControlPopoverProps extends Omit<LinkButtonProps, 'type'>, LinkMainProps {
  canSet?: boolean
  isActive?: boolean
  label?: string
  onOpenChange?: (isOpen: boolean) => void
  open?: boolean
}

export function LinkControlPopover({
  canSet = true,
  children,
  isActive = false,
  label = 'Link',
  onClick,
  onOpenChange,
  open,
  ref,
  removeLink,
  setLink,
  setUrl,
  url,
  ...buttonProps
}: LinkControlPopoverProps) {
  const [uncontrolledOpen, setUncontrolledOpen] = useState(false)
  const isOpen = open ?? uncontrolledOpen
  const isDisabled = Boolean(buttonProps.disabled) || !canSet

  const handleOnOpenChange = useCallback(
    (nextIsOpen: boolean) => {
      if (open === undefined) {
        setUncontrolledOpen(nextIsOpen)
      }
      onOpenChange?.(nextIsOpen)
    },
    [onOpenChange, open]
  )

  const handleSetLink = useCallback(() => {
    setLink()
    handleOnOpenChange(false)
  }, [handleOnOpenChange, setLink])

  const handleClick = useCallback(
    (event: BaseUIEvent<React.MouseEvent<HTMLButtonElement>>) => {
      onClick?.(event)
      if (event.defaultPrevented) return
      handleOnOpenChange(!isOpen)
    },
    [handleOnOpenChange, isOpen, onClick]
  )

  return (
    <Popover open={isOpen} onOpenChange={handleOnOpenChange}>
      <PopoverTrigger
        render={
          <LinkButton
            {...buttonProps}
            disabled={isDisabled}
            data-active-state={isActive ? 'on' : 'off'}
            data-disabled={isDisabled}
            aria-label={label}
            aria-pressed={isActive}
            onClick={handleClick}
            ref={ref}
          />
        }
      >
        {children ?? <LinkIcon />}
      </PopoverTrigger>

      <PopoverContent className="w-auto max-w-[calc(100vw-2rem)]">
        <LinkMain url={url} setUrl={setUrl} setLink={handleSetLink} removeLink={removeLink} />
      </PopoverContent>
    </Popover>
  )
}
