'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';

interface DeleteButtonProps {
    templateId: string;
}

export default function DeleteButton({ templateId }: DeleteButtonProps) {
    const router = useRouter();
    const [isDeleting, setIsDeleting] = useState(false);
    const [showConfirm, setShowConfirm] = useState(false);

    const handleDelete = async () => {
        if (isDeleting) return;

        setIsDeleting(true);
        try {
            const response = await fetch(`/api/email-templates/${templateId}`, {
                method: 'DELETE',
            });

            if (!response.ok) {
                throw new Error('Failed to delete email template');
            }

            // Refresh the page to show updated list
            router.refresh();
        } catch (error) {
            console.error('Error deleting email template:', error);
            alert('Failed to delete email template');
        } finally {
            setIsDeleting(false);
            setShowConfirm(false);
        }
    };

    return (
        <>
            {showConfirm ? (
                <span className="inline-flex items-center">
                    <button
                        onClick={handleDelete}
                        className="text-red-600 hover:text-red-900 mr-2"
                        disabled={isDeleting}
                    >
                        {isDeleting ? 'Deleting...' : 'Confirm'}
                    </button>
                    <button
                        onClick={() => setShowConfirm(false)}
                        className="text-gray-600 hover:text-gray-900"
                        disabled={isDeleting}
                    >
                        Cancel
                    </button>
                </span>
            ) : (
                <button
                    onClick={() => setShowConfirm(true)}
                    className="text-red-600 hover:text-red-900"
                >
                    Delete
                </button>
            )}
        </>
    );
}
