'use client';

import { useProcesses } from '@/lib/hooks/useSupervisor';
import { GroupView } from '@/components/groups/GroupView';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { RefreshCw, AlertCircle } from 'lucide-react';

export default function GroupsPage() {
  const { data: processes, isLoading, isError, refetch } = useProcesses();

  if (isError) {
    return (
      <div className="space-y-6">
        <h1 className="text-3xl font-bold">Process Groups</h1>
        <Card className="border-destructive/50">
          <CardContent className="p-12 text-center">
            <AlertCircle className="h-12 w-12 text-destructive mx-auto mb-4" />
            <h2 className="text-xl font-semibold mb-2">Failed to load processes</h2>
            <p className="text-muted-foreground mb-4">
              Could not connect to Supervisor. Please check your configuration.
            </p>
            <Button onClick={() => refetch()} variant="outline">
              Try Again
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Process Groups</h1>
          <p className="text-muted-foreground mt-1">
            Manage processes organized by groups with batch operations
          </p>
        </div>

        <Button
          onClick={() => refetch()}
          variant="outline"
          size="sm"
          disabled={isLoading}
          className="gap-2"
        >
          <RefreshCw className={isLoading ? 'animate-spin h-4 w-4' : 'h-4 w-4'} />
          Refresh
        </Button>
      </div>

      {isLoading ? (
        <div className="space-y-6">
          {[1, 2].map((i) => (
            <Card key={i} className="animate-pulse">
              <CardContent className="p-8">
                <div className="h-8 bg-muted rounded w-1/3 mb-4"></div>
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                  {[1, 2, 3].map((j) => (
                    <div key={j} className="h-32 bg-muted rounded"></div>
                  ))}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      ) : processes && processes.length > 0 ? (
        <GroupView processes={processes} />
      ) : (
        <Card>
          <CardContent className="p-12 text-center">
            <p className="text-muted-foreground">No processes found</p>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
