"use client";

import { useState, useCallback, useEffect } from "react";
import { StemeDBClient, type FeedResponse, ApiError } from "@/lib/api";
import type { PanelState } from "@/lib/types";
import { FEED_PAGE_SIZE } from "@/lib/constants";
import { ErrorState } from "@/components/shared/error-state";
import { FeedList } from "./feed-list";
import { FeedLoadingSkeleton } from "./feed-loading-skeleton";

interface FeedData {
  response: FeedResponse;
  allAssertions: FeedResponse["assertions"];
}

export function FeedPanel() {
  const [state, setState] = useState<PanelState<FeedData>>({ status: "idle" });
  const [loadingMore, setLoadingMore] = useState(false);

  const fetchData = useCallback(async () => {
    setState({ status: "loading" });
    try {
      const client = new StemeDBClient();
      const response = await client.feed(FEED_PAGE_SIZE, 0);
      setState({
        status: "success",
        data: { response, allAssertions: response.assertions },
      });
    } catch (err) {
      if (err instanceof ApiError && err.status === 404) {
        setState({
          status: "success",
          data: {
            response: { assertions: [], total_count: 0, has_more: false },
            allAssertions: [],
          },
        });
        return;
      }
      const message =
        err instanceof ApiError
          ? err.userMessage
          : err instanceof Error
            ? err.message
            : "Unknown error";
      setState({ status: "error", error: message });
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleLoadMore = useCallback(async () => {
    if (state.status !== "success") return;

    setLoadingMore(true);
    try {
      const client = new StemeDBClient();
      const offset = state.data.allAssertions.length;
      const response = await client.feed(FEED_PAGE_SIZE, offset);
      setState((prev) => {
        if (prev.status !== "success") return prev;
        return {
          status: "success",
          data: {
            response,
            allAssertions: [...prev.data.allAssertions, ...response.assertions],
          },
        };
      });
    } catch (err) {
      // Silently fail on load-more — user can retry
      const message =
        err instanceof ApiError
          ? err.userMessage
          : err instanceof Error
            ? err.message
            : "Failed to load more";
      console.error("Feed load more failed:", message);
    } finally {
      setLoadingMore(false);
    }
  }, [state]);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="rounded-lg border border-border bg-card p-6">
        <h2 className="text-lg font-medium text-card-foreground mb-2">
          Assertion Feed
        </h2>
        <p className="text-sm text-muted-foreground">
          Live feed of all assertions, newest first.
        </p>
      </div>

      {/* Content */}
      <div className="rounded-lg border border-border bg-card p-6">
        {(state.status === "idle" || state.status === "loading") && (
          <FeedLoadingSkeleton />
        )}

        {state.status === "error" && (
          <ErrorState
            title="Failed to Load Feed"
            error={state.error}
            onRetry={fetchData}
          />
        )}

        {state.status === "success" && (
          <FeedList
            assertions={state.data.allAssertions}
            totalCount={state.data.response.total_count}
            hasMore={state.data.response.has_more}
            onLoadMore={handleLoadMore}
            loading={loadingMore}
          />
        )}
      </div>
    </div>
  );
}
