import { ChevronDown, UserCog, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { useState, useEffect } from "react";
import { fetchModelsFromDatabase, ModelConfig } from "@/config/models";

// Texto padrão da personalidade (mesmo valor usado em ChatView)
const DEFAULT_SYSTEM_PROMPT = "Você é um assistente útil e prestativo.";

interface ChatHeaderProps {
  showModelSelector?: boolean;
  selectedModel?: string;
  onModelChange?: (model: string) => void;
  systemPrompt?: string;
  onSystemPromptChange?: (prompt: string) => void;
}

export const ChatHeader = ({
  showModelSelector = false,
  selectedModel = "GPT-4o",
  onModelChange,
  systemPrompt = DEFAULT_SYSTEM_PROMPT,
  onSystemPromptChange
}: ChatHeaderProps) => {
  const [isPersonalityOpen, setIsPersonalityOpen] = useState(false);
  const [tempSystemPrompt, setTempSystemPrompt] = useState(systemPrompt);
  const [models, setModels] = useState<ModelConfig[]>([]);
  const [isLoadingModels, setIsLoadingModels] = useState(true);

  // Carrega modelos da API ao montar o componente
  useEffect(() => {
    const loadModels = async () => {
      setIsLoadingModels(true);
      try {
        const modelsFromAPI = await fetchModelsFromDatabase();
        setModels(modelsFromAPI);
      } catch (error) {
        console.error('Erro ao carregar modelos:', error);
      } finally {
        setIsLoadingModels(false);
      }
    };

    loadModels();
  }, []);

  const handleSavePersonality = () => {
    if (onSystemPromptChange) {
      onSystemPromptChange(tempSystemPrompt);
    }
    setIsPersonalityOpen(false);
  };

  return (
    <header className="border-b border-border bg-card/50 backdrop-blur-sm px-3 md:px-6 py-3 md:py-4 flex items-center justify-between">
      <div className="flex items-center gap-2 md:gap-4">
        <div className="flex items-center gap-2">
          <div className="w-2 h-2 rounded-full bg-primary animate-pulse-glow" />
          <span className="text-sm text-muted-foreground">Online</span>
        </div>
        
        {showModelSelector && onModelChange && (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button
                variant="outline"
                className="gap-1 md:gap-2 glass-effect text-xs md:text-sm"
                disabled={isLoadingModels}
              >
                {isLoadingModels ? (
                  <>
                    <Loader2 className="w-3 h-3 md:w-4 md:h-4 animate-spin" />
                    <span className="font-medium">Carregando...</span>
                  </>
                ) : (
                  <>
                    <span className="font-medium truncate max-w-[80px] md:max-w-none">{selectedModel}</span>
                    <ChevronDown className="w-3 h-3 md:w-4 md:h-4" />
                  </>
                )}
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="start" className="glass-effect bg-popover border-border z-50">
              {models.map((model) => (
                <DropdownMenuItem
                  key={model.id}
                  className="cursor-pointer"
                  onClick={() => onModelChange(model.name)}
                >
                  <div className="flex flex-col">
                    <span className="font-medium">{model.name}</span>
                    {model.description && (
                      <span className="text-xs text-muted-foreground">{model.description}</span>
                    )}
                  </div>
                </DropdownMenuItem>
              ))}
            </DropdownMenuContent>
          </DropdownMenu>
        )}

        {showModelSelector && onSystemPromptChange && (
          <Dialog open={isPersonalityOpen} onOpenChange={setIsPersonalityOpen}>
            <DialogTrigger asChild>
              <Button
                variant="outline"
                className="gap-1 md:gap-2 glass-effect text-xs md:text-sm"
                onClick={() => setTempSystemPrompt(systemPrompt)}
              >
                <UserCog className="w-3 h-3 md:w-4 md:h-4" />
                <span className="hidden md:inline font-medium">Personalidade</span>
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Personalidade da IA</DialogTitle>
                <DialogDescription>
                  Defina o estilo, tom ou função da IA nesta conversa
                </DialogDescription>
              </DialogHeader>
              <Textarea
                value={tempSystemPrompt}
                onChange={(e) => setTempSystemPrompt(e.target.value)}
                placeholder="Ex: Você é um assistente técnico especializado em programação..."
                className="min-h-[150px]"
              />
              <div className="flex justify-end gap-2">
                <Button
                  variant="outline"
                  onClick={() => setIsPersonalityOpen(false)}
                >
                  Cancelar
                </Button>
                <Button onClick={handleSavePersonality}>
                  Salvar
                </Button>
              </div>
            </DialogContent>
          </Dialog>
        )}
      </div>

      <div className="hidden md:block text-sm text-muted-foreground">
        {showModelSelector ? "Modelo de linguagem avançado" : "Sistema HGTX Codex"}
      </div>
    </header>
  );
};
