import React, { useState, useEffect, useCallback } from 'react';
import { useNeura } from './NeuraProvider';
import { CompletionsRequestOptions, NeuraResponse } from '../types';

interface NeuraCompletionProps {
  options: CompletionsRequestOptions;
  onSuccess?: (response: NeuraResponse) => void;
  onError?: (error: Error) => void;
  children: (state: {
    response: NeuraResponse | null;
    loading: boolean;
    error: Error | null;
    refetch: () => Promise<void>;
  }) => React.ReactNode;
}

export const NeuraCompletion: React.FC<NeuraCompletionProps> = ({
  options,
  onSuccess,
  onError,
  children,
}) => {
  const { sdk } = useNeura();
  const [response, setResponse] = useState<NeuraResponse | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<Error | null>(null);

  const fetchCompletion = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      const result = await sdk.createCompletion(options);
      setResponse(result);
      onSuccess?.(result);
    } catch (err) {
      const error = err instanceof Error ? err : new Error(String(err));
      setError(error);
      onError?.(error);
    } finally {
      setLoading(false);
    }
  }, [sdk, options, onSuccess, onError]);

  useEffect(() => {
    fetchCompletion();
  }, [fetchCompletion]);

  return <>{children({ response, loading, error, refetch: fetchCompletion })}</>;
};