import { useEffect, useState } from "react";
import { useAuthStore } from "../store/authStore";
import { useChatStore } from "../store/chatStore";
import { NewChatPanel } from "./NewChatPanel";

export function ChatList() {
  const chats = useChatStore((s) => s.chats);
  const messagesByChat = useChatStore((s) => s.messagesByChat);
  const activeChatId = useChatStore((s) => s.activeChatId);
  const setActiveChatId = useChatStore((s) => s.setActiveChatId);
  const loadChats = useChatStore((s) => s.loadChats);
  const me = useAuthStore((s) => s.me);
  const [search, setSearch] = useState("");
  const [tab, setTab] = useState<"all" | "people" | "groups" | "channels">("all");

  useEffect(() => {
    const timer = setTimeout(() => {
      void loadChats(search.trim() ? search : undefined);
    }, 250);
    return () => clearTimeout(timer);
  }, [search, loadChats]);

  const filteredChats = chats.filter((chat) => {
    if (tab === "people") {
      return chat.type === "private";
    }
    if (tab === "groups") {
      return chat.type === "group";
    }
    if (tab === "channels") {
      return chat.type === "channel";
    }
    return true;
  });

  const tabs: Array<{ id: "all" | "people" | "groups" | "channels"; label: string }> = [
    { id: "all", label: "All" },
    { id: "people", label: "Люди" },
    { id: "groups", label: "Groups" },
    { id: "channels", label: "Каналы" }
  ];

  return (
    <aside className="relative flex h-full w-full max-w-xs flex-col bg-slate-900/60">
      <div className="border-b border-slate-700/50 px-3 py-3">
        <div className="mb-2 flex items-center gap-2">
          <button className="rounded-lg bg-slate-700/70 px-2 py-2 text-xs">☰</button>
          <label className="block flex-1">
            <input
              className="w-full rounded-full border border-slate-700/80 bg-slate-800/80 px-3 py-2 text-sm outline-none placeholder:text-slate-400 focus:border-sky-500"
              placeholder="Search"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
            />
          </label>
          <div className="flex h-8 w-8 items-center justify-center rounded-full bg-sky-500/30 text-xs font-semibold uppercase text-sky-100">
            {(me?.username || "u").slice(0, 1)}
          </div>
        </div>
        <div className="flex items-center gap-3 overflow-x-auto pt-1 text-sm">
          {tabs.map((item) => (
            <button
              className={`whitespace-nowrap pb-1.5 ${tab === item.id ? "border-b-2 border-sky-400 font-semibold text-sky-300" : "text-slate-300/80"}`}
              key={item.id}
              onClick={() => setTab(item.id)}
            >
              {item.label}
            </button>
          ))}
        </div>
      </div>
      <div className="tg-scrollbar flex-1 overflow-auto">
        {filteredChats.map((chat) => (
          <button
            className={`block w-full border-b border-slate-800/60 px-4 py-3 text-left transition ${
              activeChatId === chat.id ? "bg-sky-500/20" : "hover:bg-slate-800/65"
            }`}
            key={chat.id}
            onClick={() => setActiveChatId(chat.id)}
          >
            <div className="flex items-start gap-3">
              <div className="mt-0.5 flex h-10 w-10 items-center justify-center rounded-full bg-sky-500/30 text-sm font-semibold uppercase text-sky-100">
                {(chat.title || chat.type).slice(0, 1)}
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center justify-between gap-2">
                  <p className="truncate text-sm font-semibold">{chat.title || `${chat.type} #${chat.id}`}</p>
                  <span className="shrink-0 text-[11px] text-slate-400">
                    {messagesByChat[chat.id]?.length ? "now" : ""}
                  </span>
                </div>
                <p className="truncate text-xs text-slate-400">{chat.type}</p>
              </div>
            </div>
          </button>
        ))}
      </div>
      <NewChatPanel />
    </aside>
  );
}
