'use client'

import React, { type ComponentProps } from 'react'
import { SvgCheck, SvgCopy } from '@chainlink/blocks-icons'
import { cn } from '../../utils/cn'
import { ButtonIcon } from '../Button'
import {
  Popover,
  PopoverArrow,
  PopoverContent,
  PopoverTrigger,
} from '../Popover'
import {
  CopyRoot,
  CopyTrigger,
  useCopy,
  useCopyContext,
  type CopyRootProps,
  type CopyTriggerProps,
} from './CopyPrimitive'

// Re-export primitives
export { CopyRoot, CopyTrigger, useCopy, useCopyContext }
export type { CopyRootProps, CopyTriggerProps }

// ============================================================================
// CopyButton
// ============================================================================

export type CopyButtonProps = {
  /**
   * The text to copy. If provided, can be used standalone without CopyRoot.
   * If omitted, reads from CopyRoot context.
   */
  text?: string
} & Omit<ComponentProps<typeof ButtonIcon>, 'children'>

/**
 * A copy trigger styled as a ButtonIcon (xs size).
 * Can be used within a CopyRoot or standalone with the `text` prop.
 *
 * @example
 * ```tsx
 * // Standalone
 * <CopyButton text="Hello" />
 *
 * // Within CopyRoot
 * <CopyRoot text="Hello">
 *   <CopyButton />
 * </CopyRoot>
 * ```
 */
export const CopyButton = ({
  text,
  className,
  ...buttonIconProps
}: CopyButtonProps) => {
  const { isCopied, copy } = useCopy(text)
  const [popoverOpen, setPopoverOpen] = React.useState(false)

  return (
    <Popover open={isCopied || popoverOpen}>
      <PopoverTrigger className="outline-none ring-0" asChild>
        <ButtonIcon
          onClick={(e) => {
            e.stopPropagation()
            copy()
          }}
          onMouseEnter={() => setPopoverOpen(true)}
          onMouseLeave={() => setPopoverOpen(false)}
          className={cn('[&_svg]:size-3', className)}
          size="xs"
          {...buttonIconProps}
        >
          {isCopied ? <SvgCheck color="success" /> : <SvgCopy />}
        </ButtonIcon>
      </PopoverTrigger>
      <PopoverContent className="outline-none ring-0" side="top">
        {isCopied ? 'Copied!' : 'Copy'}
        <PopoverArrow />
      </PopoverContent>
    </Popover>
  )
}

// ============================================================================
// CopyIcon
// ============================================================================

export type CopyIconProps = {
  /**
   * The text to copy. If provided, can be used standalone without CopyRoot.
   * If omitted, reads from CopyRoot context.
   */
  text?: string
  /**
   * Additional class names for the icon button.
   */
  className?: string
}

/**
 * A minimal copy icon trigger.
 * Can be used within a CopyRoot or standalone with the `text` prop.
 *
 * @example
 * ```tsx
 * // Standalone
 * <CopyIcon text="Hello" />
 *
 * // Within CopyRoot
 * <CopyRoot text="Hello">
 *   <CopyIcon />
 * </CopyRoot>
 * ```
 */
export const CopyIcon = ({ text, className }: CopyIconProps) => {
  return <CopyTrigger text={text} className={className} />
}

// ============================================================================
// Copy (High-level component)
// ============================================================================

export interface CopyProps extends React.HTMLAttributes<HTMLDivElement> {
  /**
   * The text to be copied to the clipboard.
   */
  text: string
  /**
   * The visual variant of the copy trigger.
   * @default 'button'
   */
  variant?: 'button' | 'icon'
}

/**
 * High-level copy component that displays content with a copy button/icon.
 *
 * @example
 * ```tsx
 * <Copy text="0x123456789abcdef">
 *   0x1234...abcd
 * </Copy>
 * ```
 */
export const Copy = ({
  text,
  children,
  variant = 'button',
  className,
  ...props
}: CopyProps) => {
  return (
    <CopyRoot text={text} className={className} {...props}>
      {children}
      {variant === 'button' && <CopyButton />}
      {variant === 'icon' && <CopyIcon />}
    </CopyRoot>
  )
}
