"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { getChannels, Channel, Message } from "@/lib/api";
import { ChannelList } from "@/components/chat/ChannelList";
import { DMList } from "@/components/chat/DMList";
import { MessageList } from "@/components/chat/MessageList";
import { MessageInput } from "@/components/chat/MessageInput";
import { ChatHeader } from "@/components/chat/ChatHeader";
import { CreateChannelModal } from "@/components/chat/CreateChannelModal";
import { SearchBar } from "@/components/chat/SearchBar";
import { ThreadPanel } from "@/components/chat/ThreadPanel";
import { TypingIndicator } from "@/components/chat/TypingIndicator";
import { MessageSquare, LogOut, Hash, Settings, Bookmark } from "lucide-react";

export default function ChatPage() {
  const { user, isAuthenticated, loading, logout } = useAuth();
  const router = useRouter();
  const [channels, setChannels] = useState<Channel[]>([]);
  const [selectedChannel, setSelectedChannel] = useState<Channel | null>(null);
  const [loadingChannels, setLoadingChannels] = useState(true);
  const [refreshKey, setRefreshKey] = useState(0);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [threadMessage, setThreadMessage] = useState<Message | null>(null);

  useEffect(() => {
    if (!loading && !isAuthenticated) {
      router.replace("/login");
    }
  }, [loading, isAuthenticated, router]);

  const loadChannels = () => {
    setLoadingChannels(true);
    getChannels()
      .then((data) => {
        setChannels(data);
        if (data.length > 0 && !selectedChannel) {
          setSelectedChannel(data[0]);
        }
      })
      .catch((err) => {
        console.error("Failed to load channels:", err);
      })
      .finally(() => setLoadingChannels(false));
  };

  useEffect(() => {
    if (!isAuthenticated) return;
    loadChannels();
  }, [isAuthenticated]); // eslint-disable-line react-hooks/exhaustive-deps

  if (loading || (!isAuthenticated && !loading)) {
    return (
      <div className="flex h-screen items-center justify-center bg-slack-darkpurple">
        <div className="text-white text-lg animate-pulse">Loading ChatApp...</div>
      </div>
    );
  }

  const handleChannelSelect = (ch: Channel) => {
    setSelectedChannel(ch);
    setThreadMessage(null);
    setRefreshKey((k) => k + 1);
  };

  const handleMessageSent = () => {
    setRefreshKey((k) => k + 1);
  };

  const handleChannelCreated = (channel: Channel) => {
    setChannels((prev) => [...prev, channel]);
    setSelectedChannel(channel);
    setRefreshKey((k) => k + 1);
  };

  const handleReply = (msg: Message) => {
    setThreadMessage(msg);
  };

  const handleLogout = () => {
    logout();
  };

  return (
    <div className="flex h-screen bg-white">
      {/* Far left: workspace sidebar */}
      <div className="w-[60px] bg-slack-purple flex flex-col items-center py-4 gap-3">
        <div className="w-10 h-10 rounded-md bg-white text-slack-purple flex items-center justify-center font-bold text-lg">
          CA
        </div>
        <button
          onClick={() => router.push("/chat/saved")}
          className="w-10 h-10 rounded-md hover:bg-slack-lightpurple flex items-center justify-center text-white"
          title="Saved Items"
        >
          <Bookmark size={20} />
        </button>
        <button
          onClick={() => router.push("/settings")}
          className="w-10 h-10 rounded-md hover:bg-slack-lightpurple flex items-center justify-center text-white"
          title="Settings"
        >
          <Settings size={20} />
        </button>
        <button
          onClick={handleLogout}
          className="mt-auto w-10 h-10 rounded-md hover:bg-slack-lightpurple flex items-center justify-center text-white"
          title="Sign out"
        >
          <LogOut size={20} />
        </button>
      </div>

      {/* Channel list sidebar */}
      <div className="w-[240px] bg-slack-aubergine text-white flex flex-col">
        <div className="px-4 py-3 border-b border-white/10">
          <h2 className="font-bold text-sm">ChatApp Workspace</h2>
          <p className="text-xs text-white/60 mt-0.5">{user?.name || user?.email}</p>
        </div>
        <div className="flex-1 overflow-y-auto scrollbar-dark">
          {loadingChannels ? (
            <div className="px-4 py-3 text-sm text-white/60 animate-pulse">Loading channels...</div>
          ) : (
            <>
              <ChannelList
                channels={channels}
                selectedId={selectedChannel?.id}
                onSelect={handleChannelSelect}
                onCreateChannel={() => setShowCreateModal(true)}
              />
              <DMList onSelect={() => {}} />
            </>
          )}
        </div>
      </div>

      {/* Main chat area */}
      <div className="flex-1 flex flex-col min-w-0">
        {selectedChannel ? (
          <>
            {/* Header with search */}
            <div className="border-b border-gray-200">
              <ChatHeader channel={selectedChannel} />
              <div className="px-4 pb-2">
                <SearchBar />
              </div>
            </div>

            {/* Messages + Thread side-by-side */}
            <div className="flex-1 flex overflow-hidden">
              <div className="flex-1 overflow-hidden">
                <MessageList
                  key={refreshKey}
                  channelId={selectedChannel.id}
                  onReply={handleReply}
                />
              </div>

              {/* Thread panel */}
              {threadMessage && (
                <ThreadPanel
                  rootMessage={threadMessage}
                  channelId={selectedChannel.id}
                  onClose={() => setThreadMessage(null)}
                />
              )}
            </div>

            {/* Typing indicator + Message input */}
            <div>
              <TypingIndicator channelId={selectedChannel.id} currentUserId={user?.id} />
              <MessageInput
                channelId={selectedChannel.id}
                onSend={handleMessageSent}
              />
            </div>
          </>
        ) : (
          <div className="flex-1 flex items-center justify-center text-gray-400 flex-col gap-3">
            <MessageSquare size={48} />
            <p>Select a channel to start chatting</p>
          </div>
        )}
      </div>

      {/* Right sidebar: channel info (hidden when thread is open) */}
      {selectedChannel && !threadMessage && (
        <div className="w-[260px] bg-gray-50 border-l border-gray-200 p-4 hidden lg:block">
          <div className="flex items-center gap-2 mb-4">
            <Hash size={20} className="text-gray-400" />
            <h3 className="font-bold text-gray-800">
              {selectedChannel.name}
            </h3>
          </div>
          {selectedChannel.description ? (
            <p className="text-sm text-gray-600 mb-4">{selectedChannel.description}</p>
          ) : (
            <p className="text-sm text-gray-400 mb-4">
              This is the beginning of the #{selectedChannel.name} channel.
            </p>
          )}
          <div className="mt-6 pt-4 border-t border-gray-200">
            <h4 className="text-xs font-semibold text-gray-500 uppercase mb-2">Members</h4>
            <div className="flex items-center gap-2 text-sm text-gray-700">
              <div className="w-8 h-8 rounded-full bg-slack-purple text-white flex items-center justify-center text-xs font-bold">
                {(user?.name || user?.email || "U")[0].toUpperCase()}
              </div>
              <span>{user?.name || user?.email}</span>
            </div>
          </div>
        </div>
      )}

      {/* Create Channel Modal */}
      <CreateChannelModal
        open={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onCreated={handleChannelCreated}
      />
    </div>
  );
}