import { useState, useEffect, useRef } from "react";
import ThreadPane from "./thread-pane";
import type { Thread } from "./thread-sidebar";

type Props = {
  open: boolean;
  threads: Thread[];
  roomId: string;
  selectedThreadId?: string | null;
  initialSeq?: number;
  onClose: () => void;
};

export function ChannelThreadPanel({
  open,
  threads,
  roomId,
  selectedThreadId,
  initialSeq = 0,
  onClose,
}: Props) {
  const [selectedThread, setSelectedThread] = useState<Thread | null>(null);
  const prevOpen = useRef(false);
  const prevRoomId = useRef(roomId);

  // Reset selectedThread when room changes to avoid stale data leak
  useEffect(() => {
    if (prevRoomId.current !== roomId) {
      prevRoomId.current = roomId;
      setSelectedThread(null);
    }
    // Also reset when open transitions from true to false (after room switch reset)
    if (!open && prevOpen.current) {
      setSelectedThread(null);
    }
    prevOpen.current = open;
  }, [open, roomId]);

  // Auto-select the thread when selectedThreadId is provided
  useEffect(() => {
    if (!selectedThreadId) {
      return;
    }
    if (threads.length === 0) {
      // Threads haven't loaded yet for this room; don't eagerly create a placeholder
      return;
    }
    const thread = threads.find((t) => t.id === selectedThreadId);
    if (thread) {
      // eslint-disable-next-line react-hooks/set-state-in-effect -- state sync from prop, pre-existing pattern
      setSelectedThread(thread);
    } else if (initialSeq > 0) {
      setSelectedThread({
        id: selectedThreadId,
        room: roomId,
        seq: 0,
        parent_seq: initialSeq,
        title: "",
        created_by: { id: "", display_name: "", username: "" },
        archived: false,
        locked: false,
        last_message_at: null,
        created_at: new Date().toISOString(),
      });
    }
  }, [selectedThreadId, threads, roomId, initialSeq]);

  if (!open) return null;

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

      {/* Thread Pane (detail) — slides from right */}
      <div
        className={`
          absolute inset-y-0 right-0 z-40 w-[min(460px,88vw)] border-l border-border/30 bg-card shadow-2xl
          transition-[transform,opacity] duration-300 ease-out
          ${selectedThread ? "translate-x-0 opacity-100" : "translate-x-full opacity-0"}
        `}
      >
        {selectedThread && (
          <ThreadPane
            onClose={() => setSelectedThread(null)}
            roomId={roomId}
            thread={selectedThread}
          />
        )}
      </div>
    </>
  );
}
