import { Link, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { FiArrowLeft } from "react-icons/fi";
import { useApiSocialHubsRetrieve } from "@/api/generated/private/hubs/hubs";
import { useApiSocialPostsList } from "@/api/generated/private/posts/posts";
import Post from "@/components/social/posts/Post";
import Avatar from "@/components/ui/Avatar";
import Spinner from "@/components/ui/Spinner";
import EmptyState from "@/components/ui/EmptyState";

export default function HubPage() {
  const { t } = useTranslation("social");
  const { id } = useParams<{ id: string }>();
  const hubId = Number(id);

  const { data: hub, isLoading } = useApiSocialHubsRetrieve(String(hubId));
  const { data: postsData, isLoading: postsLoading } = useApiSocialPostsList(
    Number.isFinite(hubId) ? { hub: hubId } : undefined,
  );
  const posts = postsData?.results ?? [];

  if (isLoading) {
    return (
      <div className="flex justify-center py-10">
        <Spinner size={28} />
      </div>
    );
  }

  if (!hub) {
    return <EmptyState title="Hub nenalezen" />;
  }

  return (
    <div>
      <header className="sticky top-0 z-10 flex items-center gap-3 border-b border-brand-lines/10 bg-brand-bg/80 px-4 py-3 backdrop-blur">
        <Link
          to="/social/hubs"
          className="rounded-full p-1 text-brand-text hover:bg-brand-lines/10"
          aria-label={t("common:back", { defaultValue: "Zpět" })}
        >
          <FiArrowLeft size={20} />
        </Link>
        <Avatar name={hub.name} src={hub.icon ?? undefined} size={36} />
        <div className="min-w-0 flex-1">
          <h1 className="truncate text-lg font-bold text-brand-text">{hub.name}</h1>
          {hub.description && (
            <p className="truncate text-xs text-brand-text/60">{hub.description}</p>
          )}
        </div>
      </header>

      {postsLoading && (
        <div className="flex justify-center py-6">
          <Spinner size={24} />
        </div>
      )}

      {!postsLoading && posts.length === 0 && <EmptyState message="—" />}

      {posts.map((p) => (
        <Post key={p.id} post={p} />
      ))}
    </div>
  );
}
