// DashboardPage.jsx
import React, { useState, useEffect } from 'react';
import { loadPosts } from '../data/blog-post-data';
import { Button } from '@progress/kendo-react-buttons';
import { Card, CardImage, CardBody, GridLayout } from '@progress/kendo-react-layout'; 
import PostCard from '../components/Cards/PostCard'; 

const Dashboard = React.forwardRef((props, ref) => {
    const [blogPosts, setBlogPosts] = useState([]);

    useEffect(() => {
        const fetchPosts = async () => {
            const postsData = await loadPosts();
            setBlogPosts(postsData);
        };
        fetchPosts();
    }, []);

    const publishedPosts = blogPosts.filter(post => post.published);
    const draftPosts = blogPosts.filter(post => !post.published);

    const handleEdit = (slug) => {
        props.navigate(`/editor/${slug}`);
    };

    return (
        <div style={{ textAlign: 'center' }} ref={ref}>
            <h1>Dashboard</h1>

            <section style={{ textAlign: 'center', maxWidth: '1200px', margin: '0 auto' }}> 
                <h2>Published Posts</h2>
                {publishedPosts.length ? (
                    <GridLayout 
                        cols={[{ width: "1fr" }, { width: "1fr" }, { width: "1fr" }]} 
                        gap={{ rows: 30, cols: 10 }} 
                        style={{ width: '900px' }}
                    >
                        {publishedPosts.map(post => (
                            // The PostCard automatically becomes a grid item (cell)
                            <PostCard 
                                key={post.slug} 
                                post={post} 
                                onEdit={handleEdit} 
                            />
                        ))}
                    </GridLayout>
                ) : (
                    <p>No published posts.</p>
                )}
            </section>

            <section style={{ textAlign: 'center' }}>
                <h2>Drafts</h2>
                {draftPosts.length ? (
                    <ul>
                        {draftPosts.map(post => (
                            <li key={post.slug}>
                                {post.title}{' '}
                                <Button style={{ marginLeft: '30px', padding: '0 20px' }} onClick={() => handleEdit(post.slug)}>Edit</Button>
                            </li>
                        ))}
                    </ul>
                ) : (
                    <p>No drafts.</p>
                )}
            </section>
        </div>
    );
});

export default Dashboard;