"use client";

import { useState, useEffect } from "react";
import { X, MessageSquare, User, Bot } from "lucide-react";
import type { Memory } from "@/lib/types";

interface ChatMessage {
  id: number;
  role: "user" | "assistant";
  content: string;
  timestamp: string;
}

function parseComment(comment: any): ChatMessage | null {
  const body: string = comment.body || "";
  const lines = body.split("\n");

  // First line should be "role: user" or "role: assistant"
  const roleLine = lines[0]?.trim();
  const roleMatch = roleLine?.match(/^role:\s*(user|assistant)/i);
  if (!roleMatch) return null;

  const role = roleMatch[1].toLowerCase() as "user" | "assistant";

  // Rest is the message content — skip empty lines and metadata lines after role
  const contentLines: string[] = [];
  let started = false;
  for (let i = 1; i < lines.length; i++) {
    const line = lines[i];
    // Skip metadata lines like [message_id: ...] or user_id: ...
    if (!started && (line.trim() === "" || line.trim().startsWith("[message_id:") || /^[a-z_]+:/.test(line.trim()))) {
      // But if it looks like actual content (long enough, starts with letter), include it
      if (line.trim().length > 50 && !line.trim().startsWith("[")) {
        started = true;
        contentLines.push(line);
      }
      continue;
    }
    started = true;
    contentLines.push(line);
  }

  return {
    id: comment.id,
    role,
    content: contentLines.join("\n").trim(),
    timestamp: comment.created_at || "",
  };
}

function formatTime(dateStr: string): string {
  if (!dateStr) return "";
  const d = new Date(dateStr);
  return d.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" });
}

interface ConversationViewerProps {
  conversation: Memory;
  vaultFullName: string;
  onClose: () => void;
}

export function ConversationViewer({ conversation, vaultFullName, onClose }: ConversationViewerProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;

    async function load() {
      try {
        const [owner, repo] = vaultFullName.split("/");
        const res = await fetch(`/api/proxy/repos/${owner}/${repo}/issues/${conversation.id}/comments`, {
          headers: {
            "X-KnowHub-Server": (() => {
              try {
                const auth = JSON.parse(localStorage.getItem("knowhub_auth") || "{}");
                return auth.serverUrl || "";
              } catch { return ""; }
            })(),
            "X-KnowHub-Token": (() => {
              try {
                const auth = JSON.parse(localStorage.getItem("knowhub_auth") || "{}");
                return auth.token || "";
              } catch { return ""; }
            })(),
          },
        });
        if (!res.ok) return;
        const comments = await res.json();
        if (!cancelled && Array.isArray(comments)) {
          const parsed = comments.map(parseComment).filter((m): m is ChatMessage => m !== null);
          setMessages(parsed);
        }
      } catch (err) {
        console.error("Failed to load conversation:", err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    load();
    return () => { cancelled = true; };
  }, [conversation.id, vaultFullName]);

  return (
    <div className="fixed inset-0 z-50 flex">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />

      {/* Panel */}
      <div className="relative ml-auto w-full max-w-2xl h-full bg-background border-l border-border flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-5 py-4 border-b border-border-light">
          <div className="flex items-center gap-3">
            <MessageSquare size={18} className="text-accent" />
            <div>
              <h2 className="text-sm font-semibold text-text-primary">{conversation.title}</h2>
              <p className="text-xs text-text-muted">{conversation.content || `${messages.length} messages`}</p>
            </div>
          </div>
          <button onClick={onClose} className="p-1.5 rounded-md hover:bg-surface text-text-secondary hover:text-text-primary">
            <X size={16} />
          </button>
        </div>

        {/* Messages */}
        <div className="flex-1 overflow-y-auto px-5 py-4 space-y-4">
          {loading ? (
            <p className="text-sm text-text-secondary text-center py-8">Loading conversation...</p>
          ) : messages.length === 0 ? (
            <p className="text-sm text-text-secondary text-center py-8">No messages in this conversation.</p>
          ) : (
            messages.map((msg) => (
              <div key={msg.id} className={`flex gap-3 ${msg.role === "user" ? "" : ""}`}>
                {/* Avatar */}
                <div className={`w-7 h-7 rounded-full flex items-center justify-center shrink-0 mt-0.5 ${
                  msg.role === "user"
                    ? "bg-accent/20 text-accent"
                    : "bg-skill/20 text-skill"
                }`}>
                  {msg.role === "user" ? <User size={14} /> : <Bot size={14} />}
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-1">
                    <span className="text-xs font-medium text-text-primary">
                      {msg.role === "user" ? "User" : "Assistant"}
                    </span>
                    <span className="text-[11px] text-text-muted">{formatTime(msg.timestamp)}</span>
                  </div>
                  <div className={`text-sm leading-relaxed rounded-lg px-3 py-2 ${
                    msg.role === "user"
                      ? "bg-surface text-text-primary"
                      : "bg-surface-elevated text-text-secondary"
                  }`}>
                    <p className="whitespace-pre-wrap">{msg.content || "(empty message)"}</p>
                  </div>
                </div>
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
