import { useState } from 'react';
import type { FormEvent } from 'react';
import { API_BASE_URL } from '../lib/shared';

type RespostaIA = {
  answer?: string;
  error?: string;
};

export default function OllamaChat() {
  const [pergunta, setPergunta] = useState('');
  const [resposta, setResposta] = useState('');
  const [erro, setErro] = useState('');
  const [carregando, setCarregando] = useState(false);

  async function enviar(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setErro('');
    setResposta('');

    if (!pergunta.trim()) {
      setErro('Digite uma pergunta.');
      return;
    }

    setCarregando(true);

    try {
      const response = await fetch(`${API_BASE_URL}/ollama_chat.php`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ question: pergunta }),
      });

      const dados = await response.json() as RespostaIA;

      if (!response.ok) {
        throw new Error(dados.error || `Erro HTTP ${response.status}`);
      }

      if (typeof dados.answer !== 'string') {
        throw new Error('A resposta da IA veio em formato inesperado.');
      }

      setResposta(dados.answer);
    } catch (e) {
      setErro(e instanceof Error ? e.message : 'Não foi possível consultar a IA.');
    } finally {
      setCarregando(false);
    }
  }

  return (
    <section>
      <h2>Assistente de IA</h2>

      <form onSubmit={enviar}>
        <label htmlFor="ollama-question">Sua pergunta</label>
        <textarea
          id="ollama-question"
          value={pergunta}
          onChange={event => setPergunta(event.target.value)}
          maxLength={1000}
          required
        />

        <button type="submit" disabled={carregando}>
          {carregando ? 'Consultando…' : 'Perguntar'}
        </button>
      </form>

      {erro && <p role="alert">{erro}</p>}
      {resposta && <p>{resposta}</p>}
    </section>
  );
}