"use client";

import { useState } from "react";
import { getNewsroomList } from "@/api/newsroom";
import { NewsfeedItem } from "./NewsfeedItem";
import type { NewsroomItem, NewsroomPagination } from "@/types/newsroom";

interface NewsfeedContentProps {
  initialPagination: NewsroomPagination;
}

export function NewsfeedContent({ initialPagination }: NewsfeedContentProps) {
  const [articles, setArticles] = useState<NewsroomItem[]>(
    initialPagination?.docs || []
  );
  const [page, setPage] = useState<number>(initialPagination?.page || 1);
  const [hasNextPage, setHasNextPage] = useState<boolean>(
    Boolean(initialPagination?.hasNextPage)
  );
  const [loadingMore, setLoadingMore] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  const handleSeeMore = async () => {
    if (loadingMore || !hasNextPage) return;

    setLoadingMore(true);
    setError(null);

    try {
      const nextPage = page + 1;
      const res = await getNewsroomList({
        page: nextPage,
        limit: 20,
      });

      const newDocs = res.pagination.docs || [];

      // Deduplicate new docs to ensure no items are repeated
      setArticles((prev) => {
        const existingKeys = new Set(
          prev.map((item) => item._id || item.sl || item.t)
        );
        const uniqueDocs = newDocs.filter((item) => {
          const key = item._id || item.sl || item.t;
          return !existingKeys.has(key);
        });
        return [...prev, ...uniqueDocs];
      });

      setPage(res.pagination.page || nextPage);
      setHasNextPage(Boolean(res.pagination.hasNextPage));
    } catch (err) {
      console.error("Failed to load more live news:", err);
      setError("Unable to load additional updates. Please try again.");
    } finally {
      setLoadingMore(false);
    }
  };

  return (
    <div className="mx-auto w-full max-w-[1280px] px-5 sm:px-8 md:px-[60px]">
      {/* Live News Wire Header / Status Indicator */}


      {/* Main List */}
      {articles.length > 0 ? (
        <div className="divide-y divide-gray-200">
          {articles.map((item, idx) => (
            <NewsfeedItem
              key={item._id || item.sl || idx}
              item={item}
            />
          ))}
        </div>
      ) : (
        <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-gray-200 bg-gray-50/50 py-20 text-center">
          <p className="text-base font-semibold text-gray-700">
            No live news available right now.
          </p>
          <p className="mt-1 text-sm text-gray-500">
            Check back shortly for breaking intelligence updates.
          </p>
        </div>
      )}

      {/* Error Notice */}
      {error && (
        <div className="mt-6 rounded-lg bg-red-50 p-4 text-center text-sm text-red-600">
          {error}
        </div>
      )}

      {/* See More Button */}
      {hasNextPage && (
        <div className="mt-10 mb-6 flex w-full justify-center sm:mt-12 sm:mb-8">
          <button
            type="button"
            onClick={handleSeeMore}
            disabled={loadingMore}
            className="group relative inline-flex cursor-pointer items-center gap-3 overflow-hidden rounded-full border border-accent/20 bg-white px-8 py-3.5 text-sm font-semibold text-accent shadow-sm transition-all duration-300 hover:border-accent hover:bg-accent hover:text-white hover:shadow-md disabled:pointer-events-none disabled:opacity-60"
          >
            {loadingMore ? (
              <>
                <svg
                  className="h-4 w-4 animate-spin text-current"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  />
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  />
                </svg>
                <span>Loading more updates...</span>
              </>
            ) : (
              <>
                <span>See more</span>
                <span className="transition-transform duration-200 group-hover:translate-y-0.5">
                  ↓
                </span>
              </>
            )}
          </button>
        </div>
      )}

      {/* End of Feed Message */}
      {!hasNextPage && articles.length > 0 && (
        <div className="mt-12 mb-6 text-center text-xs font-medium uppercase tracking-wider text-gray-400">
          End of news latest
        </div>
      )}
    </div>
  );
}
