import { useGameStore } from '@/store';
import { formatMoney, formatNumber, formatFlops, formatPercent } from '@ai-tycoon/shared';

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="mb-3">
      <div className="text-[10px] uppercase tracking-wider text-surface-500 mb-1 font-semibold">{title}</div>
      <div className="grid grid-cols-2 gap-x-4 gap-y-0.5">{children}</div>
    </div>
  );
}

function Stat({ label, value }: { label: string; value: string | number }) {
  return (
    <>
      <span className="text-xs text-surface-400">{label}</span>
      <span className="text-xs font-mono text-surface-100 text-right">{value}</span>
    </>
  );
}

export function StateInspectionTab() {
  const meta = useGameStore((s) => s.meta);
  const economy = useGameStore((s) => s.economy);
  const compute = useGameStore((s) => s.compute);
  const market = useGameStore((s) => s.market);
  const infrastructure = useGameStore((s) => s.infrastructure);
  const reputation = useGameStore((s) => s.reputation);
  const research = useGameStore((s) => s.research);
  const models = useGameStore((s) => s.models);

  const totalFailedRacks = infrastructure.clusters.reduce((sum, cl) =>
    sum + cl.campuses.reduce((s2, ca) =>
      s2 + ca.dataCenters.reduce((s3, dc) => s3 + dc.computeRacksFailed, 0), 0), 0);

  const totalOnlineRacks = infrastructure.clusters.reduce((sum, cl) =>
    sum + cl.campuses.reduce((s2, ca) =>
      s2 + ca.dataCenters.reduce((s3, dc) => s3 + dc.computeRacksOnline, 0), 0), 0);

  const pipelineRacks = infrastructure.clusters.reduce((sum, cl) =>
    sum + cl.campuses.reduce((s2, ca) =>
      s2 + ca.dataCenters.reduce((s3, dc) =>
        s3 + dc.deploymentCohorts.reduce((s4, co) => s4 + co.count, 0), 0), 0), 0);

  return (
    <div className="space-y-1">
      <Section title="Meta">
        <Stat label="Era" value={meta.currentEra} />
        <Stat label="Tick" value={formatNumber(meta.tickCount)} />
        <Stat label="Speed" value={`${meta.gameSpeed}x`} />
        <Stat label="Paused" value={meta.isPaused ? 'Yes' : 'No'} />
      </Section>

      <Section title="Economy">
        <Stat label="Money" value={formatMoney(economy.money)} />
        <Stat label="Revenue/tick" value={formatMoney(economy.revenuePerTick)} />
        <Stat label="Expenses/tick" value={formatMoney(economy.expensesPerTick)} />
        <Stat label="Total Revenue" value={formatMoney(economy.totalRevenue)} />
        <Stat label="Valuation" value={formatMoney(economy.funding.valuation)} />
        <Stat label="Equity" value={formatPercent(economy.funding.founderEquity)} />
      </Section>

      <Section title="Compute">
        <Stat label="Total FLOPS" value={formatFlops(compute.totalFlops)} />
        <Stat label="Training FLOPS" value={formatFlops(compute.totalTrainingFlops)} />
        <Stat label="Inference FLOPS" value={formatFlops(compute.totalInferenceFlops)} />
        <Stat label="Eff. Training" value={formatFlops(compute.effectiveTrainingFlops)} />
        <Stat label="Eff. Inference" value={formatFlops(compute.effectiveInferenceFlops)} />
        <Stat label="VRAM" value={`${formatNumber(compute.totalVramGB)} GB`} />
        <Stat label="Utilization" value={formatPercent(compute.inferenceUtilization)} />
        <Stat label="Training Alloc" value={formatPercent(compute.trainingAllocation)} />
        <Stat label="Inference Alloc" value={formatPercent(compute.inferenceAllocation)} />
        <Stat label="Capacity" value={`${formatNumber(compute.tokensPerSecondCapacity)} tok/s`} />
        <Stat label="Demand" value={`${formatNumber(compute.tokensPerSecondDemand)} tok/s`} />
      </Section>

      <Section title="Market">
        <Stat label="Subscribers" value={formatNumber(market.consumerTiers.totalUsers)} />
        <Stat label="Satisfaction" value={formatPercent(market.consumerTiers.satisfaction)} />
        <Stat label="Viral Coeff" value={market.consumerTiers.viralCoefficient.toFixed(4)} />
        <Stat label="Contracts" value={market.enterprise.activeContracts.length} />
        <Stat label="API tok/tick" value={formatNumber(market.enterprise.totalApiCallsPerTick)} />
      </Section>

      <Section title="Infrastructure">
        <Stat label="Clusters" value={infrastructure.clusters.length} />
        <Stat label="Data Centers" value={infrastructure.totalDataCenterCount} />
        <Stat label="Racks Online" value={totalOnlineRacks} />
        <Stat label="Racks Failed" value={totalFailedRacks} />
        <Stat label="In Pipeline" value={pipelineRacks} />
        <Stat label="Total FLOPS" value={formatFlops(infrastructure.totalFlops)} />
        <Stat label="Training FLOPS" value={formatFlops(infrastructure.totalTrainingFlops)} />
        <Stat label="Inference FLOPS" value={formatFlops(infrastructure.totalInferenceFlops)} />
        <Stat label="Total VRAM" value={`${formatNumber(infrastructure.totalVramGB)} GB`} />
      </Section>

      <Section title="Reputation">
        <Stat label="Score" value={reputation.score} />
        <Stat label="Safety" value={reputation.safetyRecord} />
        <Stat label="Public" value={reputation.publicPerception} />
        <Stat label="Employee" value={reputation.employeeSatisfaction.toFixed(1)} />
        <Stat label="Regulatory" value={reputation.regulatoryStanding.toFixed(1)} />
      </Section>

      <Section title="Research & Models">
        <Stat label="Completed" value={research.completedResearch.length} />
        <Stat label="Points" value={research.researchPoints.toFixed(1)} />
        <Stat label="Active" value={research.activeResearch?.researchId ?? 'None'} />
        <Stat label="Models" value={models.baseModels.length} />
        <Stat label="Training" value={models.activeTrainingPipelines.filter(p => p.status === 'active').length} />
        <Stat label="Deployed" value={models.baseModels.filter(m => m.isDeployed).length} />
      </Section>
    </div>
  );
}
