"use client";

import { useEffect, useState, useRef, FormEvent } from "react";
import { getThread, sendThreadReply, Message, getAccessToken } from "@/lib/api";
import { connectSocket } from "@/lib/socket";
import { X, Send, MessageSquare } from "lucide-react";

interface ThreadPanelProps {
  rootMessage: Message;
  channelId: string;
  onClose: () => void;
}

function getMessageText(msg: Message): string {
  return msg.text || msg.content || "";
}

function getDisplayName(msg: Message): string {
  return (
    msg.user?.name ||
    msg.user?.display_name ||
    msg.user?.displayName ||
    msg.user?.email ||
    "Unknown"
  );
}

function getTimestamp(msg: Message): string {
  return msg.createdAt || msg.created_at || msg.ts || "";
}

function formatTime(iso: string): string {
  if (!iso) return "";
  try {
    const d = new Date(iso);
    return d.toLocaleString("en-US", {
      month: "short",
      day: "numeric",
      hour: "numeric",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

export function ThreadPanel({ rootMessage, channelId, onClose }: ThreadPanelProps) {
  const [replies, setReplies] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [content, setContent] = useState("");
  const [isSending, setIsSending] = useState(false);
  const [error, setError] = useState("");
  const bottomRef = useRef<HTMLDivElement>(null);

  // Load thread replies
  useEffect(() => {
    setLoading(true);
    setError("");
    getThread(rootMessage.id)
      .then((data) => {
        setReplies(Array.isArray(data) ? data : []);
      })
      .catch((err) => {
        console.error("Failed to load thread:", err);
        setError("Failed to load thread");
      })
      .finally(() => setLoading(false));
  }, [rootMessage.id]);

  // Listen for real-time thread replies via Socket.io
  useEffect(() => {
    const token = getAccessToken();
    if (!token) return;

    const socket = connectSocket(token);

    const onNewReply = (msg: Message) => {
      // Only add if it's a reply in this thread
      const msgThreadId = (msg as any).thread_root_id || (msg as any).threadRootId;
      if (msgThreadId === rootMessage.id) {
        setReplies((prev) => {
          if (prev.some((m) => m.id === msg.id)) return prev;
          return [...prev, msg];
        });
      }
    };

    socket.on("thread:new_reply", onNewReply);
    socket.on("message:new", onNewReply);

    return () => {
      socket.off("thread:new_reply", onNewReply);
      socket.off("message:new", onNewReply);
    };
  }, [rootMessage.id]);

  // Scroll to bottom when replies change
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [replies]);

  const handleReply = async (e?: FormEvent) => {
    e?.preventDefault();
    const trimmed = content.trim();
    if (!trimmed || isSending) return;

    setIsSending(true);
    setError("");
    try {
      const reply = await sendThreadReply(channelId, trimmed, rootMessage.id);
      setReplies((prev) => {
        if (prev.some((m) => m.id === reply.id)) return prev;
        return [...prev, reply];
      });
      setContent("");
    } catch (err: any) {
      const msg =
        err.response?.data?.error ||
        err.response?.data?.message ||
        err.message ||
        "Failed to send reply";
      setError(typeof msg === "string" ? msg : JSON.stringify(msg));
    } finally {
      setIsSending(false);
    }
  };

  return (
    <div className="w-[350px] border-l border-[#E1E1E1] bg-white flex flex-col h-full flex-shrink-0">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-[#E1E1E1]">
        <div className="flex items-center gap-2">
          <MessageSquare size={18} className="text-gray-500" />
          <h3 className="font-bold text-sm text-gray-800">Thread</h3>
        </div>
        <button
          onClick={onClose}
          className="p-1 rounded-md hover:bg-gray-100 text-gray-500"
          title="Close thread"
        >
          <X size={18} />
        </button>
      </div>

      {/* Root message */}
      <div className="px-4 py-3 border-b border-[#E1E1E1] bg-gray-50">
        <div className="flex gap-2">
          <div className="w-8 h-8 rounded-md bg-slack-purple text-white flex items-center justify-center text-xs font-bold flex-shrink-0">
            {getDisplayName(rootMessage)[0]?.toUpperCase() || "U"}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-baseline gap-2">
              <span className="font-bold text-sm text-gray-900">
                {getDisplayName(rootMessage)}
              </span>
              <span className="text-xs text-gray-400">
                {formatTime(getTimestamp(rootMessage))}
              </span>
            </div>
            <p className="text-sm text-gray-800 whitespace-pre-wrap break-words mt-0.5">
              {getMessageText(rootMessage)}
            </p>
          </div>
        </div>
      </div>

      {/* Replies */}
      <div className="flex-1 overflow-y-auto px-4 py-2">
        {loading && (
          <div className="text-sm text-gray-400 animate-pulse py-4 text-center">
            Loading replies...
          </div>
        )}
        {error && (
          <div className="text-sm text-red-500 py-4 text-center">{error}</div>
        )}
        {!loading && !error && replies.length === 0 && (
          <div className="text-sm text-gray-400 py-4 text-center">
            No replies yet. Start the conversation!
          </div>
        )}
        {!loading && replies.length > 0 && (
          <ul className="space-y-1">
            {replies.map((msg) => (
              <li
                key={msg.id}
                className="flex gap-2 py-1.5 hover:bg-gray-50 rounded px-2"
              >
                <div className="w-8 h-8 rounded-md bg-slack-purple text-white flex items-center justify-center text-xs font-bold flex-shrink-0">
                  {getDisplayName(msg)[0]?.toUpperCase() || "U"}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-baseline gap-2">
                    <span className="font-bold text-sm text-gray-900">
                      {getDisplayName(msg)}
                    </span>
                    <span className="text-xs text-gray-400">
                      {formatTime(getTimestamp(msg))}
                    </span>
                  </div>
                  <p className="text-sm text-gray-800 whitespace-pre-wrap break-words mt-0.5">
                    {getMessageText(msg)}
                  </p>
                </div>
              </li>
            ))}
          </ul>
        )}
        <div ref={bottomRef} />
      </div>

      {/* Reply count */}
      <div className="px-4 py-1.5 border-t border-[#E1E1E1] text-xs text-gray-400">
        {replies.length} {replies.length === 1 ? "reply" : "replies"}
      </div>

      {/* Reply input */}
      <div className="px-4 py-3">
        <form onSubmit={handleReply} className="flex items-end gap-2">
          <textarea
            value={content}
            onChange={(e) => setContent(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === "Enter" && !e.shiftKey) {
                e.preventDefault();
                handleReply();
              }
            }}
            placeholder="Reply in thread..."
            rows={1}
            className="flex-1 resize-none px-3 py-2 rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-slack-purple focus:border-transparent text-sm min-h-[36px] max-h-[100px]"
            disabled={isSending}
          />
          <button
            type="submit"
            disabled={isSending || !content.trim()}
            className="p-2 rounded-md bg-slack-purple text-white hover:bg-slack-darkpurple disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
            title="Send reply"
          >
            <Send size={18} />
          </button>
        </form>
        <p className="mt-1 text-xs text-gray-400">Press Enter to send</p>
      </div>
    </div>
  );
}