"use client"

import { useState } from "react"
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { useToast } from "@/hooks/use-toast"
import { Loader2, Save, Plus, BrainCircuit } from "lucide-react"

export function NovoAgente() {
  const { toast } = useToast()
  const [mostrarForm, setMostrarForm] = useState(false)
  const [salvando, setSalvando] = useState(false)
  const [nomeAgente, setNomeAgente] = useState("")
  const [promptPrincipal, setPromptPrincipal] = useState("")
  const [promptClassifica, setPromptClassifica] = useState("")

  const salvarAgente = async () => {
    if (!nomeAgente.trim()) {
      toast({
        title: "Campo obrigatório",
        description: "O nome do agente é obrigatório.",
        variant: "destructive",
      })
      return
    }

    if (!promptPrincipal.trim() || !promptClassifica.trim()) {
      toast({
        title: "Campos obrigatórios",
        description: "Ambos os prompts são obrigatórios.",
        variant: "destructive",
      })
      return
    }

    setSalvando(true)
    try {
      const response = await fetch("/api/agentes/salvar", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          nome: nomeAgente,
          promptPrincipal,
          promptClassifica,
        }),
      })

      const data = await response.json()

      if (data.success) {
        toast({
          title: "Agente salvo",
          description: "O agente foi salvo com sucesso.",
          variant: "default",
        })
        // Limpar formulário e fechar
        setNomeAgente("")
        setPromptPrincipal("")
        setPromptClassifica("")
        setMostrarForm(false)
      } else {
        toast({
          title: "Erro ao salvar",
          description: data.error || "Não foi possível salvar o agente.",
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "Erro",
        description: "Ocorreu um erro ao salvar o agente.",
        variant: "destructive",
      })
    } finally {
      setSalvando(false)
    }
  }

  if (!mostrarForm) {
    return (
      <div className="flex justify-end mb-4">
        <Button onClick={() => setMostrarForm(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Novo Agente
        </Button>
      </div>
    )
  }

  return (
    <Card className="w-full border-2 border-primary/20">
      <CardHeader className="bg-primary/5">
        <CardTitle className="flex items-center">
          <BrainCircuit className="h-5 w-5 mr-2 text-primary" />
          Novo Agente de IA
        </CardTitle>
        <CardDescription>Crie um novo agente de IA com prompts personalizados</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4 pt-6">
        <div className="space-y-2">
          <Label htmlFor="nome-agente">Nome do Agente</Label>
          <Input
            id="nome-agente"
            placeholder="Ex: cemig"
            value={nomeAgente}
            onChange={(e) => setNomeAgente(e.target.value)}
          />
          <p className="text-sm text-muted-foreground">
            O nome do agente será usado como identificador no banco de dados.
          </p>
        </div>

        <div className="space-y-2">
          <Label htmlFor="prompt-principal">Prompt Principal</Label>
          <Textarea
            id="prompt-principal"
            placeholder="Digite o prompt principal do agente..."
            rows={5}
            value={promptPrincipal}
            onChange={(e) => setPromptPrincipal(e.target.value)}
          />
          <p className="text-sm text-muted-foreground">
            Este é o prompt principal que define o comportamento do agente.
          </p>
        </div>

        <div className="space-y-2">
          <Label htmlFor="prompt-classifica">Prompt de Classificação</Label>
          <Textarea
            id="prompt-classifica"
            placeholder="Digite o prompt de classificação..."
            rows={5}
            value={promptClassifica}
            onChange={(e) => setPromptClassifica(e.target.value)}
          />
          <p className="text-sm text-muted-foreground">Este prompt define como o agente classifica as entradas.</p>
        </div>
      </CardContent>
      <CardFooter className="flex justify-between">
        <Button variant="outline" onClick={() => setMostrarForm(false)}>
          Cancelar
        </Button>
        <Button onClick={salvarAgente} disabled={salvando}>
          {salvando ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Salvando...
            </>
          ) : (
            <>
              <Save className="mr-2 h-4 w-4" />
              Salvar Agente
            </>
          )}
        </Button>
      </CardFooter>
    </Card>
  )
}
