'use client';

import { getVehicleDisplayStatus } from '@/lib/utils';
import { useEffect, useState } from 'react';
import { fetchVehicles, getUpdates, fetchGroups, Vehicle, FirmwareUpdate, VehicleGroup } from '@/lib/api';
import { VehicleList } from '@/components/VehicleList';
import { UpdateManager } from '@/components/UpdateManager';
import { FirmwareList } from '@/components/FirmwareList';
import { GroupManager } from '@/components/GroupManager';
import { Activity, ShieldCheck, Truck } from 'lucide-react';

export default function Home() {
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [updates, setUpdates] = useState<FirmwareUpdate[]>([]);
  const [groups, setGroups] = useState<VehicleGroup[]>([]);
  const [loading, setLoading] = useState(true);

  const loadData = async () => {
    try {
      const [v, u, g] = await Promise.all([fetchVehicles(), getUpdates(), fetchGroups()]);
      setVehicles(v);
      setUpdates(u);
      setGroups(g);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
    const interval = setInterval(loadData, 3000); // Poll every 3s
    return () => clearInterval(interval);
  }, []);

  const onlineCount = vehicles.filter(v => getVehicleDisplayStatus(v) === 'Online').length;
  const updatingCount = vehicles.filter(v => getVehicleDisplayStatus(v) === 'Updating').length;

  return (
    <main className="min-h-screen bg-black text-zinc-100 selection:bg-indigo-500/30">
      <div className="max-w-7xl mx-auto px-6 py-10 space-y-8">
        {/* Header */}
        <header className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
              OTA Fleet Commander
            </h1>
            <p className="text-zinc-500 mt-1">Manage firmware updates for your vehicle fleet</p>
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 bg-zinc-900 px-4 py-2 rounded-lg border border-zinc-800">
              <span className="relative flex h-3 w-3">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                <span className="relative inline-flex rounded-full h-3 w-3 bg-emerald-500"></span>
              </span>
              <span className="text-sm font-medium text-emerald-400">System Active</span>
            </div>
          </div>
        </header>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="bg-zinc-900/50 border border-zinc-800 p-4 rounded-xl flex items-center gap-4">
            <div className="p-3 rounded-lg bg-indigo-500/10 text-indigo-400">
              <Truck className="w-6 h-6" />
            </div>
            <div>
              <p className="text-zinc-500 text-sm">Total Vehicles</p>
              <p className="text-2xl font-bold">{vehicles.length}</p>
            </div>
          </div>
          <div className="bg-zinc-900/50 border border-zinc-800 p-4 rounded-xl flex items-center gap-4">
            <div className="p-3 rounded-lg bg-emerald-500/10 text-emerald-400">
              <Activity className="w-6 h-6" />
            </div>
            <div>
              <p className="text-zinc-500 text-sm">Online Status</p>
              <p className="text-2xl font-bold">{onlineCount} <span className="text-sm text-zinc-500 font-normal">/ {vehicles.length}</span></p>
            </div>
          </div>
          <div className="bg-zinc-900/50 border border-zinc-800 p-4 rounded-xl flex items-center gap-4">
            <div className="p-3 rounded-lg bg-amber-500/10 text-amber-400">
              <ShieldCheck className="w-6 h-6" />
            </div>
            <div>
              <p className="text-zinc-500 text-sm">Current Version</p>
              {/* Naive logic: most common version or just listing */}
              <p className="text-lg font-bold truncate max-w-[150px]">
                {updates[0]?.version || 'v1.0.0'}
              </p>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2 space-y-8">
            <VehicleList vehicles={vehicles} groups={groups} />
            <UpdateManager
              updates={updates}
              vehicles={vehicles}
              groups={groups}
              onUpdateDeployed={loadData}
            />
          </div>
          <div className="space-y-8">
            <GroupManager groups={groups} vehicles={vehicles} onGroupChanged={loadData} />
            <FirmwareList updates={updates} />
          </div>
        </div>
      </div>
    </main>
  );
}
