'use client';

import { useCombatStore, useManaStore, canAffordSpellCost } from '@/lib/game/stores';
import { SPELLS_DEF, ELEMENTS } from '@/lib/game/constants';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { CORES, FRAMES } from '@/lib/game/data/golems';
import { DebugName } from '@/components/game/debug/debug-context';

interface SpireCombatControlsProps {
  castProgress: number;
  isChanneling: boolean;
  channelSpeedMultiplier: number;
}

function formatSpellCost(cost: { type: 'raw' | 'element'; element?: string; amount: number }): string {
  if (cost.type === 'raw') return `${cost.amount} raw`;
  const elemDef = ELEMENTS[cost.element || ''];
  return `${cost.amount} ${elemDef?.sym || '?'}`;
}

export function SpireCombatControls({ castProgress, isChanneling, channelSpeedMultiplier }: SpireCombatControlsProps) {
  const spells = useCombatStore((s) => s.spells);
  const activeSpell = useCombatStore((s) => s.activeSpell);
  const setSpell = useCombatStore((s) => s.setSpell);
  const golemancy = useCombatStore((s) => s.golemancy);
  const invocationCharge = useCombatStore((s) => s.invocationCharge);
  const activeInvocation = useCombatStore((s) => s.activeInvocation);
  const rawMana = useManaStore((s) => s.rawMana);
  const elements = useManaStore((s) => s.elements);

  const learnedSpells = Object.entries(spells)
    .filter(([, state]) => state?.learned)
    .map(([id]) => id);

  const activeGolems = golemancy.activeGolems || [];
  const golemDesigns = golemancy.golemDesigns || [];

  const isInvoking = activeInvocation !== null;

  return (
    <DebugName name="SpireCombatControls">
    <div className="space-y-4">
      {/* Invocation Compact Status Indicator (§11.2) */}
      <Card className={`border-purple-700 transition-all ${isInvoking ? 'bg-purple-950/40 ring-1 ring-purple-500/50 shadow-[0_0_12px_rgba(168,85,247,0.3)]' : 'bg-gray-900/80 border-gray-700'}`}>
        <CardContent className="p-2 space-y-1.5">
          <div className="flex items-center justify-between">
            <span className="text-xs font-medium text-purple-300">💜 Invocation</span>
            <span className={`text-xs font-medium ${isInvoking ? 'text-purple-300' : 'text-gray-500'}`}>
              {isInvoking ? 'ACTIVE' : `${Math.round(invocationCharge)}%`}
            </span>
          </div>
          <Progress
            value={invocationCharge}
            className="h-1.5 bg-gray-800"
            style={{ '--progress-bg': isInvoking ? '#A855F7' : '#7C3AED' } as React.CSSProperties}
          />
          {!isInvoking && invocationCharge < 100 && (
            <div className="text-[10px] text-gray-500 text-right">
              Recharging... +{(invocationCharge).toFixed(0)}→100
            </div>
          )}
          {!isInvoking && invocationCharge >= 100 && (
            <div className="text-[10px] text-purple-400 text-right">
              ✦ Ready to invoke!
            </div>
          )}
        </CardContent>
      </Card>

      {/* Transference Channel Status Indicator */}
      {isChanneling && (
        <Card className="border-teal-700 bg-teal-950/40 ring-1 ring-teal-500/50 shadow-[0_0_12px_rgba(26,188,156,0.3)]">
          <CardContent className="p-2">
            <div className="flex items-center justify-between">
              <span className="text-xs font-medium text-teal-300">⚡ Channeling</span>
              <span className="text-xs text-teal-400">{channelSpeedMultiplier.toFixed(2)}×</span>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Active Spell Panel */}
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm text-amber-400">🔮 Active Spells</CardTitle>
        </CardHeader>
        <CardContent className="space-y-2">
          {/* Cast progress */}
          <div>
            <div className="flex items-center justify-between text-xs mb-1">
              <span className="text-gray-400">Cast Progress</span>
              <span className="text-gray-500">{Math.round(castProgress * 100)}%</span>
            </div>
            <Progress
              value={castProgress * 100}
              className="h-2 bg-gray-800"
              style={{ '--progress-bg': '#F59E0B' } as React.CSSProperties}
            />
          </div>

          {/* Spell selection */}
          <div className="grid grid-cols-1 gap-1.5 max-h-48 overflow-y-auto">
            {learnedSpells.map((spellId) => {
              const def = SPELLS_DEF[spellId];
              if (!def) return null;
              const isActive = activeSpell === spellId;
              const canCast = canAffordSpellCost(def.cost, rawMana, elements);
              const elemDef = def.elem === 'raw' ? null : ELEMENTS[def.elem];

              return (
                <button
                  key={spellId}
                  onClick={() => setSpell(spellId)}
                  className={`flex items-center justify-between p-2 rounded text-xs transition-colors ${
                    isActive
                      ? 'bg-amber-900/40 border border-amber-600'
                      : canCast
                        ? 'bg-gray-800/50 border border-gray-700 hover:border-gray-500'
                        : 'bg-gray-800/30 border border-gray-800 opacity-50'
                  }`}
                >
                  <div className="flex items-center gap-2">
                    {elemDef && <span>{elemDef.sym}</span>}
                    <span className={isActive ? 'text-amber-300 font-medium' : 'text-gray-300'}>
                      {def.name}
                    </span>
                  </div>
                  <span className="text-gray-500">
                    {formatSpellCost(def.cost)}
                  </span>
                </button>
              );
            })}
          </div>

          {learnedSpells.length === 0 && (
            <div className="text-xs text-gray-500 italic">No spells learned yet.</div>
          )}
        </CardContent>
      </Card>

      {/* Golem Status Panel */}
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm text-blue-400">🗿 Golems</CardTitle>
        </CardHeader>
        <CardContent>
          {activeGolems.length === 0 ? (
            <div className="text-xs text-gray-500 italic">No golems summoned.</div>
          ) : (
            <div className="space-y-2">
              {activeGolems.map((ag) => {
                const design = golemDesigns[ag.designId];
                if (!design) return null;
                const frame = FRAMES[design.frameId];
                const core = CORES[design.coreId];
                const elemColor = frame?.element ? ELEMENTS[frame.element]?.color || '#888' : '#888';

                return (
                  <div
                    key={ag.designId + ag.summonedFloor}
                    className="flex items-center justify-between p-2 bg-gray-800/50 rounded border border-gray-700/50"
                  >
                    <div className="flex items-center gap-2">
                      <span style={{ color: elemColor }}>●</span>
                      <span className="text-xs text-gray-200">{design.name}</span>
                    </div>
                    <div className="text-xs text-gray-500">
                      {frame?.baseDamage ?? '?'} dmg · {core?.manaRegen ?? '?'} mp
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
    </DebugName>
  );
}
