import { useCallback, useEffect, useState } from 'react';
import { RefreshCw } from 'lucide-react';

import { LoadingButtonPrimitive } from '@/components/loading-button';

export const RefreshButton: React.FC<
  React.ComponentProps<typeof LoadingButtonPrimitive> & {
    isRefreshing?: boolean;
  }
> = ({ children, isRefreshing, ...rest }) => {
  const [isAnimating, setIsAnimating] = useState(false);
  const [rotation, setRotation] = useState(0);

  const onTransitionEnd = useCallback(() => {
    if (isRefreshing) {
      setIsAnimating(true);
      setRotation((prev) => prev + 360);
    } else {
      setIsAnimating(false);
    }
  }, [isRefreshing, setRotation]);

  useEffect(() => {
    onTransitionEnd();
  }, [onTransitionEnd]);

  return (
    <LoadingButtonPrimitive variant="ghost" size="icon" loading={isAnimating} {...rest}>
      <RefreshCw
        className="size-4 duration-1000 transition-transform"
        style={{
          transform: `rotate(${rotation}deg)`,
        }}
        onTransitionEnd={onTransitionEnd}
      />
      {children}
    </LoadingButtonPrimitive>
  );
};