'use client';

import { useCallback, useMemo } from 'react';
import { useCraftingStore } from '@/lib/game/stores/craftingStore';
import type { EquipmentSlot } from '@/lib/game/types';
import { DebugName } from '@/components/game/debug/debug-context';
import { EquipmentSlotGrid } from './EquipmentTab/EquipmentSlotGrid';
import { InventoryList } from './EquipmentTab/InventoryList';
import { EquipmentEffectsSummary } from './EquipmentTab/EquipmentEffectsSummary';

export function EquipmentTab() {
  const equippedInstances = useCraftingStore((s) => s.equippedInstances);
  const equipmentInstances = useCraftingStore((s) => s.equipmentInstances);
  const storeEquipItem = useCraftingStore((s) => s.equipItem);
  const storeUnequipItem = useCraftingStore((s) => s.unequipItem);
  const storeDeleteEquipment = useCraftingStore((s) => s.deleteEquipmentInstance);

  const handleEquip = useCallback(
    (instanceId: string, slot: EquipmentSlot): boolean => {
      return storeEquipItem(instanceId, slot);
    },
    [storeEquipItem]
  );

  const handleUnequip = useCallback(
    (slot: EquipmentSlot) => {
      storeUnequipItem(slot);
    },
    [storeUnequipItem]
  );

  const handleDelete = useCallback(
    (instanceId: string) => {
      storeDeleteEquipment(instanceId);
    },
    [storeDeleteEquipment]
  );

  const inventoryItems = useMemo(
    () =>
      Object.entries(equipmentInstances).filter(
        ([id]) => !Object.values(equippedInstances).includes(id)
      ),
    [equipmentInstances, equippedInstances]
  );

  return (
    <DebugName name="EquipmentTab">
      <div className="space-y-6">
        <div>
          <h2 className="text-lg font-semibold text-[var(--text-primary)] mb-3">Equipped Gear</h2>
          <EquipmentSlotGrid
            equippedInstances={equippedInstances}
            equipmentInstances={equipmentInstances}
            onUnequip={handleUnequip}
          />
        </div>

        <EquipmentEffectsSummary
          equipmentInstances={equipmentInstances}
          equippedInstances={equippedInstances}
        />

        <div>
          <h2 className="text-lg font-semibold text-[var(--text-primary)] mb-3">
            Inventory ({inventoryItems.length})
          </h2>
          <InventoryList
            inventoryItems={inventoryItems}
            equippedInstances={equippedInstances}
            onEquip={handleEquip}
            onDelete={handleDelete}
          />
        </div>
      </div>
    </DebugName>
  );
}

EquipmentTab.displayName = 'EquipmentTab';
