'use client';

import { useEffect, useState } from 'react';
import { Icon, IconButton, Presence } from '@chakra-ui/react';
import { FiChevronUp } from 'react-icons/fi';

const BackToTop = () => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setIsVisible(window.pageYOffset > 300);
    };

    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);

  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  return (
    <Presence
      unmountOnExit
      present={isVisible}
      animationName={{ _open: 'fade-in', _closed: 'fade-out' }}
      animationDuration='moderate'
    >
      <IconButton
        variant={{ base: 'solid', _dark: 'subtle' }}
        aria-label='Back to top'
        position='fixed'
        bottom='8'
        right='8'
        borderRadius='full'
        size='lg'
        shadow='lg'
        zIndex='999'
        onClick={scrollToTop}
      >
        <Icon>
          <FiChevronUp />
        </Icon>
      </IconButton>
    </Presence>
  );
};

export default BackToTop;
