import { useState } from 'react';

// --- ASA GENERATED START ---
// React hook for billing/cancel slice.
// --- ASA GENERATED END ---

// --- USER CODE START ---

export function useCancel() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  async function cancel(): Promise<boolean> {
    setLoading(true);
    setError(null);
    setSuccess(false);

    try {
      const res = await fetch('/api/billing/cancel', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
      });

      const data = await res.json();

      if (!data.success) {
        setError(data.error);
        return false;
      }

      setSuccess(true);
      return true;
    } catch {
      setError('Failed to cancel subscription. Please try again.');
      return false;
    } finally {
      setLoading(false);
    }
  }

  return { cancel, loading, error, success };
}

// --- USER CODE END ---
