"use client";

import { useEffect, useState } from "react";
import { Card } from "@/components/ui/card";
import { Header } from "@/components/header";
import { ControllerTable } from "@/components/controller-table";
import { createClient } from "@/lib/supabase/client";

export default function ControllersPage() {
  const [controllers, setControllers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const supabase = createClient();

  useEffect(() => {
    async function loadControllers() {
      try {
        // Get unique controllers with their latest session
        const { data, error } = await supabase
          .from('controller_sessions')
          .select('*')
          .order('last_seen', { ascending: false });
        
        if (error) throw error;

        // Group by CID and take the most recent session
        const uniqueControllers = data.reduce((acc: any[], curr) => {
          const existingIndex = acc.findIndex(c => c.cid === curr.cid);
          if (existingIndex === -1) {
            acc.push(curr);
          }
          return acc;
        }, []);

        setControllers(uniqueControllers);
      } catch (error) {
        console.error("Error fetching controller data:", error);
      } finally {
        setLoading(false);
      }
    }

    loadControllers();
  }, []);

  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 
            title="Controller History" 
            subtitle="View recent controller activity" 
          />

          <Card className="overflow-hidden">
            <ControllerTable data={controllers} loading={loading} />
          </Card>
        </div>
      </div>
    </main>
  );
}