import { AlertTriangle, Activity, Server, BarChart3, Code2, FileText, GitBranch, Layers } from 'lucide-react';
import { Card } from '@/components/ui/Card';
import { Panel } from '@/components/ui/Panel';
import { Spinner } from '@/components/ui/Spinner';
import { useCodeStats } from '@/hooks/useCodeStats';
import { useDocsStats } from '@/hooks/useDocsStats';
import { useOtelStats } from '@/hooks/useOtelStats';
import { useOtelHealth } from '@/hooks/useOtelHealth';
import { TraceVolumeChart } from '@/components/charts/TraceVolumeChart';
import { EntityBreakdownChart } from '@/components/charts/EntityBreakdownChart';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

interface AnyData {
  [key: string]: unknown;
}

function asRecord(data: unknown): AnyData | null {
  if (data && typeof data === 'object' && !Array.isArray(data)) {
    return data as AnyData;
  }
  return null;
}

function num(value: unknown): number {
  return typeof value === 'number' ? value : 0;
}

function fmt(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return String(n);
}

type Gradient = 'blue' | 'green' | 'amber' | 'red' | 'none';

function errorRateGradient(rate: number): Gradient {
  if (rate > 5) return 'red';
  if (rate > 1) return 'amber';
  return 'green';
}

function latencyGradient(ms: number): Gradient {
  if (ms > 500) return 'amber';
  return 'green';
}

// ---------------------------------------------------------------------------
// Section wrapper that shows a spinner while loading
// ---------------------------------------------------------------------------

function LoadingWrap({ isLoading, children }: { isLoading: boolean; children: React.ReactNode }) {
  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-8">
        <Spinner size="lg" />
      </div>
    );
  }
  return <>{children}</>;
}

// ---------------------------------------------------------------------------
// Dashboard
// ---------------------------------------------------------------------------

export default function DashboardPage() {
  const codeStats = useCodeStats();
  const docsStats = useDocsStats();
  const otelStats = useOtelStats();
  const otelHealth = useOtelHealth();

  const code = asRecord(codeStats.data);
  const docs = asRecord(docsStats.data);
  const otel = asRecord(otelStats.data);
  const health = asRecord(otelHealth.data);

  // --- Derived values ---
  const totalTraces = num(otel?.traces);
  const errorSpans = num(otel?.error_spans);
  const totalSpans = num(otel?.spans);
  const errorRate = totalSpans > 0 ? (errorSpans / totalSpans) * 100 : 0;
  // P99 latency: not directly in stats — show a placeholder from health or N/A
  const p99 = num(health?.p99_latency_ms);
  const servicesUp = num(health?.services_up ?? otel?.services);
  const servicesTotal = num(health?.services_total ?? otel?.services);

  const codeEntities = num(code?.entities);
  const docCount = num(docs?.documents);
  const serviceCount = num(otel?.services);
  const relationsCount = num(code?.relations);

  // Entity type breakdown for bar chart (mock-friendly)
  const entityBreakdown = code
    ? (code.entity_types as Record<string, number> | undefined) ?? {
        Functions: num(code.entities),
        Classes: 0,
        Methods: 0,
        Modules: num(code.files),
      }
    : null;

  return (
    <div className="space-y-6">
      {/* ================================================================ */}
      {/* Row 1 — Health Cards                                             */}
      {/* ================================================================ */}
      <section>
        <h2 className="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">
          System Health
        </h2>
        <LoadingWrap isLoading={otelStats.isLoading || otelHealth.isLoading}>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card
              title="Error Rate"
              value={otelStats.error ? 'N/A' : `${errorRate.toFixed(1)}%`}
              subtitle={otelStats.error ? 'OTel unavailable' : `${fmt(errorSpans)} error spans`}
              icon={AlertTriangle}
              gradient={otelStats.error ? 'none' : errorRateGradient(errorRate)}
            />
            <Card
              title="P99 Latency"
              value={otelHealth.error ? 'N/A' : p99 > 0 ? `${p99}ms` : '--'}
              subtitle={otelHealth.error ? 'OTel unavailable' : 'milliseconds'}
              icon={Activity}
              gradient={otelHealth.error ? 'none' : latencyGradient(p99)}
            />
            <Card
              title="Services Up"
              value={otelStats.error ? 'N/A' : `${servicesUp}/${servicesTotal}`}
              subtitle={otelStats.error ? 'OTel unavailable' : 'active services'}
              icon={Server}
              gradient={
                otelStats.error
                  ? 'none'
                  : servicesUp >= servicesTotal && servicesTotal > 0
                    ? 'green'
                    : 'amber'
              }
            />
            <Card
              title="Traces 24h"
              value={otelStats.error ? 'N/A' : fmt(totalTraces)}
              subtitle={otelStats.error ? 'OTel unavailable' : 'total traces'}
              icon={BarChart3}
              gradient="blue"
            />
          </div>
        </LoadingWrap>
      </section>

      {/* ================================================================ */}
      {/* Row 2 — Coverage Cards                                           */}
      {/* ================================================================ */}
      <section>
        <h2 className="text-xs font-semibold uppercase tracking-wider text-text-muted mb-3">
          Coverage
        </h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <LoadingWrap isLoading={codeStats.isLoading}>
            <Card
              title="Code Entities"
              value={codeStats.error ? 'N/A' : fmt(codeEntities)}
              subtitle={codeStats.error ? 'Code subsystem unavailable' : 'indexed entities'}
              icon={Code2}
            />
          </LoadingWrap>
          <LoadingWrap isLoading={docsStats.isLoading}>
            <Card
              title="Documents"
              value={docsStats.error ? 'N/A' : fmt(docCount)}
              subtitle={docsStats.error ? 'Docs subsystem unavailable' : 'indexed documents'}
              icon={FileText}
            />
          </LoadingWrap>
          <LoadingWrap isLoading={otelStats.isLoading}>
            <Card
              title="Services"
              value={otelStats.error ? 'N/A' : fmt(serviceCount)}
              subtitle={otelStats.error ? 'OTel unavailable' : 'monitored services'}
              icon={Layers}
            />
          </LoadingWrap>
          <LoadingWrap isLoading={codeStats.isLoading}>
            <Card
              title="Relations"
              value={codeStats.error ? 'N/A' : fmt(relationsCount)}
              subtitle={codeStats.error ? 'Code subsystem unavailable' : 'dependencies & calls'}
              icon={GitBranch}
            />
          </LoadingWrap>
        </div>
      </section>

      {/* ================================================================ */}
      {/* Row 3 — Charts                                                   */}
      {/* ================================================================ */}
      <section className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Panel title="Trace Volume (24h)">
          <TraceVolumeChart />
        </Panel>
        <Panel title="Entity Type Breakdown">
          <LoadingWrap isLoading={codeStats.isLoading}>
            <EntityBreakdownChart data={entityBreakdown} />
          </LoadingWrap>
        </Panel>
      </section>
    </div>
  );
}
