"use client";

import { useEffect, useState, useCallback } from "react";
import { aiAgentApi } from "@/lib/api/aiAgent";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { MessageSquare, Loader2, User, Bot } from "lucide-react";
import { toast } from "sonner";

export default function ConversationsPage() {
  const [conversations, setConversations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [selectedConv, setSelectedConv] = useState<any>(null);
  const [messages, setMessages] = useState<any[]>([]);
  const [detailOpen, setDetailOpen] = useState(false);

  const loadConversations = useCallback(async () => {
    setLoading(true);
    try {
      const res = await aiAgentApi.listConversations({ page, limit: 20 });
      setConversations(res.data || []);
      setTotal(res.total || 0);
    } catch { toast.error("대화 목록 로드 실패"); }
    setLoading(false);
  }, [page]);

  useEffect(() => { loadConversations(); }, [loadConversations]);

  const openDetail = async (conv: any) => {
    try {
      const res = await aiAgentApi.getConversation(conv.id);
      setSelectedConv(res.data.conversation);
      setMessages(res.data.messages || []);
      setDetailOpen(true);
    } catch { toast.error("대화 상세 로드 실패"); }
  };

  return (
    <div className="flex h-full flex-col bg-background">
      <div className="shrink-0 p-6 pb-4">
        <h1 className="text-xl font-bold">대화 모니터링</h1>
        <p className="text-sm text-muted-foreground">에이전트 대화 내역을 모니터링합니다 ({total}건)</p>
      </div>

      <div className="flex-1 overflow-auto px-6 pb-6">
        {loading ? (
          <div className="flex items-center justify-center py-20"><Loader2 className="h-6 w-6 animate-spin" /></div>
        ) : conversations.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
            <MessageSquare className="h-12 w-12 mb-3" />
            <p>대화 내역이 없습니다</p>
          </div>
        ) : (
          <div className="space-y-2">
            {conversations.map((conv) => (
              <div key={conv.id} className="flex items-center justify-between rounded-xl border bg-card p-4 cursor-pointer hover:bg-accent/50 transition-colors" onClick={() => openDetail(conv)}>
                <div className="flex items-center gap-3">
                  <MessageSquare className="h-5 w-5 text-primary" />
                  <div>
                    <p className="text-sm font-medium">{conv.title || conv.conversation_id}</p>
                    <p className="text-xs text-muted-foreground">
                      {conv.agent_name || "에이전트 미지정"} · {conv.message_count}개 메시지 · {conv.total_tokens?.toLocaleString()} 토큰
                    </p>
                  </div>
                </div>
                <span className="text-xs text-muted-foreground">{new Date(conv.created_at).toLocaleDateString("ko")}</span>
              </div>
            ))}
          </div>
        )}
        {total > 20 && (
          <div className="flex justify-center gap-2 pt-4">
            <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage(page - 1)}>이전</Button>
            <span className="flex items-center text-sm text-muted-foreground">{page} / {Math.ceil(total / 20)}</span>
            <Button variant="outline" size="sm" disabled={page >= Math.ceil(total / 20)} onClick={() => setPage(page + 1)}>다음</Button>
          </div>
        )}
      </div>

      <Dialog open={detailOpen} onOpenChange={setDetailOpen}>
        <DialogContent className="max-w-2xl max-h-[80vh]">
          <DialogHeader><DialogTitle>대화 상세</DialogTitle></DialogHeader>
          <div className="overflow-auto max-h-[60vh] space-y-3 pt-2">
            {messages.map((msg) => (
              <div key={msg.id} className={`flex gap-2 ${msg.role === "assistant" ? "" : "flex-row-reverse"}`}>
                <div className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full ${msg.role === "assistant" ? "bg-primary/10" : "bg-muted"}`}>
                  {msg.role === "assistant" ? <Bot className="h-4 w-4 text-primary" /> : <User className="h-4 w-4" />}
                </div>
                <div className={`max-w-[80%] rounded-xl px-3 py-2 text-sm ${msg.role === "assistant" ? "bg-muted" : "bg-primary text-white"}`}>
                  {msg.content}
                  {msg.token_count > 0 && <span className="block text-[10px] opacity-60 mt-1">{msg.token_count} tokens</span>}
                </div>
              </div>
            ))}
            {messages.length === 0 && <p className="text-center text-sm text-muted-foreground py-8">메시지가 없습니다</p>}
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
