'use client';

import type { FloorState, EnemyState, RoomType } from '@/lib/game/types';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Button } from '@/components/ui/button';
import { getSpireRoomTypeDisplay } from '@/lib/game/utils/spire-utils';
import { ELEMENTS } from '@/lib/game/constants';
import { fmt } from '@/lib/game/stores';
import { DebugName } from '@/components/game/debug/debug-context';
import { SPECIAL_EFFECTS } from '@/lib/game/data/enchantments/special-effects';
import { isRoomEnchantmentSpecialId, getRoomEnchantmentName, getRoomEnchantmentColor, getRoomEnchantmentBaseMagnitude } from '@/lib/game/utils/room-enchantments-utils';
import { useCraftingStore } from '@/lib/game/stores/craftingStore';

interface RoomDisplayProps {
  floorState: FloorState;
  floor: number;
  roomIndex?: number;
  totalRooms?: number;
  day?: number;
  hour?: number;
  onSkip?: () => void;
  onStayLonger?: () => void;
}

interface RoomEnchantmentDisplayInfo {
  specialId: string;
  name: string;
  color: string;
  baseMagnitude: number;
}

function EnemyRow({ enemy }: { enemy: EnemyState }) {
  const elemDef = ELEMENTS[enemy.element];
  const hpPercent = enemy.maxHP > 0 ? (enemy.hp / enemy.maxHP) * 100 : 0;
  const barrierVal = enemy.barrier ?? 0;
  const hasBarrier = barrierVal > 0;
  const barrierPercent = hasBarrier ? barrierVal * 100 : 0;

  return (
    <div className="space-y-1 p-2 bg-gray-800/50 rounded border border-gray-700/50">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          {elemDef && (
            <span style={{ color: elemDef.color }}>{elemDef.sym}</span>
          )}
          <span className="text-sm font-medium text-gray-200">{enemy.name}</span>
        </div>
        <span className="text-xs text-gray-500">
          {fmt(enemy.hp)} / {fmt(enemy.maxHP)}
        </span>
      </div>
      <div className="relative">
        <Progress
          value={hpPercent}
          className="h-2 bg-gray-700"
          style={{ '--progress-bg': elemDef?.color || '#EF4444' } as React.CSSProperties}
        />
        {hasBarrier && (
          <div
            className="absolute top-0 left-0 h-2 rounded-full bg-blue-400/40"
            style={{ width: `${barrierPercent}%` }}
          />
        )}
      </div>
      <div className="flex items-center gap-2 flex-wrap">
        {enemy.armor > 0 && (
          <Badge variant="outline" className="text-[10px] border-amber-600 text-amber-400">
            ⛰️ {Math.round(enemy.armor * 100)}% armor
          </Badge>
        )}
        {enemy.dodgeChance > 0 && (
          <Badge variant="outline" className="text-[10px] border-green-600 text-green-400">
            💨 {Math.round(enemy.dodgeChance * 100)}% dodge
          </Badge>
        )}
        {hasBarrier && (
          <Badge variant="outline" className="text-[10px] border-blue-600 text-blue-400">
            🛡️ Barrier
          </Badge>
        )}
      </div>
    </div>
  );
}

function RoomHeader({ icon, label, color, roomLabel, timeLabel }: {
  icon: string; label: string; color: string; roomLabel: string | null; timeLabel: string | null;
}) {
  return (
    <CardTitle className="text-sm flex items-center gap-2" style={{ color }}>
      {icon} {label}
      {roomLabel && <Badge variant="outline" className="text-[10px] border-gray-600 text-gray-400">{roomLabel}</Badge>}
      {timeLabel && <span className="text-[10px] text-gray-500 ml-auto">{timeLabel}</span>}
    </CardTitle>
  );
}

function ProgressBar({ progress, required, color }: { progress: number; required: number; color: string }) {
  const pct = required > 0 ? Math.min((progress / required) * 100, 100) : 0;
  return (
    <Progress
      value={pct}
      className="h-2 bg-gray-800"
      style={{ '--progress-bg': color } as React.CSSProperties}
    />
  );
}

export function RoomDisplay({ floorState, floor, roomIndex, totalRooms, day, hour, onSkip, onStayLonger }: RoomDisplayProps) {
  if (!floorState || !floorState.roomType) {
    return (
      <Card className="bg-gray-900/80 border-gray-700">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm text-gray-400">Loading room...</CardTitle>
        </CardHeader>
      </Card>
    );
  }

  const roomDisplay = getSpireRoomTypeDisplay(floorState.roomType as RoomType);
  const showRoomIndex = roomIndex !== undefined && totalRooms !== undefined;
  const roomLabel = showRoomIndex ? `Room ${roomIndex + 1} / ${totalRooms}` : null;
  const timeLabel = day !== undefined && hour !== undefined ? `D${day} H${Math.floor(hour)}` : null;
  const rt = floorState.roomType as string;

  // ─── Recovery Room ──────────────────────────────────────────────────────
  if (rt === 'recovery') {
    const progress = floorState.recoveryProgress || 0;
    const required = floorState.recoveryRequired || 1;
    const stayed = floorState.recoveryStayed || false;
    return (
      <Card className="bg-gray-900/80 border-green-800/40">
        <CardHeader className="pb-2">
          <RoomHeader icon="💚" label="Recovery Room" color="#10B981" roomLabel={roomLabel} timeLabel={timeLabel} />
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-xs text-gray-400">
            Resting and recovering in a mana-rich chamber. Mana regen and conversion rates are 10× faster.
          </p>
          <ProgressBar progress={progress} required={required} color="#10B981" />
          <div className="text-xs text-gray-500">
            {Math.round(progress * 100) / 100} / {required} hours
          </div>
          <div className="flex gap-2">
            {onSkip && (
              <Button variant="outline" size="sm" onClick={onSkip} className="text-xs border-green-700 text-green-400 hover:bg-green-900/30">
                Skip
              </Button>
            )}
            {onStayLonger && (
              <Button variant="outline" size="sm" onClick={onStayLonger} disabled={stayed}
                className="text-xs border-green-700 text-green-400 hover:bg-green-900/30 disabled:opacity-40">
                {stayed ? 'Already Stayed' : 'Stay 1 Hour More'}
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  // ─── Library Room ───────────────────────────────────────────────────────
  if (rt === 'library') {
    const progress = floorState.libraryProgress || 0;
    const required = floorState.libraryRequired || 1;
    const stayed = floorState.libraryStayed || false;
    return (
      <Card className="bg-gray-900/80 border-indigo-800/40">
        <CardHeader className="pb-2">
          <RoomHeader icon="📚" label="Ancient Library" color="#6366F1" roomLabel={roomLabel} timeLabel={timeLabel} />
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-xs text-gray-400">
            Studying Mana Circulation from ancient tomes. A random discipline gains XP at 25× the normal rate.
          </p>
          <ProgressBar progress={progress} required={required} color="#6366F1" />
          <div className="text-xs text-gray-500">
            {Math.round(progress * 100) / 100} / {required} hours
          </div>
          <div className="flex gap-2">
            {onSkip && (
              <Button variant="outline" size="sm" onClick={onSkip} className="text-xs border-indigo-700 text-indigo-400 hover:bg-indigo-900/30">
                Skip
              </Button>
            )}
            {onStayLonger && (
              <Button variant="outline" size="sm" onClick={onStayLonger} disabled={stayed}
                className="text-xs border-indigo-700 text-indigo-400 hover:bg-indigo-900/30 disabled:opacity-40">
                {stayed ? 'Already Stayed' : 'Stay 1 Hour More'}
              </Button>
            )}
          </div>
        </CardContent>
      </Card>
    );
  }

  // ─── Treasure Room ──────────────────────────────────────────────────────
  if (rt === 'treasure') {
    const progress = floorState.treasureProgress || 0;
    const required = floorState.treasureRequired || 1;
    const loot = floorState.treasureLoot || [];
    const claimed = floorState.treasureLootClaimed || [];
    return (
      <Card className="bg-gray-900/80 border-amber-800/40">
        <CardHeader className="pb-2">
          <RoomHeader icon="💎" label="Treasure Room" color="#F59E0B" roomLabel={roomLabel} timeLabel={timeLabel} />
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-xs text-gray-400">
            Rummaging through ancient chests and caches. Loot is revealed progressively as you search.
          </p>
          <ProgressBar progress={progress} required={required} color="#F59E0B" />
          <div className="text-xs text-gray-500">
            {Math.round(progress * 100) / 100} / {required} hours
          </div>
          {claimed.length > 0 && (
            <div className="space-y-1">
              <div className="text-xs text-gray-400 font-medium">Loot found so far:</div>
              {claimed.map((idx) => {
                const drop = loot[idx];
                if (!drop) return null;
                return (
                  <div key={idx} className="text-xs text-amber-300">
                    • {drop.name}
                  </div>
                );
              })}
            </div>
          )}
          {onSkip && (
            <Button variant="outline" size="sm" onClick={onSkip} className="text-xs border-amber-700 text-amber-400 hover:bg-amber-900/30">
              Skip (forfeit remaining loot)
            </Button>
          )}
        </CardContent>
      </Card>
    );
  }

  // ─── Puzzle Room ────────────────────────────────────────────────────────
  if (rt === 'puzzle') {
    const puzzleId = floorState.puzzleId || 'unknown';
    const progress = floorState.puzzleProgress || 0;
    const required = floorState.puzzleRequired || 1;
    const attunements = floorState.puzzleAttunements || [];

    const puzzleNames: Record<string, string> = {
      enchanter_trial: 'Deciphering an enchanted lock',
      fabricator_trial: 'Disassembling a mana-powered mechanism',
      invoker_trial: 'Communing with residual guardian spirits',
      hybrid_enchanter_fabricator: 'Working through a complex attunement challenge',
      hybrid_enchanter_invoker: 'Working through a complex attunement challenge',
      hybrid_fabricator_invoker: 'Working through a complex attunement challenge',
    };

    const thematicText = puzzleNames[puzzleId] || 'Working through a complex attunement challenge';

    return (
      <Card className="bg-gray-900/80 border-purple-800/40">
        <CardHeader className="pb-2">
          <CardTitle className="text-sm flex items-center gap-2" style={{ color: '#8B5CF6' }}>
            🧩 Puzzle Room — {puzzleId.replace(/_/g, ' ')}
            {roomLabel && <Badge variant="outline" className="text-[10px] border-purple-600 text-purple-400">{roomLabel}</Badge>}
            {timeLabel && <span className="text-[10px] text-gray-500 ml-auto">{timeLabel}</span>}
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-3">
          <p className="text-xs text-gray-400">{thematicText}. Higher attunement levels speed up progress.</p>
          <ProgressBar progress={progress} required={required} color="#8B5CF6" />
          <div className="text-xs text-gray-500">
            {Math.round(progress * 100) / 100} / {Math.round(required * 100) / 100} hours
          </div>
          {attunements.length > 0 && (
            <div className="text-xs text-gray-500">
              Relevant attunements: {attunements.join(', ')}
            </div>
          )}
        </CardContent>
      </Card>
    );
  }

  // ─── Combat rooms (combat, swarm, speed, guardian) ───────────────────────
  const enemies = floorState.enemies || [];
  const isGuardian = floorState.roomType === 'guardian';

  // Get equipped room enchantments for display
  const equippedInstances = useCraftingStore(s => s.equippedInstances);
  const equipmentInstances = useCraftingStore(s => s.equipmentInstances);
  const roomEnchantments: RoomEnchantmentDisplayInfo[] = (() => {
    const feetId = equippedInstances?.feet;
    if (!feetId || !equipmentInstances[feetId]) return [];
    const feet = equipmentInstances[feetId];
    if (!feet.enchantments) return [];
    const result: RoomEnchantmentDisplayInfo[] = [];
    for (const enchant of feet.enchantments) {
      const effectDef = SPECIAL_EFFECTS[enchant.effectId];
      if (!effectDef?.effect.specialId || !isRoomEnchantmentSpecialId(effectDef.effect.specialId)) continue;
      const sid = effectDef.effect.specialId;
      result.push({ specialId: sid, name: getRoomEnchantmentName(sid), color: getRoomEnchantmentColor(sid), baseMagnitude: getRoomEnchantmentBaseMagnitude(sid) });
    }
    return result;
  })();

  const roomEnch = floorState.roomEnchantment;
  const coverage = roomEnch?.coverage ?? 0;
  const hasRoomEnchantments = roomEnchantments.length > 0 && roomEnch !== null;

  return (
    <DebugName name="RoomDisplay">
    <Card className={`bg-gray-900/80 ${isGuardian ? 'border-red-800/40' : 'border-gray-700'}`}>
      <CardHeader className="pb-2">
        <CardTitle className="text-sm flex items-center gap-2" style={{ color: roomDisplay.color }}>
          {roomDisplay.icon} {roomDisplay.label}
          {isGuardian && <Badge className="bg-red-900/50 text-red-300 text-xs">BOSS</Badge>}
          {roomLabel && (
            <Badge variant="outline" className="text-[10px] border-gray-600 text-gray-400">
              {roomLabel}
            </Badge>
          )}
          {timeLabel && (
            <span className="text-[10px] text-gray-500 ml-auto">{timeLabel}</span>
          )}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-2">
        {hasRoomEnchantments && (
          <div className="space-y-2 mb-2 p-2 bg-gray-800/50 rounded border border-gray-700/50">
            <div className="text-xs font-semibold text-gray-300">Room Enchantments</div>
            {roomEnchantments.map(re => {
              const mag = re.baseMagnitude * (coverage / 100);
              const label = re.specialId === 'room_fire_damage' || re.specialId === 'room_death_damage'
                ? `→ Enemies burning: ${mag.toFixed(1)} dmg/tick`
                : re.specialId === 'room_lightning_damage'
                ? `→ Chain damage: ${mag.toFixed(1)} dmg/tick`
                : re.specialId === 'room_frost_debuff'
                ? `→ Enemies slowed: ${(mag * 100).toFixed(1)}%`
                : re.specialId === 'room_dark_dodge_debuff'
                ? `→ Enemy dodge: −${(mag * 100).toFixed(1)}%`
                : re.specialId === 'room_earth_armor_debuff'
                ? `→ Enemy armor: −${(mag * 100).toFixed(1)}%`
                : re.specialId === 'room_transference_buff'
                ? `→ Cast speed: +${(mag * 100).toFixed(1)}%`
                : re.specialId === 'room_transference_regen'
                ? `→ Transference regen: +${(mag * 100).toFixed(1)}%/hr`
                : '';
              return (
                <div key={re.specialId} className="space-y-1">
                  <div className="flex items-center gap-2">
                    <span className="text-xs font-medium" style={{ color: re.color }}>{re.name}</span>
                    <span className="text-[10px] text-gray-400">{Math.round(coverage)}%</span>
                  </div>
                  <Progress value={coverage} className="h-1.5 bg-gray-700" style={{ '--progress-bg': re.color } as React.CSSProperties} />
                  <div className="text-[10px] text-gray-500">{label}</div>
                </div>
              );
            })}
          </div>
        )}
        {enemies.length === 0 ? (
          <div className="text-xs text-gray-500 italic">Room cleared!</div>
        ) : (
          enemies.map((enemy) => (
            <EnemyRow key={enemy.id} enemy={enemy} />
          ))
        )}
      </CardContent>
    </Card>
    </DebugName>
  );
}
