"use client";

import { SubjectAvatar } from "@/components/ui/SubjectAvatar";

export type SocialChatItem = {
  id: number;
  pair_id: number;
  type: "channel" | "group";
  kind?: "social" | "system_announcement" | "school_announcement" | "class_announcement";
  broadcast_space_id?: number | null;
  title: string;
  is_verified?: boolean;
  is_active?: boolean;
  linked_space_id?: number | null;
  class_code?: string | null;
  subject_name?: string | null;
  subject_image_url?: string | null;
  last_message?: string | null;
  last_at?: string | null;
  unread_count: number;
  members_count?: number;
};

function formatTime(iso?: string | null) {
  if (!iso) return "";
  try {
    return new Date(iso).toLocaleTimeString("fa-IR", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: false,
      hourCycle: "h23",
    });
  } catch {
    return "";
  }
}

export function SocialChatList({
  chats,
  activeId,
  chatFilterQuery,
  filter,
  onFilterChange,
  onSelect,
  onOpenSearch,
  className = "",
}: {
  chats: SocialChatItem[];
  activeId?: number | null;
  chatFilterQuery?: string;
  onSelect: (chat: SocialChatItem) => void;
  onOpenSearch: () => void;
  filter: "all" | "channel" | "group";
  onFilterChange: (v: "all" | "channel" | "group") => void;
  className?: string;
}) {
  const filtered = chats.filter((c) => {
    if (filter !== "all" && c.type !== filter) return false;
    const term = (chatFilterQuery ?? "").trim().toLowerCase();
    if (!term) return true;
    return [c.title, c.class_code, c.subject_name, c.last_message]
      .filter(Boolean)
      .join(" ")
      .toLowerCase()
      .includes(term);
  });

  const unreadAll = chats.reduce((s, c) => s + (c.unread_count || 0), 0);

  return (
    <aside
      className={`flex min-h-0 w-full flex-col bg-[#f7faf9] lg:max-w-[360px] lg:shrink-0 lg:border-l lg:border-slate-200/80 ${className}`}
    >
      <div className="border-b border-slate-200/80 bg-white px-4 pb-3 pt-[max(0.75rem,env(safe-area-inset-top))] lg:pt-4">
        <div className="mb-3 text-xl font-bold tracking-tight text-teal-800">شبکه</div>
        <button
          type="button"
          onClick={onOpenSearch}
          className="flex w-full items-center gap-2.5 rounded-2xl border border-slate-200/80 bg-slate-50/80 px-3.5 py-2.5 text-right text-sm text-slate-400 shadow-sm transition hover:border-teal-300 hover:bg-white hover:text-slate-500"
        >
          <svg viewBox="0 0 24 24" className="h-5 w-5 shrink-0 opacity-70" fill="currentColor" aria-hidden>
            <path d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" />
          </svg>
          <span>جستجوی پیام…</span>
        </button>
      </div>

      <div className="flex gap-2 overflow-x-auto px-4 py-2.5">
        {(
          [
            ["all", "همه", unreadAll],
            ["group", "گروه", 0],
            ["channel", "کانال", 0],
          ] as const
        ).map(([id, label, badge]) => (
          <button
            key={id}
            type="button"
            onClick={() => onFilterChange(id)}
            className={`relative whitespace-nowrap rounded-full px-4 py-1.5 text-xs font-semibold transition ${
              filter === id
                ? "bg-teal-600 text-white shadow-sm shadow-teal-600/25"
                : "bg-white text-slate-600 ring-1 ring-slate-200/80 hover:bg-slate-50"
            }`}
          >
            {label}
            {id === "all" && badge > 0 ? (
              <span
                className={`mr-1.5 inline-flex min-w-[1.1rem] justify-center rounded-full px-1.5 text-[10px] ${
                  filter === id ? "bg-white/90 text-teal-700" : "bg-teal-600 text-white"
                }`}
              >
                {badge}
              </span>
            ) : null}
          </button>
        ))}
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto px-2 pb-2">
        {filtered.map((chat) => {
          const active = activeId === chat.id;
          const avatarName = chat.subject_name ?? chat.title;
          return (
            <button
              key={chat.id}
              type="button"
              onClick={() => onSelect(chat)}
              className={`mb-1 flex w-full items-start gap-3 rounded-2xl px-3 py-3 text-right transition ${
                active
                  ? "bg-white shadow-sm ring-1 ring-teal-200/80"
                  : "hover:bg-white/70"
              }`}
            >
              <div className="relative shrink-0">
                <SubjectAvatar
                  name={avatarName}
                  imageUrl={chat.subject_image_url}
                  size="lg"
                  className="rounded-2xl ring-2 ring-white shadow-sm"
                />
                <span
                  className={`absolute -bottom-0.5 -left-0.5 rounded-md px-1 py-px text-[9px] font-bold text-white shadow ${
                    chat.type === "group" ? "bg-teal-600" : "bg-sky-500"
                  }`}
                >
                  {chat.type === "group" ? "گ" : "ک"}
                </span>
              </div>
              <div className="min-w-0 flex-1">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <div className="flex items-center gap-1 truncate font-semibold text-slate-900">
                      <span className="truncate">{chat.title}</span>
                      {chat.is_verified ? (
                        <span className="shrink-0 text-sky-500" title="تأیید شده">
                          ✓
                        </span>
                      ) : null}
                      {chat.is_active === false ? (
                        <span className="shrink-0 rounded-full bg-slate-200 px-1.5 py-0.5 text-[9px] font-bold text-slate-600">
                          غیرفعال
                        </span>
                      ) : null}
                    </div>
                    {chat.subject_name && chat.class_code ? (
                      <div className="mt-0.5 truncate text-[11px] text-slate-400">
                        {chat.subject_name} · {chat.class_code}
                      </div>
                    ) : null}
                  </div>
                  <div className="shrink-0 text-[11px] tabular-nums text-slate-400">{formatTime(chat.last_at)}</div>
                </div>
                <div className="mt-1 flex items-center justify-between gap-2">
                  <div className="truncate text-xs leading-relaxed text-slate-500">
                    {chat.last_message || "بدون پیام"}
                  </div>
                  {chat.unread_count > 0 ? (
                    <span className="flex h-5 min-w-[1.25rem] shrink-0 items-center justify-center rounded-full bg-teal-600 px-1.5 text-[10px] font-bold text-white">
                      {chat.unread_count}
                    </span>
                  ) : null}
                </div>
              </div>
            </button>
          );
        })}
        {!filtered.length ? (
          <div className="mx-2 rounded-2xl border border-dashed border-slate-200 bg-white/60 p-8 text-center text-sm text-slate-400">
            گفتگویی یافت نشد
          </div>
        ) : null}
      </div>
    </aside>
  );
}
