'use client';

import React, { useState, useCallback, useMemo } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { useCombatStore } from '@/lib/game/stores/combatStore';
import { useAttunementStore } from '@/lib/game/stores/attunementStore';
import { useManaStore } from '@/lib/game/stores/manaStore';
import { usePrestigeStore } from '@/lib/game/stores/prestigeStore';
import { computeDisciplineEffects } from '@/lib/game/effects/discipline-effects';
import {
  CORES, FRAMES, MIND_CIRCUITS, GOLEM_ENCHANTMENTS,
  ALL_CORES, ALL_FRAMES, ALL_MIND_CIRCUITS, ALL_GOLEM_ENCHANTMENTS,
} from '@/lib/game/data/golems';
import {
  getGolemSlots,
  isComponentUnlocked,
  computeGolemStats,
  canAffordGolemDesign,
} from '@/lib/game/data/golems/utils';
import type { ComputedGolemStats, GolemEnchantmentDefinition } from '@/lib/game/data/golems/types';
import type { BuilderSection } from './golemancy/types';
import { GolemDesignBuilder } from './golemancy/GolemDesignBuilder';
import { GolemLoadoutPanel } from './golemancy/GolemLoadoutPanel';
import { ActiveGolemsPanel } from './golemancy/ActiveGolemsPanel';
import { serializeDesign, buildGolemDesign } from './golemancy/golemancy-utils';
import clsx from 'clsx';

export const GolemancyTab: React.FC = () => {
  const [activeSection, setActiveSection] = useState<BuilderSection>('builder');

  // Builder state
  const [selectedCoreId, setSelectedCoreId] = useState<string | null>(null);
  const [selectedFrameId, setSelectedFrameId] = useState<string | null>(null);
  const [selectedCircuitId, setSelectedCircuitId] = useState<string | null>(null);
  const [selectedEnchantmentIds, setSelectedEnchantmentIds] = useState<string[]>([]);
  const [designName, setDesignName] = useState('');
  const [selectedManaTypes, setSelectedManaTypes] = useState<string[]>([]);
  const [selectedSpells, setSelectedSpells] = useState<string[]>([]);

  // Store access
  const { golemancy, addGolemDesign, removeGolemDesign, toggleGolemLoadoutEntry } = useCombatStore(
    useShallow(s => ({
      golemancy: s.golemancy,
      addGolemDesign: s.addGolemDesign,
      removeGolemDesign: s.removeGolemDesign,
      toggleGolemLoadoutEntry: s.toggleGolemLoadoutEntry,
    })),
  );
  const attunements = useAttunementStore(s => s.attunements);
  const { rawMana, elements } = useManaStore(useShallow(s => ({
    rawMana: s.rawMana,
    elements: s.elements,
  })));
  const signedPacts = usePrestigeStore(s => s.signedPacts);

  // Derived data
  const attunementLookup = useMemo(() => {
    const lookup: Record<string, { active: boolean; level: number }> = {};
    for (const [id, att] of Object.entries(attunements)) {
      lookup[id] = { active: att.active, level: att.level };
    }
    return lookup;
  }, [attunements]);

  const unlockedElements = useMemo(
    () => Object.entries(elements).filter(([, e]) => e.unlocked).map(([k]) => k),
    [elements],
  );

  const fabricatorLevel = attunements.fabricator?.level ?? 0;
  const baseGolemSlots = getGolemSlots(fabricatorLevel);
  const discEffects = computeDisciplineEffects();
  const discSlotBonus = Math.floor(discEffects.bonuses.golemCapacity || 0);
  const golemSlots = Math.min(7, baseGolemSlots + discSlotBonus);
  const enabledCount = golemancy.golemLoadout.filter(e => e.enabled).length;

  // Unlock checks
  const unlockedCoreIds = useMemo(() => {
    const set = new Set<string>();
    for (const core of ALL_CORES) {
      if (isComponentUnlocked(core.unlockRequirement, attunementLookup, unlockedElements, signedPacts)) {
        set.add(core.id);
      }
    }
    return set;
  }, [attunementLookup, unlockedElements, signedPacts]);

  const unlockedFrameIds = useMemo(() => {
    const set = new Set<string>();
    for (const frame of ALL_FRAMES) {
      if (isComponentUnlocked(frame.unlockRequirement, attunementLookup, unlockedElements, signedPacts)) {
        set.add(frame.id);
      }
    }
    return set;
  }, [attunementLookup, unlockedElements, signedPacts]);

  const unlockedCircuitIds = useMemo(() => {
    const set = new Set<string>();
    for (const circuit of ALL_MIND_CIRCUITS) {
      if (isComponentUnlocked(circuit.unlockRequirement, attunementLookup, unlockedElements, signedPacts)) {
        set.add(circuit.id);
      }
    }
    return set;
  }, [attunementLookup, unlockedElements, signedPacts]);

  // Selected components
  const selectedCore = selectedCoreId ? CORES[selectedCoreId] ?? null : null;
  const selectedFrame = selectedFrameId ? FRAMES[selectedFrameId] ?? null : null;
  const selectedCircuit = selectedCircuitId ? MIND_CIRCUITS[selectedCircuitId] ?? null : null;
  const selectedEnchantments = selectedEnchantmentIds
    .map(id => GOLEM_ENCHANTMENTS[id])
    .filter(Boolean) as GolemEnchantmentDefinition[];

  // Computed stats preview
  const computedStats = useMemo<ComputedGolemStats | null>(() => {
    if (!selectedCore || !selectedFrame || !selectedCircuit) return null;
    const design = buildGolemDesign(
      selectedCore, selectedFrame, selectedCircuit,
      selectedEnchantments, selectedManaTypes, selectedSpells,
    );
    return computeGolemStats(design);
  }, [selectedCore, selectedFrame, selectedCircuit, selectedEnchantments, selectedManaTypes, selectedSpells]);

  const affordability = useMemo(() => {
    if (!selectedCore || !selectedFrame || !selectedCircuit) {
      return { canAfford: false, missing: 'Select all required components' };
    }
    const design = buildGolemDesign(
      selectedCore, selectedFrame, selectedCircuit,
      selectedEnchantments, selectedManaTypes, selectedSpells,
    );
    return canAffordGolemDesign(design, rawMana, elements);
  }, [selectedCore, selectedFrame, selectedCircuit, selectedEnchantments, selectedManaTypes, selectedSpells, rawMana, elements]);

  // Enchantment capacity check
  const enchantmentCapacity = computedStats?.enchantmentCapacity ?? 0;
  const usedEnchantmentCapacity = selectedEnchantments.reduce((sum, e) => sum + e.capacityCost, 0);

  // Handlers
  const handleToggleEnchantment = useCallback((id: string) => {
    setSelectedEnchantmentIds(prev =>
      prev.includes(id) ? prev.filter(eid => eid !== id) : [...prev, id],
    );
  }, []);

  const handleToggleManaType = useCallback((type: string) => {
    setSelectedManaTypes(prev => {
      if (prev.includes(type)) return prev.filter(t => t !== type);
      const core = selectedCoreId ? CORES[selectedCoreId] : null;
      const slots = core?.id === 'intermediate' ? 2 : core?.id === 'advanced' ? 3 : core?.id === 'guardian' ? 4 : 0;
      if (prev.length >= slots) return prev;
      return [...prev, type];
    });
  }, [selectedCoreId]);

  const handleToggleSpell = useCallback((spellName: string) => {
    setSelectedSpells(prev => {
      if (prev.includes(spellName)) return prev.filter(s => s !== spellName);
      const slots = selectedCircuit?.spellSlots ?? 0;
      if (prev.length >= slots) return prev;
      return [...prev, spellName];
    });
  }, [selectedCircuit]);

  const handleSaveDesign = useCallback(() => {
    if (!selectedCore || !selectedFrame || !selectedCircuit) return;
    const name = designName.trim() || `${selectedCore.name.split(' ')[0]} ${selectedFrame.name.split(' ')[0]}`;
    const serialized = serializeDesign(
      name, selectedCore, selectedFrame, selectedCircuit,
      selectedEnchantments, selectedManaTypes, selectedSpells,
    );
    addGolemDesign(serialized);
    setDesignName('');
    setSelectedEnchantmentIds([]);
    setSelectedManaTypes([]);
    setSelectedSpells([]);
  }, [designName, selectedCore, selectedFrame, selectedCircuit, selectedEnchantments, selectedManaTypes, selectedSpells, addGolemDesign]);

  const handleRemoveLoadoutEntry = useCallback((designId: string) => {
    removeGolemDesign(designId);
  }, [removeGolemDesign]);

  const handleToggleLoadoutEntry = useCallback((designId: string) => {
    toggleGolemLoadoutEntry(designId);
  }, [toggleGolemLoadoutEntry]);

  return (
    <div className="space-y-4">
      {/* Header info */}
      <div className="text-sm text-gray-400 space-y-1">
        <p>
          Design custom golems from components. Enabled golems are automatically
          summoned when entering the spire if you can afford the cost.
        </p>
        <div className="flex gap-4 text-xs">
          <span>Slots: {enabledCount}/{golemSlots}{discSlotBonus > 0 ? <span className="text-green-400"> (+{discSlotBonus} discipline)</span> : null}</span>
          <span>Active: {golemancy.activeGolems.length}</span>
          <span>Designs: {Object.keys(golemancy.golemDesigns).length}</span>
        </div>
      </div>

      {/* Section tabs */}
      <div className="flex gap-2">
        {([
          { key: 'builder', label: 'Design Builder' },
          { key: 'loadout', label: `Loadout (${golemancy.golemLoadout.length})` },
          { key: 'active', label: `Active (${golemancy.activeGolems.length})` },
        ] as const).map(({ key, label }) => (
          <button
            key={key}
            onClick={() => setActiveSection(key)}
            className={clsx(
              'rounded px-3 py-1 text-xs font-medium transition-colors',
              activeSection === key
                ? 'bg-blue-600 text-white'
                : 'text-gray-400 hover:text-gray-200',
            )}
          >
            {label}
          </button>
        ))}
      </div>

      {/* ─── Builder Section ─────────────────────────────────────────────── */}
      {activeSection === 'builder' && (
        <GolemDesignBuilder
          selectedCoreId={selectedCoreId}
          selectedFrameId={selectedFrameId}
          selectedCircuitId={selectedCircuitId}
          selectedEnchantmentIds={selectedEnchantmentIds}
          selectedSpells={selectedSpells}
          designName={designName}
          selectedManaTypes={selectedManaTypes}
          unlockedCoreIds={unlockedCoreIds}
          unlockedFrameIds={unlockedFrameIds}
          unlockedCircuitIds={unlockedCircuitIds}
          computedStats={computedStats}
          affordability={affordability}
          enchantmentCapacity={enchantmentCapacity}
          usedEnchantmentCapacity={usedEnchantmentCapacity}
          golemSlots={golemSlots}
          enabledCount={enabledCount}
          onSelectCore={setSelectedCoreId}
          onSelectFrame={setSelectedFrameId}
          onSelectCircuit={setSelectedCircuitId}
          onToggleEnchantment={handleToggleEnchantment}
          onToggleSpell={handleToggleSpell}
          onToggleManaType={handleToggleManaType}
          onDesignNameChange={setDesignName}
          onSaveDesign={handleSaveDesign}
        />
      )}

      {/* ─── Loadout Section ─────────────────────────────────────────────── */}
      {activeSection === 'loadout' && (
        <GolemLoadoutPanel
          loadout={golemancy.golemLoadout}
          onToggle={handleToggleLoadoutEntry}
          onRemove={handleRemoveLoadoutEntry}
        />
      )}

      {/* ─── Active Golems Section ───────────────────────────────────────── */}
      {activeSection === 'active' && (
        <ActiveGolemsPanel activeGolems={golemancy.activeGolems} />
      )}
    </div>
  );
};

GolemancyTab.displayName = 'GolemancyTab';
