"use client"

import { useState, useEffect } from "react"
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { useToast } from "@/hooks/use-toast"
import { Loader2, Trash2, Edit, Save, X, RefreshCw } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"

interface Agente {
  nome: string
  promptPrincipal: string
  promptClassifica: string
}

export function ListaAgentes() {
  const { toast } = useToast()
  const [agentes, setAgentes] = useState<Agente[]>([])
  const [carregando, setCarregando] = useState(true)
  const [agenteEditando, setAgenteEditando] = useState<Agente | null>(null)
  const [salvando, setSalvando] = useState(false)

  useEffect(() => {
    carregarAgentes()
  }, [])

  const carregarAgentes = async () => {
    setCarregando(true)
    try {
      const response = await fetch("/api/agentes/listar")
      const data = await response.json()

      if (data.success) {
        setAgentes(data.agentes || [])
      } else {
        toast({
          title: "Erro ao carregar",
          description: data.error || "Não foi possível carregar os agentes.",
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "Erro",
        description: "Ocorreu um erro ao carregar os agentes.",
        variant: "destructive",
      })
    } finally {
      setCarregando(false)
    }
  }

  const excluirAgente = async (nome: string) => {
    try {
      const response = await fetch("/api/agentes/excluir", {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ nome }),
      })

      const data = await response.json()

      if (data.success) {
        toast({
          title: "Agente excluído",
          description: "O agente foi excluído com sucesso.",
          variant: "default",
        })
        carregarAgentes()
      } else {
        toast({
          title: "Erro ao excluir",
          description: data.error || "Não foi possível excluir o agente.",
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "Erro",
        description: "Ocorreu um erro ao excluir o agente.",
        variant: "destructive",
      })
    }
  }

  const salvarEdicao = async () => {
    if (!agenteEditando) return

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

      const data = await response.json()

      if (data.success) {
        toast({
          title: "Agente atualizado",
          description: "O agente foi atualizado com sucesso.",
          variant: "default",
        })
        setAgenteEditando(null)
        carregarAgentes()
      } else {
        toast({
          title: "Erro ao atualizar",
          description: data.error || "Não foi possível atualizar o agente.",
          variant: "destructive",
        })
      }
    } catch (error) {
      toast({
        title: "Erro",
        description: "Ocorreu um erro ao atualizar o agente.",
        variant: "destructive",
      })
    } finally {
      setSalvando(false)
    }
  }

  if (carregando) {
    return (
      <div className="flex justify-center items-center py-8">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
        <span className="ml-2">Carregando agentes...</span>
      </div>
    )
  }

  if (agentes.length === 0) {
    return (
      <Card className="w-full">
        <CardHeader>
          <CardTitle>Nenhum Agente Encontrado</CardTitle>
          <CardDescription>Nenhum agente de IA foi criado ainda. Crie seu primeiro agente!</CardDescription>
        </CardHeader>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-semibold">Agentes Cadastrados</h2>
        <Button variant="outline" size="sm" onClick={carregarAgentes}>
          <RefreshCw className="h-4 w-4 mr-2" />
          Atualizar
        </Button>
      </div>

      {agentes.map((agente) => (
        <Card key={agente.nome} className="w-full">
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              <span>{agente.nome}</span>
              <div className="flex space-x-2">
                <Dialog>
                  <DialogTrigger asChild>
                    <Button variant="outline" size="sm">
                      <Edit className="h-4 w-4 mr-2" />
                      Editar
                    </Button>
                  </DialogTrigger>
                  <DialogContent className="sm:max-w-[600px]">
                    <DialogHeader>
                      <DialogTitle>Editar Agente: {agente.nome}</DialogTitle>
                      <DialogDescription>
                        Modifique os prompts do agente e clique em salvar quando terminar.
                      </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4 py-4">
                      <div className="space-y-2">
                        <h4 className="font-medium">Prompt Principal</h4>
                        <Textarea
                          value={
                            agenteEditando?.nome === agente.nome
                              ? agenteEditando.promptPrincipal
                              : agente.promptPrincipal
                          }
                          rows={5}
                          onChange={(e) =>
                            setAgenteEditando({
                              nome: agente.nome,
                              promptPrincipal: e.target.value,
                              promptClassifica:
                                agenteEditando?.nome === agente.nome
                                  ? agenteEditando.promptClassifica
                                  : agente.promptClassifica,
                            })
                          }
                          onClick={() => {
                            if (!agenteEditando || agenteEditando.nome !== agente.nome) {
                              setAgenteEditando({ ...agente })
                            }
                          }}
                        />
                      </div>
                      <div className="space-y-2">
                        <h4 className="font-medium">Prompt de Classificação</h4>
                        <Textarea
                          value={
                            agenteEditando?.nome === agente.nome
                              ? agenteEditando.promptClassifica
                              : agente.promptClassifica
                          }
                          rows={5}
                          onChange={(e) =>
                            setAgenteEditando({
                              nome: agente.nome,
                              promptPrincipal:
                                agenteEditando?.nome === agente.nome
                                  ? agenteEditando.promptPrincipal
                                  : agente.promptPrincipal,
                              promptClassifica: e.target.value,
                            })
                          }
                          onClick={() => {
                            if (!agenteEditando || agenteEditando.nome !== agente.nome) {
                              setAgenteEditando({ ...agente })
                            }
                          }}
                        />
                      </div>
                    </div>
                    <DialogFooter>
                      <Button variant="outline" onClick={() => setAgenteEditando(null)}>
                        <X className="h-4 w-4 mr-2" />
                        Cancelar
                      </Button>
                      <Button onClick={salvarEdicao} disabled={salvando}>
                        {salvando ? (
                          <>
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                            Salvando...
                          </>
                        ) : (
                          <>
                            <Save className="mr-2 h-4 w-4" />
                            Salvar Alterações
                          </>
                        )}
                      </Button>
                    </DialogFooter>
                  </DialogContent>
                </Dialog>

                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button variant="destructive" size="sm">
                      <Trash2 className="h-4 w-4 mr-2" />
                      Excluir
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>Excluir Agente</AlertDialogTitle>
                      <AlertDialogDescription>
                        Tem certeza que deseja excluir o agente "{agente.nome}"? Esta ação não pode ser desfeita.
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>Cancelar</AlertDialogCancel>
                      <AlertDialogAction onClick={() => excluirAgente(agente.nome)}>
                        Confirmar Exclusão
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              </div>
            </CardTitle>
            <CardDescription>Configuração do agente de IA</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <h3 className="text-sm font-medium mb-2">Prompt Principal</h3>
              <div className="p-3 bg-muted rounded-md text-sm whitespace-pre-wrap">{agente.promptPrincipal}</div>
            </div>
            <div>
              <h3 className="text-sm font-medium mb-2">Prompt de Classificação</h3>
              <div className="p-3 bg-muted rounded-md text-sm whitespace-pre-wrap">{agente.promptClassifica}</div>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}
