"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Card } from "@/components/ui/card";
import { Header } from "@/components/header";
import { ControllerProfile } from "@/components/controller-profile";
import { createClient } from "@/lib/supabase/client";

export default function ControllerProfilePage() {
  const params = useParams();
  const [sessions, setSessions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const supabase = createClient();

  useEffect(() => {
    async function loadControllerData() {
      try {
        const { data, error } = await supabase
          .from('controller_sessions')
          .select('*')
          .eq('cid', params.cid)
          .order('last_seen', { ascending: false });
        
        if (error) throw error;
        setSessions(data || []);
      } catch (error) {
        console.error("Error fetching controller data:", error);
      } finally {
        setLoading(false);
      }
    }

    loadControllerData();
  }, [params.cid]);

  const controllerName = sessions[0]?.name || params.cid;

  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 Profile: ${controllerName}`}
            subtitle={`CID: ${params.cid}`}
          />

          <Card className="overflow-hidden">
            <ControllerProfile sessions={sessions} loading={loading} />
          </Card>
        </div>
      </div>
    </main>
  );
}