'use client';

import { useState, type ReactNode } from 'react';
import { Activity, CheckCircle, Clock, XCircle } from 'lucide-react';
import { Button } from '../ui/button';
import { Card, CardContent } from '../ui/card';
import { Skeleton } from '../ui/skeleton';
import { cn } from '../../lib/utils';

/**
 * Minimal, in-package shape of the workflow execution stats payload. Mirrors
 * the subset of the backend stats record this overview actually reads — kept
 * local so the component carries no app/Redux coupling.
 */
export interface WorkflowStats {
  totals: {
    total: number;
    completed: number;
    failed: number;
  };
  rates: {
    successRate: number;
    failureRate: number;
  };
  duration: {
    avgSeconds: number | null;
    minSeconds: number | null;
    maxSeconds: number | null;
  };
}

export interface WorkflowStatsOverviewProps {
  /** Execution stats to render. When undefined, cards show a skeleton/empty value. */
  stats?: WorkflowStats | null;
  /** Whether stats are currently loading (drives the per-card skeleton). */
  isLoading?: boolean;
  /**
   * Optional refresh callback. When provided, changing the period selector
   * invokes it with the selected period so the consumer can refetch.
   */
  onRefresh?: (period: string) => Promise<void>;
}

const PERIOD_OPTIONS = [
  { label: '7d', value: '7d' },
  { label: '30d', value: '30d' },
  { label: '90d', value: '90d' },
] as const;

function formatDuration(seconds: number | null | undefined): string {
  if (seconds === null || seconds === undefined || seconds === 0) return '0s';
  if (seconds < 60) return `${Math.round(seconds)}s`;
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.round(seconds % 60);
  if (remainingSeconds === 0) return `${minutes}m`;
  return `${minutes}m ${remainingSeconds}s`;
}

/**
 * Inline metric card — substitute for the app's `MetricsCard` primitive,
 * which is not part of @startsimpli/ui. Renders a titled value with an icon,
 * optional description, and a loading skeleton.
 */
function MetricCard({
  title,
  value,
  icon,
  description,
  loading,
}: {
  title: string;
  value: ReactNode;
  icon: ReactNode;
  description?: ReactNode;
  loading?: boolean;
}) {
  return (
    <Card>
      <CardContent className="pt-6">
        <div className="flex items-center justify-between">
          <span className="text-sm font-medium text-muted-foreground">
            {title}
          </span>
          <span className="text-muted-foreground">{icon}</span>
        </div>
        {loading ? (
          <Skeleton className="mt-2 h-7 w-20" />
        ) : (
          <div className="mt-2 text-2xl font-bold">{value ?? '—'}</div>
        )}
        {description && !loading && (
          <p className="mt-1 text-xs text-muted-foreground">{description}</p>
        )}
      </CardContent>
    </Card>
  );
}

export function WorkflowStatsOverview({
  stats,
  isLoading = false,
  onRefresh,
}: WorkflowStatsOverviewProps) {
  const [period, setPeriod] = useState('30d');

  const handlePeriodChange = (value: string) => {
    setPeriod(value);
    void onRefresh?.(value);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-medium text-muted-foreground">
          Execution Metrics
        </h3>
        <div className="flex items-center gap-1 rounded-lg border bg-muted/50 p-0.5">
          {PERIOD_OPTIONS.map((opt) => (
            <Button
              key={opt.value}
              variant="ghost"
              size="sm"
              className={cn(
                'h-7 px-3 text-xs font-medium',
                period === opt.value
                  ? 'bg-background shadow-sm text-foreground'
                  : 'text-muted-foreground hover:text-foreground'
              )}
              onClick={() => handlePeriodChange(opt.value)}
            >
              {opt.label}
            </Button>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <MetricCard
          title="Total Runs"
          value={stats?.totals.total ?? null}
          icon={<Activity className="h-4 w-4" />}
          description={`Last ${period}`}
          loading={isLoading}
        />
        <MetricCard
          title="Success Rate"
          value={stats ? `${stats.rates.successRate}%` : null}
          icon={<CheckCircle className="h-4 w-4" />}
          description={`${stats?.totals.completed ?? 0} completed`}
          loading={isLoading}
        />
        <MetricCard
          title="Avg Duration"
          value={stats ? formatDuration(stats.duration.avgSeconds) : null}
          icon={<Clock className="h-4 w-4" />}
          description={
            stats
              ? `${formatDuration(stats.duration.minSeconds)} - ${formatDuration(stats.duration.maxSeconds)}`
              : undefined
          }
          loading={isLoading}
        />
        <MetricCard
          title="Failed Runs"
          value={stats?.totals.failed ?? null}
          icon={<XCircle className="h-4 w-4" />}
          description={
            stats ? `${stats.rates.failureRate}% failure rate` : undefined
          }
          loading={isLoading}
        />
      </div>
    </div>
  );
}
