'use client';

import { Activity, Clock, Gauge } from 'lucide-react';

import { getDefectVisual } from '@/constants/defectVisualConfig';
import { cn } from '@/lib/utils';
import type { CompletedVideoResult } from '@/types';

const formatDuration = (seconds?: number) => {
  if (typeof seconds !== 'number' || !Number.isFinite(seconds)) return '-';

  const minutes = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${minutes}:${secs.toString().padStart(2, '0')}`;
};

const formatFps = (fps?: number) =>
  typeof fps === 'number' && Number.isFinite(fps) ? fps.toFixed(1) : '-';

interface ResultStatsGridProps {
  data: CompletedVideoResult;
}

export default function ResultStatsGrid({ data }: ResultStatsGridProps) {
  const defectStats = data.defect_counts.map((item) => {
    const visual = getDefectVisual(item.class_name);

    return {
      label: item.display_name,
      value: item.count,
      icon: visual.icon,
      colorClassName: visual.colorClassName,
      iconClassName: visual.iconClassName,
    };
  });

  const stats = [
    {
      label: 'Total Detections',
      value: data.summary.total_detections,
      icon: Activity,
      colorClassName: 'text-green-500',
      iconClassName: 'bg-green-500/10 text-green-500',
    },
    ...defectStats,
    {
      label: 'FPS',
      value: formatFps(data.summary.fps),
      icon: Gauge,
      colorClassName: 'text-purple-500',
      iconClassName: 'bg-purple-500/10 text-purple-500',
    },
    {
      label: 'Duration',
      value: formatDuration(data.summary.duration_seconds),
      icon: Clock,
      colorClassName: 'text-cyan-500',
      iconClassName: 'bg-cyan-500/10 text-cyan-500',
    },
  ];

  return (
    <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">
      {stats.map((stat) => {
        const Icon = stat.icon;

        return (
          <div
            key={stat.label}
            className="rounded-xl bg-muted/40 p-4 transition-colors hover:bg-muted/60"
          >
            <div className="flex items-center justify-between gap-3">
              <p
                className={cn(
                  'text-2xl font-bold tracking-tight',
                  stat.colorClassName,
                )}
              >
                {stat.value}
              </p>
              <span
                className={cn(
                  'flex size-8 shrink-0 items-center justify-center rounded-lg',
                  stat.iconClassName,
                )}
              >
                <Icon className="size-3.5" />
              </span>
            </div>
            <p className="mt-2 truncate text-xs font-semibold text-foreground">
              {stat.label}
            </p>
          </div>
        );
      })}
    </div>
  );
}
