"use client";

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";

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

  useEffect(() => {
    async function loadMetarData() {
      try {
        const response = await fetch('/api/metar');
        if (!response.ok) throw new Error('Failed to fetch METAR data');
        const data = await response.json();
        setMetarData(data);
      } catch (error) {
        console.error("Error fetching METAR data:", error);
      } finally {
        setLoading(false);
      }
    }

    loadMetarData();
  }, []);

  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">
            <MetarTable data={metarData} loading={loading} />
          </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>
  );
}