import { useToast } from '@/src/hooks/useToast';
import { useRouter } from 'next/navigation';
import { NextResponse } from 'next/server';
import { useState } from 'react';

interface UseApiWithToastOptions<T> {
  redirectTo?: string | ((data: T) => string);
  mutate?: () => void;
  messageOnSuccess?: string;
  messageOnError?: string;
  onSuccess?: () => void;
}

export function useApiWithToast() {
  const { toast } = useToast();
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);

  const handle = async <T>(
    promise: Promise<Response | NextResponse>,
    options?: UseApiWithToastOptions<T>
  ): Promise<T | undefined> => {
    try {
      setIsLoading(true);
      const response = await promise;
      const responseData = await response.json();

      if (!response.ok) {
        throw new Error(options?.messageOnError ?? responseData?.message ?? 'Something went wrong');
      }

      toast({
        title: 'Success',
        description: options?.messageOnSuccess ?? responseData.message,
      });

      if (options?.redirectTo) {
        const redirectPath =
          typeof options.redirectTo === 'function' ? options.redirectTo(responseData.data) : options.redirectTo;

        router.push(redirectPath);
      }

      if (options?.mutate) {
        options.mutate();
      }

      if (options?.onSuccess) {
        options.onSuccess();
      }

      return responseData.data;
    } catch (error) {
      toast({
        title: 'Error',
        description: error?.message ?? 'Unknown error',
        variant: 'destructive',
      });
    } finally {
      setIsLoading(false);
    }
  };

  return { handle, isLoading };
}
