'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Bug, Cpu, Box, CircuitBoard, Sparkles } from 'lucide-react';
import { useCombatStore } from '@/lib/game/stores';
import {
  ALL_CORES,
  ALL_FRAMES,
  ALL_MIND_CIRCUITS,
  ALL_GOLEM_ENCHANTMENTS,
  type CoreDefinition,
  type FrameDefinition,
  type MindCircuitDefinition,
  type GolemEnchantmentDefinition,
} from '@/lib/game/data/golems';
import { DebugName } from '@/components/game/debug/debug-context';

function formatCost(cost: { type: string; element?: string; amount: number }): string {
  if (cost.type === 'raw') return `${cost.amount} raw`;
  return `${cost.amount} ${cost.element ?? 'unknown'}`;
}

function formatUnlock(req: {
  type: string;
  attunement?: string;
  level?: number;
  manaType?: string;
  attunements?: string[];
  levels?: number[];
}): string {
  switch (req.type) {
    case 'attunement_level':
      return `${req.attunement} Lv${req.level}`;
    case 'mana_unlocked':
      return `Unlock ${req.manaType} mana`;
    case 'dual_attunement':
      return `${req.attunements?.[0]} Lv${req.levels?.[0]} + ${req.attunements?.[1]} Lv${req.levels?.[1]}`;
    case 'guardian_pact':
      return `Guardian: ${req.attunements?.[0]} Lv${req.levels?.[0]} + ${req.attunements?.[1]} Lv${req.levels?.[1]}`;
    default:
      return req.type;
  }
}

function formatCosts(costs: { type: string; element?: string; amount: number }[]): string {
  return costs.map(formatCost).join(', ');
}

function CoreCard({ core }: { core: CoreDefinition }) {
  return (
    <div className="p-2 rounded border border-gray-700 bg-gray-800/40">
      <div className="text-sm font-medium text-amber-300">{core.name}</div>
      <div className="text-xs text-gray-400 mt-0.5">{core.description}</div>
      <div className="text-xs text-gray-500 mt-1 space-y-0.5">
        <div>Tier {core.tier} · Primary: {core.primaryManaType}</div>
        <div>Capacity: {core.manaCapacity} · Regen: {core.manaRegen}/h · Duration: {core.maxRoomDuration} rooms</div>
        <div>Types: {core.manaTypes.join(', ')}</div>
        <div>Cost: {formatCosts(core.summonCost)}</div>
        <div className="text-yellow-500/70">Unlock: {formatUnlock(core.unlockRequirement)}</div>
      </div>
    </div>
  );
}

function FrameCard({ frame }: { frame: FrameDefinition }) {
  return (
    <div className="p-2 rounded border border-gray-700 bg-gray-800/40">
      <div className="text-sm font-medium text-sky-300">{frame.name}</div>
      <div className="text-xs text-gray-400 mt-0.5">{frame.description}</div>
      <div className="text-xs text-gray-500 mt-1 space-y-0.5">
        <div>Element: {frame.element} · Special: {frame.specialEffect}</div>
        <div>DMG: {frame.baseDamage} · SPD: {frame.attackSpeed} · AoE: {frame.aoeTargets}</div>
        <div>ArmorPierce: {(frame.armorPierce * 100).toFixed(0)}% · MagicAffinity: {(frame.magicAffinity * 100).toFixed(0)}%</div>
        <div>Cost: {formatCosts(frame.summonCost)}</div>
        <div className="text-yellow-500/70">Unlock: {formatUnlock(frame.unlockRequirement)}</div>
      </div>
    </div>
  );
}

function MindCircuitCard({ circuit }: { circuit: MindCircuitDefinition }) {
  return (
    <div className="p-2 rounded border border-gray-700 bg-gray-800/40">
      <div className="text-sm font-medium text-violet-300">{circuit.name}</div>
      <div className="text-xs text-gray-400 mt-0.5">{circuit.description}</div>
      <div className="text-xs text-gray-500 mt-1 space-y-0.5">
        <div>Behavior: {circuit.behavior} · Spell Slots: {circuit.spellSlots}</div>
        <div>Cost: {formatCosts(circuit.summonCost)}</div>
        <div className="text-yellow-500/70">Unlock: {formatUnlock(circuit.unlockRequirement)}</div>
      </div>
    </div>
  );
}

function EnchantmentCard({ enchant }: { enchant: GolemEnchantmentDefinition }) {
  return (
    <div className="p-2 rounded border border-gray-700 bg-gray-800/40">
      <div className="text-sm font-medium text-emerald-300">{enchant.name}</div>
      <div className="text-xs text-gray-400 mt-0.5">{enchant.description}</div>
      <div className="text-xs text-gray-500 mt-1 space-y-0.5">
        <div>Effect: {enchant.effect} · Capacity Cost: {enchant.capacityCost}</div>
        <div>Cost: {formatCosts(enchant.summonCost)}</div>
      </div>
    </div>
  );
}

export function GolemDebugSection() {
  const golemLoadout = useCombatStore((s) => s.golemancy?.golemLoadout) ?? [];
  const golemDesigns = useCombatStore((s) => s.golemancy?.golemDesigns) ?? {};
  const toggleGolemLoadoutEntry = useCombatStore((s) => s.toggleGolemLoadoutEntry);
  const addGolemDesign = useCombatStore((s) => s.addGolemDesign);

  const allComponentIds = [
    ...ALL_CORES.map((c) => c.id),
    ...ALL_FRAMES.map((f) => f.id),
    ...ALL_MIND_CIRCUITS.map((m) => m.id),
    ...ALL_GOLEM_ENCHANTMENTS.map((e) => e.id),
  ];

  const handleCreateTestDesigns = () => {
    // Create a test design from the first core/frame/circuit
    const core = ALL_CORES[0];
    const frame = ALL_FRAMES[0];
    const circuit = ALL_MIND_CIRCUITS[0];
    if (!core || !frame || !circuit) return;

    addGolemDesign({
      id: `test-design-${Date.now()}`,
      name: `Test ${core.name} ${frame.name}`,
      coreId: core.id,
      frameId: frame.id,
      mindCircuitId: circuit.id,
      enchantmentIds: [],
      selectedManaTypes: core.manaTypes.slice(0, 1),
      selectedSpells: [],
    });
  };

  const handleClearLoadout = () => {
    // Disable all loadout entries
    for (const entry of golemLoadout) {
      if (entry.enabled) {
        toggleGolemLoadoutEntry(entry.designId);
      }
    }
  };

  const enabledCount = golemLoadout.filter((e) => e.enabled).length;

  return (
    <DebugName name="GolemDebugSection">
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-orange-400 text-sm flex items-center gap-2">
            <Bug className="w-4 h-4" />
            Golem Debug — Component System
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex gap-2 flex-wrap">
            <Button size="sm" variant="outline" onClick={handleCreateTestDesigns}>
              Create Test Design
            </Button>
            <Button size="sm" variant="outline" onClick={handleClearLoadout}>
              Disable All Loadout
            </Button>
          </div>
          <div className="text-xs text-gray-400">
            Designs: {Object.keys(golemDesigns).length} · Loadout: {enabledCount} / {golemLoadout.length} enabled
          </div>

          {/* ─── Cores ─────────────────────────────────────────────── */}
          <div>
            <div className="text-xs font-semibold text-amber-400 uppercase tracking-wider mb-2 flex items-center gap-1.5">
              <Cpu className="w-3.5 h-3.5" /> Cores ({ALL_CORES.length})
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-52 overflow-y-auto">
              {ALL_CORES.map((core) => (
                <div key={core.id} className="relative">
                  <CoreCard core={core} />
                </div>
              ))}
            </div>
          </div>

          {/* ─── Frames ────────────────────────────────────────────── */}
          <div>
            <div className="text-xs font-semibold text-sky-400 uppercase tracking-wider mb-2 flex items-center gap-1.5">
              <Box className="w-3.5 h-3.5" /> Frames ({ALL_FRAMES.length})
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 max-h-64 overflow-y-auto">
              {ALL_FRAMES.map((frame) => (
                <div key={frame.id} className="relative">
                  <FrameCard frame={frame} />
                </div>
              ))}
            </div>
          </div>

          {/* ─── Mind Circuits ─────────────────────────────────────── */}
          <div>
            <div className="text-xs font-semibold text-violet-400 uppercase tracking-wider mb-2 flex items-center gap-1.5">
              <CircuitBoard className="w-3.5 h-3.5" /> Mind Circuits ({ALL_MIND_CIRCUITS.length})
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 max-h-44 overflow-y-auto">
              {ALL_MIND_CIRCUITS.map((circuit) => (
                <div key={circuit.id} className="relative">
                  <MindCircuitCard circuit={circuit} />
                </div>
              ))}
            </div>
          </div>

          {/* ─── Enchantments ──────────────────────────────────────── */}
          <div>
            <div className="text-xs font-semibold text-emerald-400 uppercase tracking-wider mb-2 flex items-center gap-1.5">
              <Sparkles className="w-3.5 h-3.5" /> Enchantments ({ALL_GOLEM_ENCHANTMENTS.length})
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 max-h-52 overflow-y-auto">
              {ALL_GOLEM_ENCHANTMENTS.map((enchant) => (
                <div key={enchant.id} className="relative">
                  <EnchantmentCard enchant={enchant} />
                </div>
              ))}
            </div>
          </div>
        </CardContent>
      </Card>
    </DebugName>
  );
}

GolemDebugSection.displayName = 'GolemDebugSection';
