"use client";

import { useEffect, useState } from "react";
import { RefreshCcw, Wind, Plane } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { MetarTable } from "@/components/metar-table";
import { CallsignSearch } from "@/components/callsign-search";
import { mainAirports, secondaryAirports, fetchAirportData, getUTCtime } from "@/lib/utils/metar";
import { useToast } from "@/components/ui/use-toast";

export default function Home() {
  const [loading, setLoading] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<string>("");
  const [metarData, setMetarData] = useState<any[]>([]);
  const { toast } = useToast();

  const fetchData = async () => {
    setLoading(true);
    try {
      const allAirports = [...mainAirports, ...secondaryAirports];
      const promises = allAirports.map(airport => fetchAirportData(airport));
      const results = await Promise.all(promises);
      const validResults = results.filter(Boolean);
      
      if (validResults.length === 0) {
        throw new Error("Unable to fetch METAR data for any airport");
      }
      
      setMetarData(validResults);
      setLastUpdated(getUTCtime());
    } catch (error) {
      console.error("Failed to fetch METAR data:", error);
      toast({
        title: "Error",
        description: "Failed to fetch METAR data. Please try again later.",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 300000); // Refresh every 5 minutes
    return () => clearInterval(interval);
  }, []);

  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">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Plane className="h-8 w-8 text-blue-600 dark:text-blue-400" />
              <h1 className="text-3xl font-bold tracking-tight">CZQM Ops Support Tool</h1>
            </div>
            <div className="flex items-center gap-4">
              <p className="text-sm text-gray-600 dark:text-gray-400">
                Last updated: {lastUpdated || "--:-- UTC"}
              </p>
              <Button
                onClick={fetchData}
                disabled={loading}
                variant="outline"
                className="gap-2"
              >
                <RefreshCcw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
                Refresh
              </Button>
            </div>
          </div>

          <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>
  );
}