import React, { useRef } from 'react'
import './update-btn.scss'
import { useUpdateBtnAnimation } from './update-btn.js'

function UpdateBtn({
  onClick,
  disabled = false,
  loading: externalLoading,
  title = 'Refresh',
  className = ''
}) {
  const btnRef = useRef(null)
  const { isLoading, handleClick } = useUpdateBtnAnimation(btnRef, externalLoading, onClick, disabled)
  
  const refreshIcon = (
    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M1 4V10H7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M23 20V14H17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10M23 14L18.36 18.36A9 9 0 0 1 3.51 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  )

  const loadingIcon = (
    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" opacity="0.2"/>
      <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeDasharray="47.124" strokeDashoffset="47.124"/>
    </svg>
  )

  const refreshIconDisabled = (
    <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" opacity="0.5">
      <path d="M1 4V10H7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M23 20V14H17" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
      <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10M23 14L18.36 18.36A9 9 0 0 1 3.51 15" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  )

  return (
    <div 
      ref={btnRef}
      className={`update-btn ${isLoading ? 'update-btn--loading' : ''} ${disabled || isLoading ? 'update-btn--disabled' : ''} ${className}`}
      onClick={handleClick}
      title={isLoading ? 'Loading...' : title}
      role="button"
      tabIndex={disabled || isLoading ? -1 : 0}
    >
      <div className="update-btn__icon">
        {disabled ? refreshIconDisabled : (isLoading ? loadingIcon : refreshIcon)}
      </div>
    </div>
  )
}

export default UpdateBtn
