"use client";

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

interface ThreadViewProps {
  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 || "";
}

export function ThreadView({ rootMessage, channelId, onClose }: ThreadViewProps) {
  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]);

  // 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);
    }
  };

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

  return (
    <div className="w-[340px] border-l border-gray-200 bg-white flex flex-col h-full">
      {/* Header */}
      <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200">
        <h3 className="font-bold text-sm text-gray-800">Thread</h3>
        <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-gray-100">
        <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()}
          </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 && 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()}
                </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 input */}
      <div className="border-t border-gray-200 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>
  );
}