"use client";  // Mark this component as client-side

import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { MetarTable } from "@/components/metar-table";
import { CallsignSearch } from "@/components/callsign-search";
import { Header } from "@/components/header";
import { getUTCtime } from "@/lib/utils/metar";

// Function to fetch METAR data from the API
async function fetchMetarData() {
  const response = await fetch('/api/metar');
  if (!response.ok) {
    throw new Error('Failed to fetch METAR data');
  }
  return await response.json();
}

export default function Home() {
  const [metarData, setMetarData] = useState(null);
  const [loading, setLoading] = useState(true);
  const currentTime = getUTCtime();

  useEffect(() => {
    async function loadMetarData() {
      try {
        const data = await fetchMetarData();
        setMetarData(data);  // Update the state with fetched data
      } catch (error) {
        console.error("Error fetching METAR data:", error);
        setMetarData(null);  // Optionally handle error case
      } finally {
        setLoading(false);  // Set loading to false after fetching
      }
    }

    loadMetarData();  // Call the fetch function when the component mounts
  }, []);  // Empty dependency array means this effect runs once after mount

  return (
    <main className="min-h-screen bg-gradient-to-b from-gray-50 to-gray-100 dark:from-gray-900 dark:to-gray-800">
      <div className="container mx-auto px-4 py-8">
        <div className="flex flex-col gap-8">
          <Header currentTime={currentTime} />

          <Card className="overflow-hidden">
            {loading ? (
              <p>Loading METAR data...</p>
            ) : metarData ? (
              <MetarTable data={metarData} loading={false} />
            ) : (
              <p className="text-red-500">Error loading METAR data.</p>
            )}
          </Card>

          <div className="mt-8">
            <Card className="p-6">
              <h2 className="text-xl font-semibold mb-4">Callsign Decode</h2>
              <CallsignSearch />
            </Card>
          </div>
        </div>
      </div>
    </main>
  );
}
