import { useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { FiClock, FiTrendingUp } from "react-icons/fi";
import {
  useApiSocialHubsRetrieve,
  getApiSocialHubsRetrieveQueryKey,
  useApiSocialHubsJoinCreate,
  useApiSocialHubsLeaveCreate,
} from "@/api/generated/private/hubs/hubs";
import { useAuth } from "@/hooks/useAuth";
import { useInfiniteHubPosts } from "@/hooks/useInfiniteHubPosts";
import { useIntersectionLoader } from "@/hooks/useIntersectionLoader";
import type { HubSortOption, HubTimeOption } from "@/api/social/hubFeed";
import HubHeader from "@/components/social/hub/HubHeader";
import Post from "@/components/social/posts/Post";
import PostComposer from "@/components/social/posts/PostComposer";
import Spinner from "@/components/ui/Spinner";
import EmptyState from "@/components/ui/EmptyState";

export default function HubPage() {
  const { t } = useTranslation("social");
  const { name } = useParams<{ name: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const { user } = useAuth();

  const [sort, setSort] = useState<HubSortOption>("newest");
  const [time, setTime] = useState<HubTimeOption>("all");
  const [customStart, setCustomStart] = useState("");
  const [customEnd, setCustomEnd] = useState("");

  const TIME_OPTIONS: { value: HubTimeOption; label: string }[] = [
    { value: "1h",     label: "1 h" },
    { value: "6h",     label: "6 h" },
    { value: "day",    label: t("hub.timeOptions.day") },
    { value: "week",   label: t("hub.timeOptions.week") },
    { value: "month",  label: t("hub.timeOptions.month") },
    { value: "year",   label: t("hub.timeOptions.year") },
    { value: "all",    label: t("hub.timeOptions.all") },
    { value: "custom", label: t("hub.timeOptions.custom") },
  ];

  const { data: hub, isLoading: hubLoading } = useApiSocialHubsRetrieve(name ?? "");

  const isMember = !!(user && hub?.members?.includes(user.id));
  const isOwner = !!(user && hub?.owner === user.id);
  const isModerator = !!(user && hub?.moderators?.some((m) => m.user === user.id));

  const joinMutation = useApiSocialHubsJoinCreate({
    mutation: {
      onSuccess: () => {
        void queryClient.invalidateQueries({ queryKey: getApiSocialHubsRetrieveQueryKey(name!) });
      },
    },
  });
  const leaveMutation = useApiSocialHubsLeaveCreate({
    mutation: {
      onSuccess: () => {
        void queryClient.invalidateQueries({ queryKey: getApiSocialHubsRetrieveQueryKey(name!) });
      },
    },
  });

  const {
    posts,
    isLoading: postsLoading,
    hasNextPage,
    isFetchingNextPage,
    fetchNextPage,
    refetch,
  } = useInfiniteHubPosts({
    hubId: hub?.id ?? 0,
    sort,
    time,
    start: time === "custom" ? customStart : undefined,
    end: time === "custom" ? customEnd : undefined,
    enabled: !!hub?.id,
  });

  const sentinelRef = useIntersectionLoader<HTMLDivElement>(
    () => { if (hasNextPage && !isFetchingNextPage) void fetchNextPage(); },
    { enabled: hasNextPage && !postsLoading },
  );

  if (hubLoading) {
    return <div className="flex justify-center py-10"><Spinner size={28} /></div>;
  }
  if (!hub) {
    return <EmptyState title={t("hub.notFound")} />;
  }

  return (
    <div>
      <HubHeader
        hub={hub}
        isMember={isMember}
        isOwner={isOwner}
        isModerator={isModerator}
        joining={joinMutation.isPending || leaveMutation.isPending}
        onJoin={() => joinMutation.mutate({ name: name! })}
        onLeave={() => leaveMutation.mutate({ name: name! })}
      />

      {/* Composer — members and owner */}
      {(isMember || isOwner) && (
        <>
          <hr className="border-brand-lines/15" />
          <PostComposer hubId={hub.id} hubName={hub.name} onPosted={() => void refetch()} />
        </>
      )}

      {/* Sort + time filter bar */}
      <div className="border-b border-brand-lines/10 px-4 py-2 flex flex-col gap-2">
        {/* Sort toggle */}
        <div className="flex gap-1">
          <button
            type="button"
            onClick={() => setSort("newest")}
            className={[
              "flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors",
              sort === "newest"
                ? "bg-brand-accent text-white"
                : "text-brand-text/60 hover:bg-brand-lines/10 hover:text-brand-text",
            ].join(" ")}
          >
            <FiClock size={12} />
            {t("hub.newest")}
          </button>
          <button
            type="button"
            onClick={() => setSort("top")}
            className={[
              "flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors",
              sort === "top"
                ? "bg-brand-accent text-white"
                : "text-brand-text/60 hover:bg-brand-lines/10 hover:text-brand-text",
            ].join(" ")}
          >
            <FiTrendingUp size={12} />
            {t("hub.top")}
          </button>
        </div>

        {/* Time filter — only for "top" */}
        {sort === "top" && (
          <div className="flex flex-wrap gap-1">
            {TIME_OPTIONS.map((opt) => (
              <button
                key={opt.value}
                type="button"
                onClick={() => setTime(opt.value)}
                className={[
                  "rounded-full px-2.5 py-0.5 text-xs font-medium transition-colors",
                  time === opt.value
                    ? "bg-brand-accent/20 text-brand-accent"
                    : "text-brand-text/50 hover:bg-brand-lines/10 hover:text-brand-text",
                ].join(" ")}
              >
                {opt.label}
              </button>
            ))}
          </div>
        )}

        {/* Custom date range */}
        {sort === "top" && time === "custom" && (
          <div className="flex items-center gap-2">
            <input
              type="date"
              value={customStart}
              onChange={(e) => setCustomStart(e.target.value)}
              className="rounded-lg border border-brand-lines/25 bg-brand-bgLight/40 px-2 py-1 text-xs text-brand-text focus:border-brand-accent focus:outline-none"
            />
            <span className="text-xs text-brand-text/40">–</span>
            <input
              type="date"
              value={customEnd}
              onChange={(e) => setCustomEnd(e.target.value)}
              className="rounded-lg border border-brand-lines/25 bg-brand-bgLight/40 px-2 py-1 text-xs text-brand-text focus:border-brand-accent focus:outline-none"
            />
          </div>
        )}
      </div>

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

      {!postsLoading && posts.length === 0 && (
        <EmptyState message={t("hub.noPosts")} />
      )}

      {posts.map((p) => (
        <Post
          key={p.id}
          post={p}
          hideHubBadge
          onReplyClick={() => navigate(`/social/post/${p.id}`)}
        />
      ))}

      {hasNextPage && (
        <div ref={sentinelRef} className="flex justify-center py-6 text-sm text-brand-text/60">
          {isFetchingNextPage ? <Spinner size={20} /> : t("hub.loadMore")}
        </div>
      )}
    </div>
  );
}
