"use client";

import { useState, useEffect } from "react";
import { Container } from "@/components/layout/Container";
import { PostCard } from "@/components/post/PostCard";
import { PostCardSkeleton } from "@/components/post/PostCardSkeleton";
import { Button } from "@/components/ui/Button";
import { api } from "@/lib/api";
import type { Post } from "@/types/api";

export default function HomePage() {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const limit = 10;

  useEffect(() => {
    async function fetchPosts() {
      setLoading(true);
      setError(null);
      try {
        const response = await api.getPosts(page, limit);
        setPosts(response.posts ?? []);
        setTotal(response.total ?? 0);
      } catch {
        setError("Could not retrieve latest transmission.");
      } finally {
        setLoading(false);
      }
    }

    fetchPosts();
  }, [page]);

  const totalPages = Math.ceil(total / limit);

  return (
    <Container className="py-24">
      <h1 className="text-6xl md:text-8xl font-bold tracking-tighter mb-24">
        Latest
      </h1>

      {error && (
        <p className="text-neutral-400 text-lg">{error}</p>
      )}

      {loading && (
        <>
          <PostCardSkeleton />
          <PostCardSkeleton />
          <PostCardSkeleton />
        </>
      )}

      {!loading && !error && posts?.length === 0 && (
        <p className="text-neutral-400 text-lg">No posts yet.</p>
      )}

      {!loading && !error && posts?.map((post) => (
        <PostCard key={post.id} post={post} />
      ))}

      {!loading && totalPages > 1 && (
        <div className="flex items-center justify-center gap-4 mt-24">
          <Button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page === 1}
          >
            Previous
          </Button>
          <span className="text-sm tracking-widest uppercase text-neutral-500">
            {page} / {totalPages}
          </span>
          <Button
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page === totalPages}
          >
            Next
          </Button>
        </div>
      )}
    </Container>
  );
}
