import { DocumentDuplicateIcon, PencilSquareIcon } from '@heroicons/react/24/outline';
import { Cog8ToothIcon, TrashIcon } from '@heroicons/react/24/solid';
import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import LoadingSpinner from '../../../../components/LoadingSpinner';
import { useAddBadgeMutation } from '../../../../features/badges/badgesApi';

const BadgeActions = ({ badge, setShowDeleteModal, setDeleteId }) => {
  const [addBadge, { isLoading }] = useAddBadgeMutation();
  const [open, setOpen] = useState(false);
  const wrapperRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
        setOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleDuplicateBadge = async (data) => {
    try {
      const duplicateData = { ...data };
      delete duplicateData.created_at;
      delete duplicateData.updated_at;
      duplicateData.badge_name = data.badge_name + ' (Copy)';
      duplicateData.status = '0';
      await addBadge(duplicateData).unwrap();
      toast.success('Badge duplicated successfully');
    } catch {
      toast.error('Failed to duplicate badge');
    }
  };

  const navigate = useNavigate();
  return (
    <div ref={wrapperRef} className='wmx-flex wmx-items-center wmx-justify-center'>
      <div className='wmx-relative wmx-inline-block'>
        <button
          onClick={() => setOpen((prev) => !prev)}
          className='wmx-flex wmx-items-center wmx-justify-center wmx-border-none wmx-shadow-none wmx-outline-none'
        >
          {!isLoading ? <Cog8ToothIcon className='wmx-size-5' /> : <LoadingSpinner className='wmx-size-5' />}
        </button>
        {open && (
          <div className='wmx-absolute wmx-top-[22px] wmx-right-0 wmx-transform wmx-z-10'>
            <div className='wmx-bg-white wmx-border wmx-border-gray-300 wmx-p-1 wmx-pr-1.5 wmx-rounded-lg wmx-shadow-md'>
              <button
                className='wmx-flex wmx-items-center wmx-gap-1 hover:wmx-bg-gray-100 wmx-px-1 wmx-py-0.5 wmx-rounded'
                onClick={() => {
                  navigate(`editor?id=${badge.id}`, { state: { badge } });
                  setOpen(false);
                }}
              >
                <PencilSquareIcon className='wmx-size-4' />
                <span className='wmx-text-sm wmx-mt-1'>Edit</span>
              </button>

              <button
                className='wmx-flex wmx-items-center wmx-gap-1 hover:wmx-bg-gray-100 wmx-px-1 wmx-py-0.5 wmx-rounded'
                onClick={() => {
                  handleDuplicateBadge(badge);
                  setOpen(false);
                }}
              >
                <DocumentDuplicateIcon className='wmx-size-4' />
                <span className='wmx-text-sm wmx-mt-0.5'>Duplicate</span>
              </button>

              <button
                className='wmx-flex wmx-items-center wmx-gap-1 wmx-px-1 wmx-py-0.5 wmx-rounded wmx-text-red-500'
                onClick={() => {
                  setDeleteId(badge.id);
                  setShowDeleteModal(true);
                  setOpen(false);
                }}
              >
                <TrashIcon className='wmx-size-4' />
                <span className='wmx-text-sm wmx-mt-0.5'>Delete</span>
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
export default BadgeActions;
