"use client";

import { useState, useRef, useEffect } from "react";
import {
  Plus,
  Send,
  Trash2,
  MessageSquare,
  Settings,
  Loader2,
  Bot,
  Wifi,
  WifiOff,
  FolderOpen,
  X,
} from "lucide-react";
import { Button } from "@/shared/components/ui/button";
import { Input } from "@/shared/components/ui/input";
import { Badge } from "@/shared/components/ui/badge";
import { cn } from "@/shared/lib/utils";
import { useChat } from "../hooks/use-chat";
import { useTags } from "@/core/tagging/use-tags";

const PROVIDER_LABELS: Record<string, string> = {
  openai: "OpenAI",
  anthropic: "Claude",
  ollama: "Ollama",
  demo: "Demo",
};

export function AiChatModule() {
  const {
    sessions,
    activeSession,
    activeSessionId,
    sending,
    providerConfig,
    createSession,
    updateSession,
    sendMessage,
    deleteSession,
    selectSession,
  } = useChat();

  const { tags: projectTags } = useTags("project");

  const [input, setInput] = useState("");
  const [showConfig, setShowConfig] = useState(false);
  const [showProjectPicker, setShowProjectPicker] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [activeSession?.messages.length]);

  const providerLabel = providerConfig
    ? (PROVIDER_LABELS[providerConfig.provider] ?? providerConfig.provider)
    : "Demo";
  const isConfigured = providerConfig?.isConfigured ?? false;

  const handleSend = async () => {
    if (!input.trim() || sending) return;
    const text = input.trim();
    setInput("");

    if (!activeSessionId) {
      await createSession();
    }

    await sendMessage(text);
  };

  return (
    <div className="flex h-[calc(100vh-12rem)] gap-4">
      {/* Sidebar - sessions */}
      <div className="hidden w-64 shrink-0 flex-col gap-2 md:flex">
        <Button onClick={() => createSession()} size="sm" className="w-full">
          <Plus className="mr-1.5 h-3.5 w-3.5" /> Conversație nouă
        </Button>

        <div className="flex-1 space-y-1 overflow-y-auto">
          {sessions.map((session) => (
            <div
              key={session.id}
              className={cn(
                "group flex cursor-pointer items-center justify-between rounded-md px-2 py-1.5 text-sm transition-colors",
                session.id === activeSessionId
                  ? "bg-accent"
                  : "hover:bg-accent/50",
              )}
              onClick={() => selectSession(session.id)}
            >
              <div className="flex min-w-0 flex-col">
                <div className="flex items-center gap-1.5">
                  <MessageSquare className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
                  <span className="truncate">{session.title}</span>
                </div>
                {session.projectName && (
                  <span className="ml-5 truncate text-[10px] text-muted-foreground">
                    {session.projectName}
                  </span>
                )}
              </div>
              <Button
                variant="ghost"
                size="icon"
                className="h-6 w-6 opacity-0 group-hover:opacity-100"
                onClick={(e) => {
                  e.stopPropagation();
                  deleteSession(session.id);
                }}
              >
                <Trash2 className="h-3 w-3 text-destructive" />
              </Button>
            </div>
          ))}
        </div>
      </div>

      {/* Main chat area */}
      <div className="flex flex-1 flex-col rounded-lg border">
        {/* Header */}
        <div className="flex items-center justify-between border-b px-4 py-2">
          <div className="flex items-center gap-2">
            <h3 className="text-sm font-medium">
              {activeSession?.title ?? "Chat AI"}
            </h3>
            {/* Project link */}
            {activeSession && (
              <div className="relative">
                {activeSession.projectName ? (
                  <Badge
                    variant="secondary"
                    className="cursor-pointer gap-1 text-[10px]"
                    onClick={() => setShowProjectPicker(!showProjectPicker)}
                  >
                    <FolderOpen className="h-2.5 w-2.5" />
                    {activeSession.projectName}
                    <X
                      className="h-2.5 w-2.5 opacity-60 hover:opacity-100"
                      onClick={(e) => {
                        e.stopPropagation();
                        updateSession(activeSession.id, {
                          projectTagId: undefined,
                          projectName: undefined,
                        });
                      }}
                    />
                  </Badge>
                ) : (
                  <Button
                    variant="ghost"
                    size="sm"
                    className="h-6 gap-1 px-2 text-[10px] text-muted-foreground"
                    onClick={() => setShowProjectPicker(!showProjectPicker)}
                  >
                    <FolderOpen className="h-3 w-3" />
                    Proiect
                  </Button>
                )}
                {showProjectPicker && projectTags.length > 0 && (
                  <div className="absolute left-0 top-full z-50 mt-1 max-h-48 w-52 overflow-y-auto rounded-md border bg-popover p-1 shadow-md">
                    {projectTags.map((tag) => (
                      <button
                        key={tag.id}
                        type="button"
                        className={cn(
                          "flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs hover:bg-accent",
                          activeSession.projectTagId === tag.id &&
                            "bg-accent font-medium",
                        )}
                        onClick={() => {
                          updateSession(activeSession.id, {
                            projectTagId: tag.id,
                            projectName: tag.projectCode
                              ? `${tag.projectCode} — ${tag.label}`
                              : tag.label,
                          });
                          setShowProjectPicker(false);
                        }}
                      >
                        {tag.color && (
                          <span
                            className="h-2 w-2 rounded-full"
                            style={{ backgroundColor: tag.color }}
                          />
                        )}
                        <span className="truncate">
                          {tag.projectCode && (
                            <span className="mr-1 font-mono text-muted-foreground">
                              {tag.projectCode}
                            </span>
                          )}
                          {tag.label}
                        </span>
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
            <Badge
              variant={isConfigured ? "default" : "outline"}
              className={cn(
                "text-[10px]",
                isConfigured && "bg-green-600 hover:bg-green-700",
              )}
            >
              {isConfigured ? (
                <Wifi className="mr-1 h-2.5 w-2.5" />
              ) : (
                <WifiOff className="mr-1 h-2.5 w-2.5" />
              )}
              {providerLabel}
            </Badge>
          </div>
          <Button
            variant="ghost"
            size="icon"
            className="h-7 w-7"
            onClick={() => setShowConfig(!showConfig)}
          >
            <Settings className="h-3.5 w-3.5" />
          </Button>
        </div>

        {/* Config banner */}
        {showConfig && (
          <div className="border-b bg-muted/30 px-4 py-3 text-xs text-muted-foreground">
            <p className="font-medium">Configurare API</p>
            {providerConfig ? (
              <>
                <div className="mt-2 grid grid-cols-2 gap-x-4 gap-y-1">
                  <span>Provider:</span>
                  <span className="font-medium text-foreground">
                    {providerLabel}
                  </span>
                  <span>Model:</span>
                  <span className="font-medium text-foreground">
                    {providerConfig.model}
                  </span>
                  <span>Max tokens:</span>
                  <span className="font-medium text-foreground">
                    {providerConfig.maxTokens}
                  </span>
                  <span>Stare:</span>
                  <span
                    className={cn(
                      "font-medium",
                      isConfigured ? "text-green-600" : "text-amber-600",
                    )}
                  >
                    {isConfigured ? "Configurat" : "Neconfigurat (mod demo)"}
                  </span>
                </div>
                {!isConfigured && (
                  <p className="mt-2 text-amber-600">
                    Setați variabilele de mediu AI_PROVIDER, AI_API_KEY și
                    AI_MODEL pentru a activa răspunsurile AI reale.
                  </p>
                )}
              </>
            ) : (
              <p className="mt-1">Se verifică conexiunea la API...</p>
            )}
          </div>
        )}

        {/* Messages */}
        <div className="flex-1 overflow-y-auto p-4">
          {!activeSession || activeSession.messages.length === 0 ? (
            <div className="flex h-full flex-col items-center justify-center text-muted-foreground">
              <MessageSquare className="mb-3 h-10 w-10 opacity-30" />
              <p className="text-sm">Începe o conversație nouă</p>
              <p className="mt-1 text-xs">
                Scrie un mesaj sau creează o sesiune nouă din bara laterală.
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {activeSession.messages.map((msg) => (
                <div
                  key={msg.id}
                  className={cn(
                    "max-w-[80%] rounded-lg px-3 py-2 text-sm",
                    msg.role === "user"
                      ? "ml-auto bg-primary text-primary-foreground"
                      : "bg-muted",
                  )}
                >
                  {msg.role === "assistant" && (
                    <Bot className="mb-1 inline h-3.5 w-3.5 text-muted-foreground" />
                  )}
                  <p className="whitespace-pre-wrap">{msg.content}</p>
                  <p
                    className={cn(
                      "mt-1 text-[10px]",
                      msg.role === "user"
                        ? "text-primary-foreground/60"
                        : "text-muted-foreground",
                    )}
                  >
                    {new Date(msg.timestamp).toLocaleTimeString("ro-RO", {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </p>
                </div>
              ))}
              {sending && (
                <div className="flex max-w-[80%] items-center gap-2 rounded-lg bg-muted px-3 py-2 text-sm text-muted-foreground">
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                  <span>Se generează răspunsul...</span>
                </div>
              )}
              <div ref={messagesEndRef} />
            </div>
          )}
        </div>

        {/* Input */}
        <div className="border-t p-3">
          <div className="flex gap-2">
            <Input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) =>
                e.key === "Enter" && !e.shiftKey && handleSend()
              }
              placeholder={sending ? "Se generează..." : "Scrie un mesaj..."}
              disabled={sending}
              className="flex-1"
            />
            <Button onClick={handleSend} disabled={!input.trim() || sending}>
              {sending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}
