import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import NavBar from '../components/NavBar';
import Footer from '../components/Footer';

interface Article {
    id: string;
    title: string;
    content: string;
    author: string;
    publishedAt: string;
    editedAt: string;
}

const ArticlePage: React.FC = () => {
    const { id } = useParams<{ id: string }>();
    const [article, setArticle] = useState<Article | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        fetch(`/api/article/${id}`)
                .then(response => response.json())
                .then(data => setArticle(data))
                .catch(_ => setError('Failed to fetch article'))
                .finally(() => setLoading(false));
    }, [id]);

    if (loading) {
        return <div>Loading...</div>;
    }

    if (error) {
        return <div>{error}</div>;
    }

    if (!article) {
        return <div>Article not found</div>;
    }

    return (
        <div style={{
            display: 'flex',
            flexDirection: 'column',
            minHeight: '100vh'
        }}>
            <NavBar/>
            <div style={{
                borderRadius: '8px',
                color: 'var(--color-black)',
                fontFamily: '"Haas Grot Text R Web", "Helvetica Neue", Helvetica, Arial, sans-serif',
                fontSize: '14px',
                lineHeight: '20px',
                padding: '1.25em',
                paddingBottom: '1em',
                textAlign: 'left',
                maxWidth: '60rem',
                margin: 'auto',
            }}>
                <img src="https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fimages8.alphacoders.com%2F438%2F438396.jpg&f=1&nofb=1&ipt=14796576c139b58db62d2d2098392ef2fbaee77911040f7c0d98ab65a69c4644&ipo=images" alt="Article preview" style={{
                    borderRadius: '8px',
                    width: '100%',
                    height: 'auto',
                    marginBottom: '10px',
                }} />
                <div>
                    <h1>{article.title}</h1>
                    <p>écrit par {article.author} le {new Date(article.publishedAt).toLocaleDateString()} (Dernière modification le : {new Date(article.editedAt || article.publishedAt).toLocaleDateString()})</p>
                    <hr/>
                    <p>{article.content}</p>
                </div>
            </div>
            <Footer bgcolor='lightblue'/>
        </div>
    );
};

export default ArticlePage;