'use client';

import { useEffect, useState } from 'react';
import type { Park } from '@/types/api';

export default function Home() {
  const [parks, setParks] = useState<Park[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchParks() {
      try {
        const response = await fetch('/api/parks');
        const data = await response.json();
        
        if (!data.success) {
          throw new Error(data.error || 'Failed to fetch parks');
        }

        setParks(data.data || []);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setLoading(false);
      }
    }

    fetchParks();
  }, []);

  if (loading) {
    return (
      <main className="min-h-screen p-8">
        <div className="text-center">
          <div className="inline-block h-8 w-8 animate-spin rounded-full border-4 border-solid border-current border-r-transparent align-[-0.125em] motion-reduce:animate-[spin_1.5s_linear_infinite]" />
          <p className="mt-4 text-gray-600">Loading parks...</p>
        </div>
      </main>
    );
  }

  if (error) {
    return (
      <main className="min-h-screen p-8">
        <div className="rounded-lg bg-red-50 p-4 border border-red-200">
          <h2 className="text-red-800 font-semibold">Error</h2>
          <p className="text-red-600 mt-2">{error}</p>
        </div>
      </main>
    );
  }

  return (
    <main className="min-h-screen p-8">
      <h1 className="text-3xl font-bold mb-8">ThrillWiki Parks</h1>
      
      {parks.length === 0 ? (
        <p className="text-gray-600">No parks found</p>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {parks.map((park) => (
            <div
              key={park.id}
              className="rounded-lg border border-gray-200 p-6 hover:shadow-lg transition-shadow"
            >
              <h2 className="text-xl font-semibold mb-2">{park.name}</h2>
              {park.description && (
                <p className="text-gray-600 mb-4">
                  {park.description.length > 150
                    ? `${park.description.slice(0, 150)}...`
                    : park.description}
                </p>
              )}
              <div className="text-sm text-gray-500">
                Added: {new Date(park.createdAt).toLocaleDateString()}
              </div>
            </div>
          ))}
        </div>
      )}
    </main>
  );
}
