'use client';

import { ELEMENTS, GUARDIANS } from '@/lib/game/constants';
import { getTierMultiplier } from '@/lib/game/skill-evolution';
import { hasSpecial, SPECIAL_EFFECTS } from '@/lib/game/effects';
import { fmt, fmtDec } from '@/lib/game/store';
import type { GameStore, UnifiedEffects } from '@/lib/game/types';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import { FlaskConical, Trophy, RotateCcw } from 'lucide-react';
import { ManaStatsSection } from '../stats/ManaStatsSection';
import { ManaTypeBreakdown } from '../stats/ManaTypeBreakdown';
import { CombatStatsSection } from '../stats/CombatStatsSection';
import { StudyStatsSection } from '../stats/StudyStatsSection';
import { UpgradeEffectsSection } from '../stats/UpgradeEffectsSection';

export interface StatsTabProps {
  store: GameStore;
  upgradeEffects: UnifiedEffects;
  maxMana: number;
  baseRegen: number;
  clickMana: number;
  meditationMultiplier: number;
  effectiveRegen: number;
  incursionStrength: number;
  manaCascadeBonus: number;
  manaWaterfallBonus: number;
  hasManaWaterfall: boolean;
  hasFlowSurge: boolean;
  hasManaOverflow: boolean;
  hasEternalFlow: boolean;
  studySpeedMult: number;
  studyCostMult: number;
}

export function StatsTab({
  store,
  upgradeEffects,
  maxMana,
  baseRegen,
  clickMana,
  meditationMultiplier,
  effectiveRegen,
  incursionStrength,
  manaCascadeBonus,
  manaWaterfallBonus,
  hasManaWaterfall,
  hasFlowSurge,
  hasManaOverflow,
  hasEternalFlow,
  studySpeedMult,
  studyCostMult,
}: StatsTabProps) {
  // Compute element max
  const elemMax = (() => {
    const ea = store.skillTiers?.elemAttune || 1;
    const tieredSkillId = ea > 1 ? `elemAttune_t${ea}` : 'elemAttune';
    const level = store.skills[tieredSkillId] || store.skills.elemAttune || 0;
    const tierMult = getTierMultiplier(tieredSkillId);
    return 10 + level * 50 * tierMult + (store.prestigeUpgrades.elementalAttune || 0) * 25;
  })();

  return (
    <div className="space-y-4">
      {/* Mana Stats */}
      <ManaStatsSection
        store={store}
        upgradeEffects={upgradeEffects}
        maxMana={maxMana}
        baseRegen={baseRegen}
        clickMana={clickMana}
        meditationMultiplier={meditationMultiplier}
        effectiveRegen={effectiveRegen}
        incursionStrength={incursionStrength}
        manaCascadeBonus={manaCascadeBonus}
        manaWaterfallBonus={manaWaterfallBonus}
        hasManaWaterfall={hasManaWaterfall}
        hasFlowSurge={hasFlowSurge}
        hasManaOverflow={hasManaOverflow}
        hasEternalFlow={hasEternalFlow}
      />

      {/* Mana Type Breakdown */}
      <ManaTypeBreakdown store={store} />

      {/* Combat Stats */}
      <CombatStatsSection store={store} />

      {/* Study Stats */}
      <StudyStatsSection
        store={store}
        studySpeedMult={studySpeedMult}
        studyCostMult={studyCostMult}
      />

      {/* Element Stats */}
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-green-400 game-panel-title text-xs flex items-center gap-2">
            <FlaskConical className="w-4 h-4" />
            Element Stats
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Element Capacity:</span>
                <span className="text-green-300">{elemMax}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Elem. Attunement Bonus:</span>
                <span className="text-green-300">
                  {(() => {
                    const ea = store.skillTiers?.elemAttune || 1;
                    const tieredSkillId = ea > 1 ? `elemAttune_t${ea}` : 'elemAttune';
                    const level = store.skills[tieredSkillId] || store.skills.elemAttune || 0;
                    const tierMult = getTierMultiplier(tieredSkillId);
                    return `+${level * 50 * tierMult}`;
                  })()}
                </span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Prestige Attunement:</span>
                <span className="text-green-300">+{(store.prestigeUpgrades.elementalAttune || 0) * 25}</span>
              </div>
            </div>
            <div className="space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Unlocked Elements:</span>
                <span className="text-green-300">{Object.values(store.elements).filter(e => e.unlocked).length} / {Object.keys(ELEMENTS).length}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Elem. Crafting Bonus:</span>
                <span className="text-green-300">×{fmtDec(1 + (store.skills.elemCrafting || 0) * 0.25, 2)}</span>
              </div>
            </div>
          </div>
          <Separator className="bg-gray-700 my-3" />
          <div className="text-xs text-gray-400 mb-2">Elemental Mana Pools:</div>
          <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 gap-2">
            {Object.entries(store.elements)
              .filter(([, state]) => state.unlocked)
              .map(([id, state]) => {
                const def = ELEMENTS[id];
                return (
                  <div key={id} className="p-2 rounded border border-gray-700 bg-gray-800/50 text-center">
                    <div className="text-lg">{def?.sym}</div>
                    <div className="text-xs text-gray-400">{state.current}/{state.max}</div>
                  </div>
                );
              })}
          </div>
        </CardContent>
      </Card>

      {/* Active Upgrades */}
      <UpgradeEffectsSection store={store} />

      {/* Enchantment Power (placeholder for Task 5) */}
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-blue-400 game-panel-title text-xs flex items-center gap-2">
            ✨ Enchantment Power
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex justify-between text-sm">
            <span className="text-gray-400">Enchantment Power:</span>
            <span className="text-blue-300 font-[var(--font-mono)]">
              {upgradeEffects?.enchantmentPowerMultiplier?.toFixed(2) || '1.0'}×
            </span>
          </div>
          <p className="text-xs text-gray-500 mt-2">
            Increases the power of all enchantments by {((upgradeEffects?.enchantmentPowerMultiplier || 1) - 1) * 100}%. Multiplier applied to all enchantment effects.
          </p>
        </CardContent>
      </Card>

      {/* Pact Bonuses */}
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-amber-400 game-panel-title text-xs flex items-center gap-2">
            <Trophy className="w-4 h-4" />
            Signed Pacts ({store.signedPacts.length}/10)
          </CardTitle>
        </CardHeader>
        <CardContent>
          {store.signedPacts.length === 0 ? (
            <div className="text-gray-500 text-sm">No pacts signed yet. Defeat guardians to earn pacts.</div>
          ) : (
            <div className="space-y-2">
              {store.signedPacts.map((floor) => {
                const guardian = GUARDIANS[floor];
                if (!guardian) return null;
                return (
                  <div
                    key={floor}
                    className="flex items-center justify-between p-2 rounded border"
                    style={{ borderColor: guardian.color, backgroundColor: `${guardian.color}15` }}
                  >
                    <div>
                      <div className="font-semibold text-sm" style={{ color: guardian.color }}>
                        {guardian.name}
                      </div>
                      <div className="text-xs text-gray-400">Floor {floor}</div>
                    </div>
                    <Badge className="bg-amber-900/50 text-amber-300">
                      {guardian.pact}x multiplier
                    </Badge>
                  </div>
                );
              })}
              <div className="flex justify-between text-sm font-semibold border-t border-gray-700 pt-2 mt-2">
                <span className="text-gray-300">Combined Pact Multiplier:</span>
                <span className="text-amber-400">×{fmtDec(store.signedPacts.reduce((m, f) => m * (GUARDIANS[f]?.pact || 1), 1), 2)}</span>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Loop Stats */}
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-purple-400 game-panel-title text-xs flex items-center gap-2">
            <RotateCcw className="w-4 h-4" />
            Loop Stats
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-2xl font-bold text-amber-400 game-mono">{store.loopCount}</div>
              <div className="text-xs text-gray-400">Loops Completed</div>
            </div>
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-2xl font-bold text-purple-400 game-mono">{fmt(store.insight)}</div>
              <div className="text-xs text-gray-400">Current Insight</div>
            </div>
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-2xl font-bold text-blue-400 game-mono">{fmt(store.totalInsight)}</div>
              <div className="text-xs text-gray-400">Total Insight</div>
            </div>
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-2xl font-bold text-green-400 game-mono">{store.maxFloorReached}</div>
              <div className="text-xs text-gray-400">Max Floor</div>
            </div>
          </div>
          <Separator className="bg-gray-700 my-3" />
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-xl font-bold text-gray-300 game-mono">{Object.values(store.spells).filter(s => s.learned).length}</div>
              <div className="text-xs text-gray-400">Spells Learned</div>
            </div>
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-xl font-bold text-gray-300 game-mono">{Object.values(store.skills).reduce((a, b) => a + b, 0)}</div>
              <div className="text-xs text-gray-400">Total Skill Levels</div>
            </div>
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-xl font-bold text-gray-300 game-mono">{fmt(store.totalManaGathered)}</div>
              <div className="text-xs text-gray-400">Total Mana Gathered</div>
            </div>
            <div className="p-3 bg-gray-800/50 rounded text-center">
              <div className="text-xl font-bold text-gray-300 game-mono">{store.memorySlots}</div>
              <div className="text-xs text-gray-400">Memory Slots</div>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

StatsTab.displayName = "StatsTab";
