"use client";

import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
import type { AgentDetails } from "@/lib/types";
import { AgentOverviewTab } from "./AgentOverviewTab";
import { AgentSettingsTab } from "./AgentSettingsTab";
import { ChatView } from "@/components/chat/ChatView";
import { ImessageHistory } from "@/components/chat/ImessageHistory";

type Tab = "overview" | "settings" | "chat" | "imessage";

const baseTabs: { id: Tab; label: string }[] = [
  { id: "overview", label: "Overview" },
  { id: "settings", label: "Settings" },
  { id: "chat", label: "Chat" },
];

const imessageTab: { id: Tab; label: string } = { id: "imessage", label: "iMessage" };

interface AgentDetailViewProps {
  agentName: string;
}

export function AgentDetailView({ agentName }: AgentDetailViewProps) {
  const [activeTab, setActiveTab] = useState<Tab>("overview");
  const [details, setDetails] = useState<AgentDetails | null>(null);
  const tabs = details?.fifo ? [...baseTabs, imessageTab] : baseTabs;
  const [online, setOnline] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    fetch(`/api/agents/${agentName}/details`)
      .then((r) => r.json())
      .then((data) => {
        setDetails(data);
        setOnline(data.online ?? false);
      })
      .catch(() => setDetails(null))
      .finally(() => setLoading(false));
  }, [agentName]);

  if (loading) {
    return (
      <div className="flex flex-1 items-center justify-center">
        <Loader2 size={24} className="animate-spin text-zinc-400" />
      </div>
    );
  }

  if (!details) {
    return (
      <div className="flex flex-1 items-center justify-center">
        <p className="text-sm text-zinc-500">Agent not found</p>
      </div>
    );
  }

  return (
    <div className="flex flex-1 flex-col overflow-hidden">
      {/* Tab bar */}
      <div className="flex shrink-0 overflow-x-auto border-b border-zinc-200 bg-zinc-50 px-3 md:px-6 dark:border-zinc-800 dark:bg-zinc-900">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`relative whitespace-nowrap px-3 py-3 text-sm font-medium transition-colors md:px-4 ${
              activeTab === tab.id
                ? "text-zinc-900 dark:text-zinc-100"
                : "text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200"
            }`}
          >
            {tab.label}
            {activeTab === tab.id && (
              <span className="absolute inset-x-0 bottom-0 h-0.5 bg-zinc-900 dark:bg-zinc-100" />
            )}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="flex-1 overflow-y-auto">
        {activeTab === "overview" && (
          <AgentOverviewTab details={details} online={online} />
        )}
        {activeTab === "settings" && (
          <AgentSettingsTab details={details} />
        )}
        {activeTab === "chat" && (
          <div className="flex h-full flex-col">
            <ChatView agentName={agentName} />
          </div>
        )}
        {activeTab === "imessage" && (
          <ImessageHistory />
        )}
      </div>
    </div>
  );
}
