"use client"

import { Button } from "@/components/ui/button";
import { gql, useQuery } from "@apollo/client";
import Link from "next/link";
import { useEffect } from "react";

const BLOG = gql`
    query Blog {

        blogs {
            items {
                id
                title
                excerpt
                slug
            }
        }
        
    }
`

export default function Blog() {

    const { data, loading, error } = useQuery(BLOG);

    const items = data?.blogs?.items || [];

    return <div>
        <h1 className="text-5xl font-bold my-12">Blog</h1>
        {loading && <div>Loading...</div>}
        {error && <div>Error: {error.message}</div>}
        {!loading && items.length === 0 && <div>No blogs found</div>}
        {items.map((blog: any) => (
            <BlogItem key={blog.id} blog={blog} />
        ))}
    </div>;
}

function BlogItem({ blog }: { blog: any }) {
    return <div>
        <Link href={`/blog/${blog.slug}`}>
            <Button variant="link" asChild>
                <h2 className="text-2xl font-bold">{blog.title}</h2>
            </Button>
        </Link>
        <p className="text-sm text-gray-500">{blog.excerpt}</p>
    </div>
}

