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

export default function PageView() {
  const { slug } = useParams();
  const [page, setPage] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchPage = async () => {
      try {
        const res = await axios.get('http://localhost:5000/api/cms-pages');
        const found = res.data.find(p => p.slug === slug);
        if (found) {
          setPage(found);
        } else {
          setError('The page you requested could not be found.');
        }
      } catch (err) {
        setError('Failed to fetch page content from database.');
      } finally {
        setLoading(false);
      }
    };
    fetchPage();
  }, [slug]);

  return (
    <div className="min-h-screen bg-background font-sans flex flex-col justify-between">
      <div>
        <Navbar />
        <main className="max-w-4xl mx-auto px-6 py-24 mt-8">
          {loading ? (
            <div className="text-center py-24">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto"></div>
              <p className="text-on-surface-variant mt-4 font-semibold">Loading page details...</p>
            </div>
          ) : error ? (
            <div className="text-center py-20 max-w-md mx-auto space-y-6">
              <span className="material-symbols-outlined text-red-400 text-[80px]">error</span>
              <h1 className="text-3xl font-headline font-bold text-primary">Page Not Found</h1>
              <p className="text-on-surface-variant font-medium">{error}</p>
              <Link 
                to="/" 
                className="inline-block bg-primary text-white px-8 py-3 rounded-full font-bold shadow-lg shadow-primary/10 hover:scale-[1.02] active:scale-95 transition-transform"
              >
                Return to Home
              </Link>
            </div>
          ) : (
            <article className="space-y-8">
              <div className="border-b-2 border-outline-variant/30 pb-6">
                <h1 className="text-4xl md:text-5xl font-headline font-bold text-primary">{page.title}</h1>
                <p className="text-xs text-on-surface-variant font-medium mt-2">
                  Published: {new Date(page.lastUpdated).toLocaleDateString()}
                </p>
              </div>
              <div 
                className="prose max-w-none text-on-surface-variant leading-relaxed text-sm md:text-base font-medium space-y-4"
                dangerouslySetInnerHTML={{ __html: page.content }}
              />
            </article>
          )}
        </main>
      </div>
      <Footer />
    </div>
  );
}
