import React, { useEffect, useRef, useState } from 'react'

import { Button, ButtonProps, Progress } from 'antd'

interface AutoRefreshButtonProps {
  autoRefreshSec?: number
  loading: boolean
  onRefresh: () => void
  onClick?: () => void
}

export const AutoRefreshButton: React.FC<
  AutoRefreshButtonProps & ButtonProps
> = ({ onRefresh, loading, onClick, autoRefreshSec = 60, ...btnProps }) => {
  const [remainingSec, setRemainingSec] = useState(autoRefreshSec)
  const percent = 100 - Math.floor((remainingSec / autoRefreshSec) * 100)
  const timerRef = useRef<number>()
  const refreshHandler = () => {
    setRemainingSec(autoRefreshSec)
    onRefresh()
  }

  useEffect(() => {
    if (loading) {
      return
    }

    timerRef.current = window.setTimeout(() => {
      if (remainingSec === 0) {
        refreshHandler()
      } else {
        setRemainingSec((v) => v - 1)
      }
    }, 1000)

    return () => window.clearTimeout(timerRef.current)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [remainingSec, loading])

  return (
    <Button
      {...btnProps}
      icon={
        !loading && (
          <Progress
            type='circle'
            trailColor='#ddd'
            strokeColor='var(--ant-primary-color)'
            percent={percent}
            strokeWidth={16}
            width={14}
            showInfo={false}
            className='mr-2 mb-2'
          />
        )
      }
      loading={loading}
      onClick={() => {
        refreshHandler()
        onClick?.()
      }}
    >
      Refresh
    </Button>
  )
}
