"use client";

import { usePathname } from "next/navigation";
import { Icon } from "@/components/ui/Icon";
import { Avatar } from "@/components/ui/Avatar";
import { NewChannelDialog } from "./NewChannelDialog";
import { usePresence } from "@/lib/ui/usePresence";
import type { ChannelListItem } from "@/lib/chat/queries";
import type { PresenceInfo } from "@/lib/presence";

type UserOption = { id: string; name: string };

const TYPE_ICON: Record<string, string> = {
  TEAM: "users",
  PROJECT: "projects",
  GROUP: "hash",
  DIRECT: "user",
};

// Alle Kategorie-Punkte einheitlich in Markenblau.
const DOT_COLOR = "#9ed7ff";
const GROUP_ORDER: { key: string; label: string }[] = [
  { key: "TEAM", label: "Teamkanäle" },
  { key: "PROJECT", label: "Projektkanäle" },
  { key: "GROUP", label: "Gruppen" },
  { key: "DIRECT", label: "Direktnachrichten" },
];

export function ChannelSidebar({
  channels,
  users,
  initialPresence,
  canCreate,
}: {
  channels: ChannelListItem[];
  users: UserOption[];
  initialPresence: Record<string, PresenceInfo>;
  canCreate: boolean;
}) {
  const pathname = usePathname();
  const dmIds = channels
    .map((c) => c.otherUserId)
    .filter((id): id is string => Boolean(id));
  const presence = usePresence(dmIds, initialPresence);

  return (
    <div className="card chat-col" style={{ padding: 14 }}>
      <div className="mb-3 flex items-center justify-between px-1">
        <h2 style={{ fontSize: "1.15rem" }}>Chat</h2>
        <span className="badge">{channels.length}</span>
      </div>

      {canCreate ? (
        <div className="mb-3">
          <NewChannelDialog users={users} />
        </div>
      ) : null}

      <div className="channel-scroll flex flex-1 flex-col gap-3 overflow-y-auto">
        {channels.length === 0 ? (
          <p className="text-muted px-1 py-4 text-sm">
            Noch keine Kanäle. Erstelle deinen ersten Kanal.
          </p>
        ) : (
          GROUP_ORDER.map(({ key, label }) => {
            const group = channels.filter((c) => c.type === key);
            if (group.length === 0) return null;
            return (
              <div key={key}>
                <div className="chat-group-head">
                  <span className="chat-group-dot" style={{ background: DOT_COLOR, boxShadow: `0 0 8px ${DOT_COLOR}` }} />
                  {label}
                </div>
                <div className="flex flex-col gap-0.5">
                  {group.map((c) => {
                    const active = pathname === `/chat/${c.id}`;
                    const dmStatus = c.type === "DIRECT" && c.otherUserId ? presence[c.otherUserId]?.status ?? null : null;
                    return (
                      <a key={c.id} href={`/chat/${c.id}`} className="channel-item" data-active={active}>
                        {c.type === "DIRECT" ? (
                          <Avatar name={c.title} src={c.avatarUrl} size={40} status={dmStatus} />
                        ) : c.avatarUrl ? (
                          <Avatar name={c.title} src={c.avatarUrl} size={40} square />
                        ) : (
                          <span className="channel-avatar">
                            <Icon name={TYPE_ICON[c.type] ?? "hash"} size={17} />
                          </span>
                        )}
                        <span className="min-w-0 flex-1">
                          <span className="flex items-center justify-between gap-2">
                            <span className="truncate font-bold">{c.title}</span>
                            {c.unread > 0 ? (
                              <span
                                className="grid h-[18px] min-w-[18px] place-items-center rounded-full px-1 text-[10px] font-black"
                                style={{ background: "var(--grad-brand)", color: "#0a0e22" }}
                              >
                                {c.unread > 9 ? "9+" : c.unread}
                              </span>
                            ) : null}
                          </span>
                          <span className="block truncate text-xs text-muted">
                            {c.lastMessage
                              ? `${c.lastMessage.author}: ${c.lastMessage.preview}`
                              : "Noch keine Nachrichten"}
                          </span>
                        </span>
                      </a>
                    );
                  })}
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
}
