'use client';

import { ActionButton } from '@/components/ui/action-button';
import { GameCard } from '@/components/ui/game-card';
import { SectionHeader } from '@/components/ui/section-header';
import { StatRow } from '@/components/ui/stat-row';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Separator } from '@/components/ui/separator';
import { ENCHANTMENT_EFFECTS } from '@/lib/game/data/enchantment-effects';
import type { EquipmentSlot } from '@/lib/game/data/equipment';
import { fmt } from '@/lib/game/stores';
import { CheckCircle, Sparkles } from 'lucide-react';
import { useCraftingStore, useManaStore } from '@/lib/game/stores';
import { DebugName } from '@/components/game/debug/debug-context';

export interface EnchantmentApplierProps {
  selectedEquipmentInstance: string | null;
  setSelectedEquipmentInstance: (id: string | null) => void;
  selectedDesign: string | null;
  setSelectedDesign: (id: string | null) => void;
  onEnchantmentApplied?: () => void;
  onCapacityExceeded?: (itemName: string, used: number, total: number) => void;
}

export function EnchantmentApplier({
  selectedEquipmentInstance,
  setSelectedEquipmentInstance,
  selectedDesign,
  setSelectedDesign,
  onEnchantmentApplied,
  onCapacityExceeded,
}: EnchantmentApplierProps) {
  const equippedInstances = useCraftingStore((s) => s.equippedInstances);
  const equipmentInstances = useCraftingStore((s) => s.equipmentInstances);
  const completedEnchantmentDesigns = useCraftingStore((s) => s.completedEnchantmentDesigns);
  const applicationProgress = useCraftingStore((s) => s.applicationProgress);
  const _rawMana = useManaStore((s) => s.rawMana);
  const startApplying = useCraftingStore((s) => s.startApplying);
  const pauseApplication = useCraftingStore((s) => s.pauseApplication);
  const resumeApplication = useCraftingStore((s) => s.resumeApplication);
  const cancelApplication = useCraftingStore((s) => s.cancelApplication);

  // Get equipped items as array - ONLY show items tagged 'Ready for Enchantment' (requirement cr5)
  const equippedItems = Object.entries(equippedInstances)
    .filter(([, instanceId]) => instanceId && equipmentInstances[instanceId])
    .map(([slot, instanceId]) => ({
      slot: slot as EquipmentSlot,
      instance: equipmentInstances[instanceId!],
    }))
    .filter(({ instance }) => instance.tags?.includes('Ready for Enchantment'));

  // Handle apply button click
  const handleApply = () => {
    if (!selectedEquipmentInstance || !selectedDesign) return;

    const instance = equipmentInstances[selectedEquipmentInstance];
    const design = completedEnchantmentDesigns.find(d => d.id === selectedDesign);

    if (!instance || !design) return;

    // Check capacity
    const availableCap = instance.totalCapacity - instance.usedCapacity;
    if (availableCap < design.totalCapacityUsed) {
      onCapacityExceeded?.(instance.name, instance.usedCapacity, instance.totalCapacity);
      return;
    }

    startApplying(selectedEquipmentInstance, selectedDesign);
  };

  return (
    <DebugName name="EnchantmentApplier">
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
      {/* Equipment & Design Selection */}
      <GameCard variant="default">
        <SectionHeader title="Select Equipment & Design" />
        {applicationProgress ? (
          <div className="space-y-3">
            <div className="text-sm text-[var(--text-secondary)]">
              Applying to: {equipmentInstances[applicationProgress.equipmentInstanceId]?.name}
            </div>
            <div className="h-3 bg-[var(--bg-sunken)] rounded-full overflow-hidden">
              <div
                className="h-full bg-[var(--mana-light)] transition-all duration-300"
                style={{ width: `${(applicationProgress.progress / applicationProgress.required) * 100}%` }}
              />
            </div>
            <div className="flex justify-between text-xs text-[var(--text-muted)]">
              <span>{applicationProgress.progress.toFixed(1)}h / {applicationProgress.required.toFixed(1)}h</span>
              <span>Mana spent: {fmt(applicationProgress.manaSpent)}</span>
            </div>
            <div className="flex gap-2">
              {applicationProgress.paused ? (
                <ActionButton size="sm" onClick={resumeApplication}>Resume</ActionButton>
              ) : (
                <>
                  <ActionButton variant="secondary" size="sm" onClick={pauseApplication}>Pause</ActionButton>
                  <ActionButton variant="ghost" size="sm" onClick={() => {
                    cancelApplication();
                    onEnchantmentApplied?.(); // This will trigger the cancel toast via parent
                  }}>Cancel</ActionButton>
                </>
              )}
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            <div>
              <div className="text-sm text-[var(--text-muted)] mb-2">
                Equipment (Ready for Enchantment):
              </div>
              <ScrollArea className="h-32">
                <div className="space-y-1">
                  {equippedItems.map(({ slot: _slot, instance }) => (
                    <div
                      key={instance.instanceId}
                      className={`p-2 rounded border cursor-pointer text-sm transition-all
                        ${selectedEquipmentInstance === instance.instanceId
                          ? 'border-[var(--mana-light)] bg-[var(--mana-light)]/10'
                          : 'border-[var(--border-default)] bg-[var(--bg-sunken)]/50 hover:border-[var(--border-default)]'
                        }
                      `}
                      onClick={() => setSelectedEquipmentInstance(instance.instanceId)}
                      role="button"
                      tabIndex={0}
                      aria-label={`Select ${instance.name} (Ready for Enchantment)`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="text-[var(--text-primary)]">{instance.name}</span>
                        <span className="text-xs text-[var(--text-muted)]">
                          ({instance.usedCapacity}/{instance.totalCapacity} cap)
                        </span>
                      </div>
                      <div className="text-xs text-[var(--color-success)] mt-1">
                        <CheckCircle size={10} className="inline mr-1" />
                        Ready
                      </div>
                    </div>
                  ))}
                  {equippedItems.length === 0 && (
                    <div className="text-center text-[var(--text-muted)] text-xs py-2">
                      No equipment ready for enchantment.
                      <br />
                      Prepare equipment first in the Prepare stage.
                    </div>
                  )}
                </div>
              </ScrollArea>
            </div>

            <div>
              <div className="text-sm text-[var(--text-muted)] mb-2">Design:</div>
              <ScrollArea className="h-32">
                <div className="space-y-1">
                  {completedEnchantmentDesigns.map(design => (
                    <div
                      key={design.id}
                      className={`p-2 rounded border cursor-pointer text-sm transition-all
                        ${selectedDesign === design.id
                          ? 'border-[var(--mana-stellar)] bg-[var(--mana-stellar)]/10'
                          : 'border-[var(--border-default)] bg-[var(--bg-sunken)]/50 hover:border-[var(--border-default)]'
                        }
                      `}
                      onClick={() => setSelectedDesign(design.id)}
                      role="button"
                      tabIndex={0}
                      aria-label={`Select design: ${design.name}`}
                    >
                      <span className="text-[var(--text-primary)]">{design.name}</span>
                      <span className="text-xs text-[var(--text-muted)] ml-2">
                        ({design.totalCapacityUsed} cap)
                      </span>
                    </div>
                  ))}
                  {completedEnchantmentDesigns.length === 0 && (
                    <div className="text-center text-[var(--text-muted)] text-xs py-2">
                      No designs available. Create one in the Design stage.
                    </div>
                  )}
                </div>
              </ScrollArea>
            </div>
          </div>
        )}
      </GameCard>

      {/* Application Details */}
      <GameCard variant="default">
        <SectionHeader title="Apply Enchantment" />
        {!selectedEquipmentInstance || !selectedDesign ? (
          <div className="text-center text-[var(--text-muted)] py-8">
            Select equipment and a design
          </div>
        ) : applicationProgress ? (
          <div className="text-[var(--text-secondary)]">Application in progress...</div>
        ) : (
          (() => {
            const instance = equipmentInstances[selectedEquipmentInstance];
            if (!instance) return null;

            // Check if equipment is ready for enchantment
            const isReady = instance.tags?.includes('Ready for Enchantment');
            if (!isReady) {
              return (
                <div className="text-center text-[var(--color-danger)] py-8">
                  This equipment is not prepared for enchantment. Please prepare it in the Prepare stage first.
                </div>
              );
            }

            const design = completedEnchantmentDesigns.find(d => d.id === selectedDesign);
            if (!design) return null;

            const availableCap = instance.totalCapacity - instance.usedCapacity;
            const canFit = availableCap >= design.totalCapacityUsed;
            const applicationTime = 2 + design.effects.reduce((t, e) => t + e.stacks, 0);
            const manaPerHour = 20 + design.effects.reduce((t, e) => t + e.stacks * 5, 0);

            return (
              <div className="space-y-4">
                <div className="text-lg font-semibold text-[var(--text-primary)]">{design.name}</div>
                <div className="text-sm text-[var(--text-secondary)]">{instance.name}</div>
                <div className="text-xs text-[var(--color-success)]">
                  <CheckCircle size={12} className="inline mr-1" />
                  Ready for Enchantment
                </div>
                <Separator className="bg-[var(--border-subtle)]" />

                <div className="space-y-2 text-sm">
                  <StatRow
                    label="Required Capacity:"
                    value={
                      <span className={canFit ? 'text-[var(--color-success)]' : 'text-[var(--color-danger)]'}>
                        {design.totalCapacityUsed} / {availableCap} available
                      </span>
                    }
                    highlight={canFit ? 'success' : 'danger'}
                  />
                  <StatRow
                    label="Application Time:"
                    value={`${applicationTime}h`}
                    highlight="default"
                  />
                  <StatRow
                    label="Mana per Hour:"
                    value={manaPerHour}
                    highlight="default"
                  />
                </div>

                <div className="text-sm text-[var(--text-muted)]">
                  Effects:
                  <ul className="list-disc list-inside mt-1">
                    {design.effects.map(eff => (
                      <li key={eff.effectId} className="text-[var(--text-secondary)]">
                        {ENCHANTMENT_EFFECTS[eff.effectId]?.name} x{eff.stacks}
                      </li>
                    ))}
                  </ul>
                </div>

                <ActionButton
                  className="w-full"
                  disabled={!canFit}
                  onClick={handleApply}
                >
                  <Sparkles size={16} className="mr-2" />
                  Apply Enchantment
                </ActionButton>
              </div>
            );
          })()
        )}
      </GameCard>
    </div>
    </DebugName>
  );
}

EnchantmentApplier.displayName = 'EnchantmentApplier';
