import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToast } from "@/hooks/use-toast";
import { createAgent } from "@/lib/api/agents";
import { AI_MODELS, getModelIdByValue } from "@/lib/constants/aiModels";

interface CreateAgentDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function CreateAgentDialog({ open, onOpenChange }: CreateAgentDialogProps) {
  const navigate = useNavigate();
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [name, setName] = useState("");
  const [selectedModel, setSelectedModel] = useState("");

  const createAgentMutation = useMutation({
    mutationFn: ({ name, modelId }: { name: string; modelId: number }) =>
      createAgent(name, modelId),
    onSuccess: (data) => {
      toast({
        title: "Agente criado",
        description: `${data.agent_name} foi criado com sucesso.`,
      });

      // Invalidate agents query to refetch the list
      queryClient.invalidateQueries({ queryKey: ["agents"] });

      onOpenChange(false);

      // Navegar para a tela de detalhes do novo agente
      navigate(`/agents/${data.agent_id}`);

      // Reset form
      setName("");
      setSelectedModel("");
    },
    onError: (error: any) => {
      toast({
        title: "Erro ao criar agente",
        description: error.response?.data?.message || "Ocorreu um erro ao criar o agente.",
        variant: "destructive",
      });
    },
  });

  const handleCreate = () => {
    const modelId = getModelIdByValue(selectedModel);
    if (!modelId) {
      toast({
        title: "Erro",
        description: "Modelo de IA inválido.",
        variant: "destructive",
      });
      return;
    }

    createAgentMutation.mutate({ name, modelId });
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Criar Novo Agente</DialogTitle>
          <DialogDescription>
            Preencha os dados básicos do agente. Você poderá configurar o system prompt na próxima tela.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="name">Nome do Agente</Label>
            <Input
              id="name"
              placeholder="Ex: Agente de Atendimento"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="model">Modelo de IA</Label>
            <Select value={selectedModel} onValueChange={setSelectedModel}>
              <SelectTrigger id="model">
                <SelectValue placeholder="Selecione um modelo" />
              </SelectTrigger>
              <SelectContent>
                {AI_MODELS.map((model) => (
                  <SelectItem key={model.value} value={model.value}>
                    {model.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t">
            <Button variant="outline" onClick={() => onOpenChange(false)}>
              Cancelar
            </Button>
            <Button
              onClick={handleCreate}
              disabled={!name || !selectedModel || createAgentMutation.isPending}
            >
              {createAgentMutation.isPending ? "Criando..." : "Criar Agente"}
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}
