'use client';

import { useShallow } from 'zustand/react/shallow';
import { useCombatStore, useManaStore, usePrestigeStore, useGameStore, fmt, computeMaxMana, computeRegen } from '@/lib/game/stores';
import { computeDisciplineEffects } from '@/lib/game/effects/discipline-effects';
import { getUnifiedEffects } from '@/lib/game/effects';
import { useCraftingStore } from '@/lib/game/stores/craftingStore';
import { useAttunementStore } from '@/lib/game/stores/attunementStore';
import { SpireHeader } from './SpireHeader';
import { RoomDisplay } from './RoomDisplay';
import { SpireCombatControls } from './SpireCombatControls';
import { SpireActivityLog } from './SpireActivityLog';
import { SpireManaDisplay } from './SpireManaDisplay';
import { DebugName } from '@/components/game/debug/debug-context';
import { Card, CardContent } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { getGuardianForFloor } from '@/lib/game/data/guardian-encounters';
import { SPELLS_DEF } from '@/lib/game/constants';
import { computeChannelStats } from '@/lib/game/stores/combat-channel';

// ─── Derived Stats Hook ──────────────────────────────────────────────────────

function useSpireStats(prestigeUpgrades: Record<string, number>, equippedInstances: Record<string, string | null>, equipmentInstances: Record<string, import('@/lib/game/types').EquipmentInstance>) {
  let disciplineEffects: ReturnType<typeof computeDisciplineEffects> | null = null;
  try {
    disciplineEffects = computeDisciplineEffects();
  } catch {
    disciplineEffects = { bonuses: {}, multipliers: {}, specials: new Set(), meditationCapBonus: 0, conversions: {} };
  }

  const upgradeEffects = getUnifiedEffects({
    skillUpgrades: {},
    skillTiers: {},
    equippedInstances,
    equipmentInstances,
  });

  const maxMana = computeMaxMana({
    skills: {},
    prestigeUpgrades,
    skillUpgrades: {},
    skillTiers: {},
  }, upgradeEffects, disciplineEffects);

  const baseRegen = computeRegen({
    skills: {},
    prestigeUpgrades,
    skillUpgrades: {},
    skillTiers: {},
    attunements: {},
  }, upgradeEffects, disciplineEffects);

  return { maxMana, baseRegen };
}

// ─── Invocation Panel Component ───────────────────────────────────────────────

function InvocationPanel({ invocationCharge, activeInvocation }: { invocationCharge: number; activeInvocation: { guardianFloor: number; spellId: string; element: string; castProgress: number } | null }) {
  const isActive = activeInvocation !== null;
  const guardian = isActive ? getGuardianForFloor(activeInvocation.guardianFloor) : null;
  const spellDef = isActive ? SPELLS_DEF[activeInvocation.spellId] : null;

  return (
    <Card className={`border-purple-700 ${isActive ? 'bg-purple-950/40' : 'bg-gray-900/60'}`}>
      <CardContent className="p-3 space-y-2">
        <div className="flex items-center justify-between">
          <span className="text-xs font-medium text-purple-300">💜 Invocation</span>
          <span className="text-xs text-gray-400">
            {isActive ? 'Active' : `${Math.round(invocationCharge)}%`}
          </span>
        </div>

        <Progress
          value={invocationCharge}
          className="h-2 bg-gray-800"
          style={{ '--progress-bg': isActive ? '#A855F7' : '#7C3AED' } as React.CSSProperties}
        />

        {isActive && guardian && spellDef && (
          <div className="space-y-1 pt-1">
            <div className="flex items-center gap-2">
              <span className="text-xs text-purple-200 font-medium">{guardian.name}</span>
            </div>
            <div className="flex items-center justify-between">
              <span className="text-xs text-gray-300">
                Casting: {spellDef.name}
              </span>
              <span className="text-xs text-gray-500">
                {Math.round(activeInvocation.castProgress * 100)}%
              </span>
            </div>
            <Progress
              value={activeInvocation.castProgress * 100}
              className="h-1.5 bg-gray-800"
              style={{ '--progress-bg': '#C084FC' } as React.CSSProperties}
            />
            <div className="flex gap-1 pt-0.5">
              {guardian.element.map((el) => (
                <span key={el} className="text-[10px] px-1.5 py-0.5 rounded bg-gray-800 text-gray-400">
                  {el}
                </span>
              ))}
            </div>
          </div>
        )}

        {!isActive && invocationCharge < 100 && (
          <div className="text-[10px] text-gray-500 italic">
            Recharging...
          </div>
        )}

        {!isActive && invocationCharge >= 100 && (
          <div className="text-[10px] text-purple-400 italic">
            Ready to invoke!
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// ─── Main Component ───────────────────────────────────────────────────────────

export function SpireCombatPage() {
  const {
    currentFloor,
    castProgress,
    currentAction,
    isDescending,
    currentRoom,
    activityLog,
    climbDirection,
    currentRoomIndex,
    roomsPerFloor,
    isDescentComplete,
    startFloor,
    exitSpireMode,
    startClimbUp,
    startClimbDown,
    addActivityLog,
    setAction,
    skipNonCombatRoom,
    stayLongerInRoom,
    invocationCharge,
    activeInvocation,
    isChanneling,
    startChanneling,
    stopChanneling,
  } = useCombatStore(useShallow((s) => ({
    currentFloor: s.currentFloor,
    castProgress: s.castProgress,
    currentAction: s.currentAction,
    isDescending: s.isDescending,
    currentRoom: s.currentRoom,
    activityLog: s.activityLog,
    climbDirection: s.climbDirection,
    currentRoomIndex: s.currentRoomIndex,
    roomsPerFloor: s.roomsPerFloor,
    isDescentComplete: s.isDescentComplete,
    startFloor: s.startFloor,
    exitSpireMode: s.exitSpireMode,
    startClimbUp: s.startClimbUp,
    startClimbDown: s.startClimbDown,
    addActivityLog: s.addActivityLog,
    setAction: s.setAction,
    skipNonCombatRoom: s.skipNonCombatRoom,
    stayLongerInRoom: s.stayLongerInRoom,
    invocationCharge: s.invocationCharge,
    activeInvocation: s.activeInvocation,
    isChanneling: s.isChanneling,
    startChanneling: s.startChanneling,
    stopChanneling: s.stopChanneling,
  })));

  const { rawMana, elements } = useManaStore(useShallow((s) => ({
    rawMana: s.rawMana,
    elements: s.elements,
  })));

  const { prestigeUpgrades, insight } = usePrestigeStore(useShallow((s) => ({
    prestigeUpgrades: s.prestigeUpgrades,
    insight: s.insight,
  })));

  const { equippedInstances, equipmentInstances } = useCraftingStore(useShallow((s) => ({
    equippedInstances: s.equippedInstances,
    equipmentInstances: s.equipmentInstances,
  })));

  const day = useGameStore((s) => s.day);
  const hour = useGameStore((s) => s.hour);
  const enchanterActive = useAttunementStore((s) => s.attunements?.enchanter?.active ?? false);
  const transference = elements.transference;
  const channelStats = computeChannelStats();

  const showChannelButton = enchanterActive && currentAction === 'climb' && transference && transference.current > 0;

  const { maxMana, baseRegen } = useSpireStats(prestigeUpgrades, equippedInstances, equipmentInstances);

  const handleClimbUp = () => {
    startClimbUp();
    addActivityLog('floor_transition', `⬆️ Climbing to floor ${currentFloor + 1}...`);
  };

  const handleClimbDown = () => {
    if (currentFloor <= 1) return;
    startClimbDown();
    addActivityLog('floor_transition', `⬇️ Descending to floor ${currentFloor - 1}...`);
  };

  const handleExitSpire = () => {
    exitSpireMode();
  };

  const handleChannelMouseDown = () => {
    startChanneling();
  };

  const handleChannelMouseUp = () => {
    stopChanneling();
  };

  const handleChannelMouseLeave = () => {
    if (isChanneling) stopChanneling();
  };

  return (
    <DebugName name="SpireCombatPage">
    <div className="min-h-screen bg-gray-950 flex flex-col">
      <header className="sticky top-0 z-50 bg-gray-900/95 border-b border-gray-800 px-4 py-2">
        <div className="flex items-center justify-between">
          <h1 className="text-lg font-bold text-amber-400 tracking-wider">🏔️ SPIRE</h1>
          <div className="text-xs text-gray-500">
            Floor {currentFloor} · Insight: {fmt(insight)}
          </div>
        </div>
      </header>

      <main className="flex-1 p-4 space-y-4 max-w-7xl mx-auto w-full">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="lg:col-span-2">
            <SpireHeader
              currentFloor={currentFloor}
              roomsCleared={currentRoomIndex}
              totalRooms={roomsPerFloor}
              onClimbUp={handleClimbUp}
              onClimbDown={handleClimbDown}
              onExitSpire={handleExitSpire}
              isDescending={isDescending}
            />
          </div>
          <div>
            <SpireManaDisplay maxMana={maxMana} effectiveRegen={baseRegen} />
          </div>
        </div>

        {/* Invocation Panel */}
        <InvocationPanel
          invocationCharge={invocationCharge}
          activeInvocation={activeInvocation}
        />

        {/* Transference Channel Button */}
        {showChannelButton && (
          <Card className={`border-teal-700 transition-all ${isChanneling ? 'bg-teal-950/40 ring-1 ring-teal-500/50 shadow-[0_0_12px_rgba(26,188,156,0.3)]' : 'bg-gray-900/80 border-gray-700'}`}>
            <CardContent className="p-3 space-y-2">
              <button
                onMouseDown={handleChannelMouseDown}
                onMouseUp={handleChannelMouseUp}
                onMouseLeave={handleChannelMouseLeave}
                onTouchStart={handleChannelMouseDown}
                onTouchEnd={handleChannelMouseUp}
                className={`w-full py-2 px-4 rounded font-medium text-sm transition-all ${
                  isChanneling
                    ? 'bg-teal-600 text-white shadow-[0_0_16px_rgba(26,188,156,0.5)]'
                    : 'bg-teal-800/60 text-teal-200 hover:bg-teal-700/60 border border-teal-700/50'
                }`}
              >
                🔗 {isChanneling ? 'Channeling...' : 'Channel Transference'}
              </button>
              <div className="space-y-1">
                <div className="flex items-center justify-between text-xs">
                  <span className="text-gray-400">Transference</span>
                  <span className="text-teal-300">
                    {fmt(transference.current)} / {fmt(transference.max)}
                  </span>
                </div>
                <Progress
                  value={(transference.current / transference.max) * 100}
                  className="h-1.5 bg-gray-800"
                  style={{ '--progress-bg': '#1ABC9C' } as React.CSSProperties}
                />
                {isChanneling && (
                  <div className="flex items-center justify-between text-[10px] text-gray-500">
                    <span>⚡ {channelStats.speedMultiplier.toFixed(2)}× speed</span>
                    <span>Draining {(channelStats.drainRate * 5).toFixed(2)}/s</span>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        )}

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
          <div className="lg:col-span-2">
            <RoomDisplay
              floorState={currentRoom}
              floor={currentFloor}
              roomIndex={currentRoomIndex}
              totalRooms={roomsPerFloor}
              day={day}
              hour={hour}
              onSkip={skipNonCombatRoom}
              onStayLonger={stayLongerInRoom}
            />
          </div>
          <div>
            <SpireCombatControls
              castProgress={castProgress}
              isChanneling={isChanneling}
              channelSpeedMultiplier={channelStats.speedMultiplier}
            />
          </div>
        </div>

        <SpireActivityLog activityLog={activityLog} maxEntries={20} />
      </main>
    </div>
    </DebugName>
  );
}
