import { useCallback, useEffect, useRef, useState } from "react";
import type { Channel } from "@/types/Channel";
import type { Message } from "@/types/Message";
import { getChannels, getMessages } from "@/api";
import { ChannelSidebar } from "@/components/ChannelSidebar";
import { MessageItem } from "@/components/MessageItem";
import { ComposeBox } from "@/components/ComposeBox";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import { Button } from "@/components/ui/button";

export default function App() {
  const [channels, setChannels] = useState<Channel[]>([]);
  const [activeChannelId, setActiveChannelId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [replyTo, setReplyTo] = useState<string | null>(null);
  const [sheetOpen, setSheetOpen] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const prevMsgCountRef = useRef(0);
  const activeChannelRef = useRef(activeChannelId);

  activeChannelRef.current = activeChannelId;

  const loadChannels = useCallback(async () => {
    const chs = await getChannels();
    setChannels(chs);
    setActiveChannelId((prev) => (prev ? prev : chs[0]?.id ?? null));
  }, []);

  const loadMessages = useCallback(async () => {
    const channelId = activeChannelRef.current;
    if (!channelId) return;
    try {
      const msgs = await getMessages(channelId);
      if (activeChannelRef.current === channelId) {
        setMessages(msgs);
      }
    } catch {
      // Silently ignore fetch errors during polling
    }
  }, []);

  useEffect(() => { loadChannels(); }, [loadChannels]);

  useEffect(() => {
    setMessages([]);
    setReplyTo(null);
    prevMsgCountRef.current = 0;
    loadMessages();
  }, [activeChannelId, loadMessages]);

  useEffect(() => {
    if (messages.length > prevMsgCountRef.current && scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
    prevMsgCountRef.current = messages.length;
  }, [messages]);

  useEffect(() => {
    const interval = setInterval(loadMessages, 3000);
    return () => clearInterval(interval);
  }, [loadMessages]);

  const messagesById = new Map(messages.map((m) => [m.id, m]));
  const activeChannel = channels.find((c) => c.id === activeChannelId);

  const sidebar = (
    <ChannelSidebar
      channels={channels}
      activeId={activeChannelId}
      onSelect={(id) => {
        setActiveChannelId(id);
        setSheetOpen(false);
      }}
      onChannelCreated={loadChannels}
    />
  );

  return (
    <div className="flex h-full">
      {/* Desktop sidebar */}
      <div className="hidden md:block">
        {sidebar}
      </div>

      <div className="flex-1 flex flex-col min-w-0">
        {/* Channel header */}
        <div className="px-3 py-2 md:px-4 border-b border-border flex items-center gap-2">
          {/* Mobile: Sheet trigger */}
          <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
            <SheetTrigger asChild>
              <Button variant="ghost" size="sm" className="md:hidden p-1 h-8 w-8 text-muted-foreground">
                =
              </Button>
            </SheetTrigger>
            <SheetContent side="left" className="p-0 w-64 bg-background">
              {sidebar}
            </SheetContent>
          </Sheet>

          {activeChannel ? (
            <>
              <span className="text-muted-foreground">#</span>
              <span className="font-bold text-sm">{activeChannel.name}</span>
              {activeChannel.description && (
                <span className="text-xs text-muted-foreground ml-2 hidden md:inline">
                  {activeChannel.description}
                </span>
              )}
              <span className="ml-auto text-xs text-muted-foreground tabular-nums">
                {messages.length} msg
              </span>
            </>
          ) : (
            <span className="text-muted-foreground text-xs">select a channel</span>
          )}
        </div>

        {/* Messages */}
        <div ref={scrollRef} className="flex-1 overflow-y-auto">
          {messages.length === 0 && activeChannelId && (
            <div className="flex items-center justify-center h-full text-muted-foreground text-xs">
              no messages yet
            </div>
          )}
          {messages.map((msg) => (
            <MessageItem
              key={msg.id}
              message={msg}
              replyTarget={msg.reply_to ? messagesById.get(msg.reply_to) : undefined}
              onReply={setReplyTo}
            />
          ))}
        </div>

        {activeChannelId && (
          <ComposeBox
            key={activeChannelId}
            channelId={activeChannelId}
            replyTo={replyTo}
            onClearReply={() => setReplyTo(null)}
            onMessageSent={loadMessages}
          />
        )}
      </div>
    </div>
  );
}
