'use client'

import { useState, useCallback, useEffect } from 'react'
import { Button, ButtonProps } from '@/components/ui/button'
import { RefreshCw } from 'lucide-react'
import { cn } from '@/lib/utils'

interface RefreshButtonProps extends Omit<ButtonProps, 'onClick'> {
  onClick: () => void | Promise<unknown>
  isRefreshing?: boolean
  /** Minimum animation duration in ms (default: 500) */
  minAnimationDuration?: number
  /** Show text label (default: true) */
  showLabel?: boolean
  /** Custom label text (default: "Refresh") */
  label?: string
  /** Icon size class (default: "h-4 w-4") */
  iconSize?: string
}

export function RefreshButton({
  onClick,
  isRefreshing = false,
  minAnimationDuration = 500,
  showLabel = true,
  label = 'Refresh',
  iconSize = 'h-4 w-4',
  className,
  disabled,
  ...props
}: RefreshButtonProps) {
  const [isAnimating, setIsAnimating] = useState(false)
  const [animationStartTime, setAnimationStartTime] = useState<number | null>(null)

  // Start animation immediately on click
  const handleClick = useCallback(async () => {
    if (isAnimating || disabled) return

    setIsAnimating(true)
    setAnimationStartTime(Date.now())

    try {
      await onClick()
    } catch (error) {
      console.error('Refresh failed:', error)
    }
  }, [onClick, isAnimating, disabled])

  // Keep animation running for minimum duration or while still refreshing
  useEffect(() => {
    if (!isAnimating) return

    const checkShouldStop = () => {
      const elapsed = animationStartTime ? Date.now() - animationStartTime : 0
      const minDurationMet = elapsed >= minAnimationDuration

      // Stop animation only when minimum duration is met AND not actively refreshing
      if (minDurationMet && !isRefreshing) {
        setIsAnimating(false)
        setAnimationStartTime(null)
      }
    }

    // Check immediately
    checkShouldStop()

    // Also check on interval for ongoing refreshes
    const interval = setInterval(checkShouldStop, 100)
    return () => clearInterval(interval)
  }, [isAnimating, isRefreshing, animationStartTime, minAnimationDuration])

  const shouldAnimate = isAnimating || isRefreshing

  return (
    <Button
      variant="ghost"
      size="sm"
      onClick={handleClick}
      disabled={disabled || shouldAnimate}
      className={cn('gap-2', className)}
      {...props}
    >
      <RefreshCw
        className={cn(
          iconSize,
          'transition-transform duration-200',
          shouldAnimate && 'animate-spin'
        )}
      />
      {showLabel && label}
    </Button>
  )
}
