import { CustomChannelHeader } from "@ui/components/CustomChannelHeader";
import { UserTablo } from "@xtablo/shared/types/tablos.types";
import { useEffect, useState } from "react";
import { Channel as StreamChannel } from "stream-chat";
import { Channel, MessageInput, MessageList, useChatContext, Window } from "stream-chat-react";
import ChatProvider from "../providers/ChatProvider";
import { LoadingSpinner } from "./LoadingSpinner";
import { TabloHeaderActions } from "./TabloHeaderActions";

interface TabloDiscussionSectionProps {
  tablo: UserTablo;
  isAdmin: boolean;
}

const TabloChat = ({ tablo }: { tablo: UserTablo }) => {
  const { client, setActiveChannel } = useChatContext();
  const [channel, setChannel] = useState<StreamChannel | null>(null);

  useEffect(() => {
    const initChannel = async () => {
      if (client && tablo.id) {
        const newChannel = client.channel("messaging", tablo.id);
        await newChannel.watch();
        setChannel(newChannel);
        setActiveChannel(newChannel);
      }
    };

    initChannel();
  }, [client, tablo.id, setActiveChannel]);

  if (!channel) {
    return (
      <div className="flex items-center justify-center h-96">
        <LoadingSpinner />
      </div>
    );
  }

  return (
    <Channel channel={channel}>
      <Window>
        <CustomChannelHeader tablos={[tablo]} showToggleButton={false} />
        <MessageList />
        <MessageInput />
      </Window>
    </Channel>
  );
};

export const TabloDiscussionSection = ({ tablo, isAdmin }: TabloDiscussionSectionProps) => {
  return (
    <div className="flex flex-col h-full">
      <div className="flex justify-between items-start mb-6">
        <div>
          <h1 className="text-3xl font-bold text-foreground">Discussion</h1>
          <p className="text-muted-foreground mt-1">Conversations liées à ce tablo</p>
        </div>
        <TabloHeaderActions tablo={tablo} isAdmin={isAdmin} />
      </div>

      <div className="flex-1 bg-card rounded-lg border border-border overflow-hidden min-h-0">
        <ChatProvider>
          <TabloChat tablo={tablo} />
        </ChatProvider>
      </div>
    </div>
  );
};
