import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import Displayer from '../components/Displayer';
import CommentSection from '../components/CommentSection';
import api from '../utils/api';
import { Article } from '../types/article';

const ArticleDetail = () => {
    const { id } = useParams<{ id: string }>();
    const [article, setArticle] = useState<Article | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');

    useEffect(() => {
        const fetchArticle = async () => {
            try {
                const res = await api.get(`/articles/article/${id}`);
                setArticle(res.data);

                console.log(res.data);

            } catch (err) {
                console.error('Chyba při načítání článku:', err);
                setError('Článek se nepodařilo načíst.');
            } finally {
                setLoading(false);
            }
        };

        fetchArticle();
    }, [id]);

    if (loading) return <div className="p-8">Načítám článek...</div>;
    if (error) return <div className="p-8 text-red-600">{error}</div>;
    if (!article) return <div className="p-8">Článek nebyl nalezen.</div>;


    return (
        <>
            <Displayer article={article} preview={false} />
            <CommentSection comments={article.comments} articleId={article.id} />
        </>
    );
};

export default ArticleDetail;
