import { useState } from 'react';
import type { FunnelDefinition } from '@/lib/funnel/types';

interface CreateFunnelData {
  name: string;
  description?: string;
  funnelData: FunnelDefinition;
}

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

  const createFunnel = async (data: CreateFunnelData) => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch('/api/funnels', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
      });

      if (!response.ok) {
        throw new Error('Failed to create funnel');
      }

      return await response.json();
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to create funnel';
      setError(message);
      throw new Error(message);
    } finally {
      setLoading(false);
    }
  };

  return { createFunnel, loading, error };
}

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

  const duplicateFunnel = async (funnelId: string, name: string) => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch(`/api/funnels/${funnelId}/duplicate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name }),
      });

      if (!response.ok) {
        throw new Error('Failed to duplicate funnel');
      }

      return await response.json();
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to duplicate funnel';
      setError(message);
      throw new Error(message);
    } finally {
      setLoading(false);
    }
  };

  return { duplicateFunnel, loading, error };
}

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

  const deleteFunnel = async (funnelId: string) => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch(`/api/funnels/${funnelId}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to delete funnel');
      }

      return true;
    } catch (err) {
      const message = err instanceof Error ? err.message : 'Failed to delete funnel';
      setError(message);
      throw new Error(message);
    } finally {
      setLoading(false);
    }
  };

  return { deleteFunnel, loading, error };
}
