'use client';

import { GameCard } from '@/components/ui/game-card';
import { Separator } from '@/components/ui/separator';
import type { DesignEffect, EquipmentCategory } from '@/lib/game/types';
import { EquipmentTypeSelector } from './EnchantmentDesigner/EquipmentTypeSelector';
import { EffectSelector } from './EnchantmentDesigner/EffectSelector';
import { SavedDesigns } from './EnchantmentDesigner/SavedDesigns';
import { DesignForm } from './EnchantmentDesigner/DesignForm';
import {
  getAvailableEffects,
  getIncompatibleEffects,
  getOwnedEquipmentTypes,
  getIncompatibilityReason,
  calculateDesignCapacityCost,
  getEquipmentCapacity,
  calculateDesignTime,
  addEffectToDesign,
  removeEffectFromDesign,
} from './EnchantmentDesigner/utils';
import { useCraftingStore, useAttunementStore } from '@/lib/game/stores';
import { DebugName } from '@/components/game/debug/debug-context';

export function EnchantmentDesigner() {
  // Attunement store — get Enchanter level for effect selector gating
  const enchanterLevel = useAttunementStore((s) => s.attunements?.enchanter?.level ?? 0);

  // Crafting store selectors — persisted selection state
  const selectedEquipmentType = useCraftingStore((s) => s.enchantmentSelection.selectedEquipmentType);
  const setSelectedEquipmentType = useCraftingStore((s) => s.setSelectedEquipmentType);
  const selectedEffects = useCraftingStore((s) => s.enchantmentSelection.selectedEffects);
  const setSelectedEffects = useCraftingStore((s) => s.setSelectedEffects);
  const designName = useCraftingStore((s) => s.enchantmentSelection.designName);
  const setDesignName = useCraftingStore((s) => s.setDesignName);
  const selectedDesign = useCraftingStore((s) => s.enchantmentSelection.selectedDesign);
  const setSelectedDesign = useCraftingStore((s) => s.setSelectedDesign);

  // Crafting store — other state
  const completedEnchantmentDesigns = useCraftingStore((s) => s.completedEnchantmentDesigns);
  const designProgress = useCraftingStore((s) => s.designProgress);
  const startDesigningEnchantment = useCraftingStore((s) => s.startDesigningEnchantment);
  const cancelDesign = useCraftingStore((s) => s.cancelDesign);
  const deleteDesign = useCraftingStore((s) => s.deleteDesign);
  const unlockedEffects = useCraftingStore((s) => s.unlockedEffects);
  const equipmentInstances = useCraftingStore((s) => s.equipmentInstances);

  // Calculate total capacity cost for current design
  const designCapacityCost = calculateDesignCapacityCost(selectedEffects, 0);

  // Get capacity limit for selected equipment type
  const selectedEquipmentCapacity = getEquipmentCapacity(selectedEquipmentType);

  // Calculate design time
  const designTime = calculateDesignTime(selectedEffects);

  // Add effect to design
  const addEffect = (effectId: string) => {
    addEffectToDesign(effectId, selectedEffects, 0, setSelectedEffects);
  };

  // Remove effect from design
  const removeEffect = (effectId: string) => {
    removeEffectFromDesign(effectId, selectedEffects, setSelectedEffects);
  };

  // Create design
  const handleCreateDesign = () => {
    if (!designName || !selectedEquipmentType || selectedEffects.length === 0) return;

    const success = startDesigningEnchantment(designName, selectedEquipmentType, selectedEffects);
    if (success) {
      // Reset form
      setDesignName('');
      setSelectedEquipmentType(null);
      setSelectedEffects([]);
    }
  };

  // Get available effects for selected equipment type (only unlocked ones)
  const availableEffects = getAvailableEffects(selectedEquipmentType, unlockedEffects);

  // Get incompatible effects (unlocked but not for this equipment type)
  const incompatibleEffects = getIncompatibleEffects(selectedEquipmentType, unlockedEffects);

  // Get equipment types that the player actually owns (has instances of)
  const ownedEquipmentTypes = getOwnedEquipmentTypes(equipmentInstances);

  // Get the reason why an effect is incompatible
  const getIncompatibilityReasonWrapper = (effect: { id: string; name: string; description: string; allowedEquipmentCategories: EquipmentCategory[] }) => {
    return getIncompatibilityReason(effect, selectedEquipmentType);
  };

  // Render stage
  return (
    <DebugName name="EnchantmentDesigner">
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      {/* Equipment Type Selection */}
      <EquipmentTypeSelector
        ownedEquipmentTypes={ownedEquipmentTypes}
        selectedEquipmentType={selectedEquipmentType}
        setSelectedEquipmentType={setSelectedEquipmentType}
        designProgress={designProgress}
        cancelDesign={cancelDesign}
      />

      {/* Effect Selection */}
      <GameCard variant="default">
        <EffectSelector
          selectedEquipmentType={selectedEquipmentType}
          selectedEffects={selectedEffects}
          setSelectedEffects={setSelectedEffects}
          availableEffects={availableEffects}
          incompatibleEffects={incompatibleEffects}
          enchantingLevel={enchanterLevel}
          efficiencyBonus={0}
          designProgress={designProgress}
          addEffect={addEffect}
          removeEffect={removeEffect}
          getIncompatibilityReason={getIncompatibilityReasonWrapper}
        />

        {/* Selected effects summary - only show when not in design progress and equipment type is selected */}
        {!designProgress && selectedEquipmentType && (
          <>
            <Separator className="bg-[var(--border-subtle)] my-2" />
            <DesignForm
              designName={designName}
              setDesignName={setDesignName}
              selectedEffects={selectedEffects}
              designCapacityCost={designCapacityCost}
              selectedEquipmentCapacity={selectedEquipmentCapacity}
              isOverCapacity={designCapacityCost > selectedEquipmentCapacity}
              designTime={designTime}
              selectedEquipmentType={selectedEquipmentType}
              handleCreateDesign={handleCreateDesign}
            />
          </>
        )}
      </GameCard>

      {/* Saved Designs */}
      <SavedDesigns
        completedEnchantmentDesigns={completedEnchantmentDesigns}
        selectedDesign={selectedDesign}
        setSelectedDesign={setSelectedDesign}
        deleteDesign={deleteDesign}
      />
    </div>
    </DebugName>
  );
}

EnchantmentDesigner.displayName = 'EnchantmentDesigner';
