import { useCallback, useEffect, useRef, useState } from "react";
import {
  Loader2,
  MessageSquarePlus,
  ArrowLeft,
  Send,
} from "lucide-react";
import { api } from "@/client";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { workspaceColor, workspaceInitial } from "@/components/shell/shared";
import type { MessageNewService } from "@/socket";
import type { Thread } from "./thread-sidebar";

type Props = {
  thread: Thread;
  roomId: string;
  onClose: () => void;
};

function formatTime(iso: string) {
  const d = new Date(iso);
  return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

export default function ThreadPane({ thread, roomId, onClose }: Props) {
  const [messages, setMessages] = useState<MessageNewService[]>([]);
  const [loading, setLoading] = useState(true);
  const [reply, setReply] = useState("");
  const [sending, setSending] = useState(false);
  const bottomRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    let cancelled = false;
    api
      .get<{ data?: { messages?: MessageNewService[] } }>(
        `/api/v1/ws/rooms/${roomId}/messages/around`,
        { params: { seq: thread.seq, limit: 30 } },
      )
      .then((res) => {
        if (!cancelled) setMessages(res.data?.data?.messages ?? []);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [thread.seq, roomId]);

  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages.length]);

  const handleReply = useCallback(async () => {
    const trimmed = reply.trim();
    if (!trimmed || sending) return;
    setSending(true);
    try {
      await api.post(`/api/v1/ws/rooms/${roomId}/messages`, {
        content: trimmed,
        content_type: "text",
        thread: thread.id,
      });
      setReply("");
    } catch {
      // ignore
    } finally {
      setSending(false);
    }
  }, [reply, sending, roomId, thread.id]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        handleReply();
      }
      if (e.key === "Escape") setReply("");
    },
    [handleReply],
  );

  // Group messages by sender
  const grouped = (() => {
    const groups: {
      senderId: string;
      name: string;
      avatar_url?: string;
      colorClass: string;
      initial: string;
      messages: { msg: MessageNewService; showHeader: boolean }[];
    }[] = [];

    for (let i = 0; i < messages.length; i++) {
      const msg = messages[i];
      const prev = i > 0 ? messages[i - 1] : undefined;
      const isFirst =
        !prev ||
        prev.sender.id !== msg.sender.id ||
        new Date(msg.send_at).getTime() -
          new Date(prev.send_at).getTime() >
          5 * 60 * 1000;

      const name = msg.sender.display_name || msg.sender.username || "User";
      const colorClass = workspaceColor(name);
      const initial = workspaceInitial(name);

      if (isFirst) {
        groups.push({
          senderId: msg.sender.id,
          name,
          avatar_url: msg.sender.avatar_url,
          colorClass,
          initial,
          messages: [{ msg, showHeader: true }],
        });
      } else {
        groups[groups.length - 1].messages.push({ msg, showHeader: false });
      }
    }
    return groups;
  })();

  return (
    <aside className="flex h-full w-full flex-col bg-card">
      {/* Header */}
      <div className="flex h-[52px] shrink-0 items-center gap-3 border-b border-border/40 px-4">
        <Button
          className="size-8 shrink-0 cursor-pointer rounded-lg text-muted-foreground/40 hover:bg-accent/50 hover:text-foreground"
          onClick={onClose}
          size="icon"
          variant="ghost"
        >
          <ArrowLeft className="size-4" />
        </Button>
        <div className="min-w-0 flex-1">
          <h3 className="truncate text-sm font-semibold text-foreground">
            {thread.title || `Thread #${thread.seq}`}
          </h3>
          <div className="flex items-center gap-1.5">
            <span className="text-[11px] text-muted-foreground/40">
              {thread.archived
                ? "Archived"
                : thread.locked
                  ? "Resolved"
                  : "Active"}
            </span>
            <span className="text-muted-foreground/20">·</span>
            <span className="text-[11px] text-muted-foreground/30">
              {messages.length} message{messages.length !== 1 ? "s" : ""}
            </span>
          </div>
        </div>
      </div>

      {/* Messages */}
      <div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
        {loading && (
          <div className="flex justify-center py-20">
            <Loader2 className="size-5 animate-spin text-muted-foreground/25" />
          </div>
        )}

        {!loading && messages.length === 0 && (
          <div className="flex flex-col items-center justify-center py-20">
            <div className="grid size-12 place-items-center rounded-2xl bg-muted/20 ring-1 ring-border/20">
              <MessageSquarePlus className="size-5 text-muted-foreground/20" />
            </div>
            <p className="mt-3 text-xs font-medium text-muted-foreground/40">
              No messages yet
            </p>
            <p className="mt-1 text-[11px] text-muted-foreground/30">
              Be the first to reply
            </p>
          </div>
        )}

        <div className="py-2">
          {grouped.map((group) => (
            <div
              className="group flex gap-2.5 px-4 py-1 transition-colors duration-100 hover:bg-accent/[0.02]"
              key={group.messages[0].msg.id}
            >
              <div className="mt-0.5 shrink-0">
                <div
                  className={cn(
                    "grid size-8 place-items-center rounded-full bg-gradient-to-br text-xs font-semibold text-white shadow-sm",
                    group.colorClass,
                  )}
                >
                  {group.avatar_url ? (
                    <img
                      alt={group.name}
                      className="size-full rounded-full object-cover"
                      src={group.avatar_url}
                    />
                  ) : (
                    group.initial
                  )}
                </div>
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-baseline gap-2">
                  <span className="text-[13px] font-semibold text-foreground">
                    {group.name}
                  </span>
                  <span className="text-[10px] text-muted-foreground/35">
                    {formatTime(group.messages[0].msg.send_at)}
                  </span>
                </div>
                {group.messages.map(({ msg }) => (
                  <p
                    className="whitespace-pre-wrap break-words text-[13px] leading-relaxed text-foreground/85"
                    key={msg.id}
                  >
                    {msg.content}
                  </p>
                ))}
              </div>
            </div>
          ))}
          <div ref={bottomRef} />
        </div>
      </div>

      {/* Reply composer */}
      <div className="shrink-0 border-t border-border/40 p-3">
        <div
          className={cn(
            "flex items-end gap-2 rounded-xl border bg-card px-3 py-2 transition-[background-color,border-color,color,opacity,box-shadow,transform] duration-200",
            "focus-within:border-primary/20 focus-within:ring-1 focus-within:ring-primary/[0.06]",
            "border-border/50",
          )}
        >
          <textarea
            aria-label="Reply in thread"
            className="min-h-[36px] max-h-32 flex-1 resize-none border-0 bg-transparent text-sm leading-relaxed text-foreground placeholder:text-muted-foreground/30 focus-visible:ring-0 focus-visible:outline-none"
            disabled={thread.archived || thread.locked}
            onChange={(e) => setReply(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder={
              thread.archived || thread.locked
                ? "Thread is closed"
                : "Reply in thread…"
            }
            ref={textareaRef}
            rows={1}
            value={reply}
          />
          <Button
            className="shrink-0 cursor-pointer rounded-lg"
            disabled={
              !reply.trim() || sending || thread.archived || thread.locked
            }
            onClick={handleReply}
            size="sm"
          >
            {sending ? (
              <Loader2 className="size-4 animate-spin" />
            ) : (
              <Send className="size-[15px]" />
            )}
          </Button>
        </div>
        <p className="mt-1.5 px-1 text-[10px] text-muted-foreground/25">
          Press Enter to send, Shift+Enter for new line
        </p>
      </div>
    </aside>
  );
}
