'use client';

import { useState, useMemo } from 'react';
import { GameCard } from '@/components/ui/game-card';
import { Separator } from '@/components/ui/separator';
import { EQUIPMENT_TYPES } from '@/lib/game/data/equipment';
import { ENCHANTMENT_EFFECTS } from '@/lib/game/data/enchantment-effects';
import type { EquipmentInstance, EnchantmentDesign, DesignEffect, EquipmentCraftingProgress, EquipmentCategory } from '@/lib/game/types';
import type { EnchantmentDesignerProps } from './EnchantmentDesigner/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 } from '@/lib/game/stores';

export function EnchantmentDesigner({
  selectedEquipmentType,
  setSelectedEquipmentType,
  selectedEffects,
  setSelectedEffects,
  designName,
  setDesignName,
  selectedDesign,
  setSelectedDesign,
}: EnchantmentDesignerProps) {
  // Crafting store selectors
  const enchantmentDesigns = useCraftingStore((s) => s.enchantmentDesigns);
  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 (
    <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={0}
          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
        enchantmentDesigns={enchantmentDesigns}
        selectedDesign={selectedDesign}
        setSelectedDesign={setSelectedDesign}
        deleteDesign={deleteDesign}
      />
    </div>
  );
}

EnchantmentDesigner.displayName = 'EnchantmentDesigner';
