'use client';

import { ProcessInfo, ProcessState } from '@/lib/supervisor/types';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { chartColors } from '@/lib/utils/chartColors';

interface GroupStatisticsProps {
  processes: ProcessInfo[];
}

export function GroupStatistics({ processes }: GroupStatisticsProps) {
  // Group processes and count states
  const groupData = processes.reduce((acc, proc) => {
    const group = proc.group;
    if (!acc[group]) {
      acc[group] = { name: group, running: 0, stopped: 0, fatal: 0, total: 0 };
    }
    acc[group].total++;
    if (proc.state === ProcessState.RUNNING) acc[group].running++;
    else if (proc.state === ProcessState.STOPPED || proc.state === ProcessState.EXITED) acc[group].stopped++;
    else if (proc.state === ProcessState.FATAL) acc[group].fatal++;
    return acc;
  }, {} as Record<string, { name: string; running: number; stopped: number; fatal: number; total: number }>);

  const data = Object.values(groupData).sort((a, b) => b.total - a.total);

  if (data.length === 0) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Process Groups Overview</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="h-[300px] flex items-center justify-center text-muted-foreground">
            No process groups
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Process Groups Overview</CardTitle>
      </CardHeader>
      <CardContent>
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={data}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" />
            <YAxis />
            <Tooltip
              contentStyle={{
                backgroundColor: 'rgba(0, 0, 0, 0.9)',
                border: 'none',
                borderRadius: '8px',
                color: '#ffffff',
              }}
              itemStyle={{ color: '#ffffff' }}
            />
            <Legend />
            <Bar dataKey="running" stackId="a" fill={chartColors.running} name="Running" />
            <Bar dataKey="stopped" stackId="a" fill={chartColors.stopped} name="Stopped" />
            <Bar dataKey="fatal" stackId="a" fill={chartColors.fatal} name="Fatal" />
          </BarChart>
        </ResponsiveContainer>
      </CardContent>
    </Card>
  );
}
