import { useCallback, useEffect, useRef, useState } from "react";
import { useParams } from "react-router";
import { useQueryClient } from "@tanstack/react-query";
import { api } from "@/client";
import { MessageSquare } from "lucide-react";
import { useChannelState } from "./use-channel-state";
import { ChannelHeader } from "./channel-header";
import { ChannelThreadPanel } from "./channel-thread-panel";
import RoomSettingsDialog from "./room-settings-dialog";
import MessageView from "./message-view";
import ArticleFeed from "./article-feed";
import ArticleComposer from "./article-composer";
import { useArticleDraft } from "./use-article-draft";

export default function ChannelPage() {
  const { roomId } = useParams();
  const { state, actions } = useChannelState(roomId);
  const queryClient = useQueryClient();
  const [showThreads, setShowThreads] = useState(false);
  const [activeThreadId, setActiveThreadId] = useState<string | null>(null);
  const [activeThreadSeq, setActiveThreadSeq] = useState<number>(0);
  const [showRoomSettings, setShowRoomSettings] = useState(false);

  // Global composer state
  const [showComposer, setShowComposer] = useState(false);
  const [composerChannel, setComposerChannel] = useState<string | null>(null);
  const { draft, persist, initDraft, clearDraft } = useArticleDraft(composerChannel ?? undefined);

  const openComposer = useCallback((channel: string) => {
    setComposerChannel(channel);
    const existing = initDraft(channel);
    if (!existing || (!existing.title && !existing.content)) {
      // fresh draft
    }
    setShowComposer(true);
  }, [initDraft]);

  const closeComposer = useCallback(() => {
    setShowComposer(false);
  }, []);

  const handleArticleCreated = useCallback(() => {
    setShowComposer(false);
    setComposerChannel(null);
  }, []);

  // Reset thread view & room settings when switching rooms
  const prevRoomId = useRef(roomId);
  useEffect(() => {
    if (prevRoomId.current !== roomId) {
      prevRoomId.current = roomId;
      setShowThreads(false);
      setActiveThreadId(null);
      setActiveThreadSeq(0);
      setShowRoomSettings(false);
    }
  }, [roomId]);

  const handleStartThread = useCallback(
    async (_messageId: string, seq: number) => {
      if (!roomId) return;
      try {
        const res = await api.post(`/api/v1/ws/rooms/${roomId}/threads`, {
          parent: seq,
        });
        const payload = res.data as Record<string, unknown> | undefined;
        const eventData = payload?.data as Record<string, unknown> | undefined;
        const threadId = eventData?.id as string | undefined;
        if (threadId) {
          setActiveThreadId(threadId);
          setShowThreads(true);
        }
      } catch {
        // ignore – websocket will sync threads
      }
    },
    [roomId],
  );

  const handleViewThread = useCallback((threadId: string, seq: number) => {
    setActiveThreadId(threadId);
    setActiveThreadSeq(seq);
    setShowThreads(true);
  }, []);

  const closeThreadPanel = useCallback(() => {
    setShowThreads(false);
    setTimeout(() => {
      setActiveThreadId(null);
      setActiveThreadSeq(0);
    }, 320);
  }, []);

  return (
    <div className="relative flex h-full min-w-0 flex-col overflow-hidden">
      {state.currentRoom ? (
        <ChannelHeader
          memberCount={undefined}
          onToggleSettings={() => setShowRoomSettings(true)}
          room={state.currentRoom}
        />
      ) : (
        <div className="flex h-[52px] shrink-0 items-center border-b border-border/40 px-4">
          {state.loadingRooms ? (
            <span className="text-sm text-muted-foreground/40">Loading…</span>
          ) : (
            <div className="flex items-center gap-2 text-muted-foreground/40">
              <MessageSquare className="size-4" />
              <span className="text-sm">Select a channel to start chatting</span>
            </div>
          )}
        </div>
      )}

      {state.currentRoom?.room_type === "article" && roomId ? (
        <ArticleFeed
          currentUserId={state.currentUserId}
          roomId={roomId}
          roomName={state.currentRoom.name}
          onCompose={() => openComposer(roomId)}
        />
      ) : (
        <>
          <MessageView
            currentUserId={state.currentUserId}
            hasMore={state.hasMore}
            loading={state.loadingMessages}
            messages={state.messages}
            onDelete={actions.handleDeleteMessage}
            onEdit={actions.handleEditMessage}
            onLoadMore={actions.handleLoadMore}
            onPinToggle={actions.handlePinToggle}
            onReactionToggle={actions.handleReactionToggle}
            onSend={actions.handleSend}
            onStartThread={handleStartThread}
            onViewThread={handleViewThread}
            onTyping={actions.handleTyping}
            roomId={roomId ?? ""}
            roomName={state.currentRoom?.name ?? ""}
            streamingMessages={state.streamingMessages}
            threads={state.threads}
            typingText={state.typingText}
          />

          {roomId && (
            <ChannelThreadPanel
              initialSeq={activeThreadSeq}
              onClose={closeThreadPanel}
              open={showThreads}
              roomId={roomId}
              selectedThreadId={activeThreadId}
              threads={state.threads}
            />
          )}
        </>
      )}

      {roomId && state.currentRoom && (
        <RoomSettingsDialog
          categories={state.categories}
          categoryId={state.currentRoom.category ?? null}
          isPrivate={state.currentRoom.is_private}
          aiEnabled={state.currentRoom.ai_enabled}
          onDeleted={() => queryClient.invalidateQueries({queryKey: ["channel", "rooms"]})}
          onOpenChange={setShowRoomSettings}
          onUpdated={() => queryClient.invalidateQueries({queryKey: ["channel", "rooms"]})}
          open={showRoomSettings}
          roomId={roomId}
          roomName={state.currentRoom.name}
          topic={state.currentRoom.topic}
        />
      )}

      {/* Global article composer */}
      {showComposer && composerChannel && (
        <ArticleComposer
          channel={composerChannel}
          draft={draft}
          onClearDraft={clearDraft}
          onClose={closeComposer}
          onCreated={handleArticleCreated}
          onDraftChange={persist}
        />
      )}
    </div>
  );
}
