"use client";

import { useEffect, useRef, useState } from "react";
import { Bot, Circle, Terminal, CheckCircle2, AlertCircle, Loader2 } from "lucide-react";
import { ChatMessage } from "./ChatMessage";
import { ChatInput } from "./ChatInput";
import { useChat } from "./useChat";
import { StatusIndicator } from "./StatusIndicator";
import { ImessageHistory } from "@/components/chat/ImessageHistory";

interface ChatViewProps {
  agentName: string;
  agentDisplayName?: string;
}

export function ChatView({ agentName, agentDisplayName }: ChatViewProps) {
  const displayName = agentDisplayName || agentName.charAt(0).toUpperCase() + agentName.slice(1);
  const { messages, connected, sending, agentStatus, send } = useChat(agentName);
  const [agentOnline, setAgentOnline] = useState<boolean | null>(null);
  const [agentHasFifo, setAgentHasFifo] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);
  const [activeTab, setActiveTab] = useState<"chat" | "imessage">("chat");

  // Check agent's status and capabilities on mount
  useEffect(() => {
    fetch(`/api/agents/${encodeURIComponent(agentName)}/status`)
      .then((r) => r.json())
      .then((d) => setAgentOnline(d.online as boolean))
      .catch(() => setAgentOnline(false));

    fetch(`/api/agents/${encodeURIComponent(agentName)}/details`)
      .then((r) => r.json())
      .then((d) => setAgentHasFifo(Boolean(d.fifo)))
      .catch(() => setAgentHasFifo(false));
  }, [agentName]);

  // Auto-scroll on new messages or status changes
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, agentStatus]);

  return (
    <div className="flex h-full flex-col">
      {agentHasFifo && (
        <div className="flex border-b border-zinc-200 dark:border-zinc-700">
          <button
            onClick={() => setActiveTab("chat")}
            className={`relative px-4 py-2.5 text-sm font-medium transition-colors ${
              activeTab === "chat"
                ? "text-zinc-900 dark:text-zinc-100"
                : "text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200"
            }`}
          >
            Chat
            {activeTab === "chat" && (
              <span className="absolute inset-x-0 bottom-0 h-0.5 bg-zinc-900 dark:bg-zinc-100" />
            )}
          </button>
          <button
            onClick={() => setActiveTab("imessage")}
            className={`relative px-4 py-2.5 text-sm font-medium transition-colors ${
              activeTab === "imessage"
                ? "text-zinc-900 dark:text-zinc-100"
                : "text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200"
            }`}
          >
            iMessage
            {activeTab === "imessage" && (
              <span className="absolute inset-x-0 bottom-0 h-0.5 bg-zinc-900 dark:bg-zinc-100" />
            )}
          </button>
        </div>
      )}

      {activeTab === "imessage" && agentHasFifo ? (
        <ImessageHistory />
      ) : (
        <>
          {/* Header */}
          <div className="flex items-center gap-3 border-b border-zinc-200 px-3 py-3 md:px-4 dark:border-zinc-800">
            <div className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-100 dark:bg-blue-900/50">
              <Bot size={16} className="text-blue-600 dark:text-blue-400" />
            </div>
            <div className="flex-1">
              <h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">
                {displayName}
              </h2>
              <div className="flex items-center gap-1.5">
                <Circle
                  size={6}
                  className={
                    agentOnline
                      ? "fill-green-500 text-green-500"
                      : agentOnline === false
                        ? "fill-zinc-400 text-zinc-400"
                        : "fill-yellow-500 text-yellow-500"
                  }
                />
                <span className="text-xs text-zinc-500 dark:text-zinc-400">
                  {agentOnline
                    ? "Online"
                    : agentOnline === false
                      ? "Offline"
                      : "Checking..."}
                  {connected && agentOnline && " \u00b7 Connected"}
                </span>
              </div>
            </div>
          </div>

          {/* Messages */}
          <div className="flex-1 overflow-y-auto">
            {messages.length === 0 && (
              <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-center">
                <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-zinc-100 dark:bg-zinc-800">
                  <Bot
                    size={24}
                    className="text-zinc-400 dark:text-zinc-500"
                  />
                </div>
                <div>
                  <p className="text-sm font-medium text-zinc-700 dark:text-zinc-300">
                    Start a conversation with {displayName}
                  </p>
                  <p className="mt-1 text-xs text-zinc-400 dark:text-zinc-500">
                    Persistent AI agent
                  </p>
                </div>
              </div>
            )}
            {messages.map((msg) => (
              <ChatMessage key={msg.id} message={msg} agentDisplayName={displayName} />
            ))}
            {agentStatus && (
              <StatusIndicator
                status={agentStatus.status}
                toolName={agentStatus.toolName}
                agentDisplayName={displayName}
              />
            )}
            <div ref={bottomRef} />
          </div>

          {/* Input */}
          <ChatInput
            onSend={send}
            disabled={sending || agentOnline === false}
            agentDisplayName={displayName}
          />
        </>
      )}
    </div>
  );
}
