'use client';

import React, { useState, useMemo, useCallback } from 'react';
import { useShallow } from 'zustand/react/shallow';
import { usePrestigeStore } from '@/lib/game/stores/prestigeStore';
import { useManaStore } from '@/lib/game/stores/manaStore';
import { useUIStore } from '@/lib/game/stores/uiStore';
import { getGuardianForFloor, getAllGuardianFloors } from '@/lib/game/data/guardian-encounters';
import type { GuardianDef } from '@/lib/game/types';
import { DebugName } from '@/components/game/debug/debug-context';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  GuardianCard,
  PactHeaderSummary,
  TierFilter,
} from './guardian-pacts-components';

// ─── Helpers ─────────────────────────────────────────────────────────────────

type GuardianStatus = 'undefeated' | 'defeated' | 'signed';

function getGuardianStatus(floor: number, defeated: number[], signed: number[]): GuardianStatus {
  if (signed.includes(floor)) return 'signed';
  if (defeated.includes(floor)) return 'defeated';
  return 'undefeated';
}

interface FloorTier {
  label: string;
  floors: number[];
}

function groupFloorsByTier(floors: number[]): FloorTier[] {
  const tiers: FloorTier[] = [
    { label: 'Early Spire (10–40)', floors: [] },
    { label: 'Mid Spire (50–80)', floors: [] },
    { label: 'Late Spire (90–100)', floors: [] },
    { label: 'Compound (110)', floors: [] },
    { label: 'Exotic (120–140)', floors: [] },
    { label: 'Transcendent (150+)', floors: [] },
  ];
  for (const f of floors) {
    if (f <= 40) tiers[0].floors.push(f);
    else if (f <= 80) tiers[1].floors.push(f);
    else if (f <= 100) tiers[2].floors.push(f);
    else if (f <= 110) tiers[3].floors.push(f);
    else if (f <= 140) tiers[4].floors.push(f);
    else tiers[5].floors.push(f);
  }
  return tiers.filter(t => t.floors.length > 0);
}

// ─── Main Tab ────────────────────────────────────────────────────────────────

export const GuardianPactsTab: React.FC = () => {
  const [activeTier, setActiveTier] = useState<string>('all');

  const {
    defeatedGuardians,
    signedPacts,
    pactSlots,
    pactRitualFloor,
    pactRitualProgress,
    startPactRitual,
  } = usePrestigeStore(useShallow(s => ({
    defeatedGuardians: s.defeatedGuardians,
    signedPacts: s.signedPacts,
    pactSlots: s.pactSlots,
    pactRitualFloor: s.pactRitualFloor,
    pactRitualProgress: s.pactRitualProgress,
    startPactRitual: s.startPactRitual,
  })));

  const rawMana = useManaStore(s => s.rawMana);
  const addLog = useUIStore(s => s.addLog);

  const guardianFloors = useMemo(
    () => getAllGuardianFloors(),
    [],
  );

  const guardianMap = useMemo(() => {
    const map: Record<number, GuardianDef> = {};
    for (const floor of guardianFloors) {
      const g = getGuardianForFloor(floor);
      if (g) map[floor] = g;
    }
    return map;
  }, [guardianFloors]);

  const tiers = useMemo(() => groupFloorsByTier(guardianFloors), [guardianFloors]);

  const filteredFloors = useMemo(() => {
    if (activeTier === 'all') return guardianFloors;
    const tier = tiers.find(t => t.label === activeTier);
    return tier ? tier.floors : guardianFloors;
  }, [activeTier, guardianFloors, tiers]);

  const handleStartRitual = useCallback((floor: number) => {
    const guardian = getGuardianForFloor(floor);
    if (!guardian) return;

    const result = startPactRitual(floor, rawMana);
    if (result.success) {
      addLog(`📜 Began pact ritual with ${guardian.name}…`);
    } else {
      addLog(`⚠️ ${result.error}`);
    }
  }, [startPactRitual, rawMana, addLog]);

  const cumulativeBoons = useMemo(() => {
    const boonMap: Record<string, number> = {};
    for (const floor of signedPacts) {
      const guardian = getGuardianForFloor(floor);
      if (!guardian) continue;
      for (const boon of guardian.boons) {
        boonMap[boon.type] = (boonMap[boon.type] || 0) + boon.value;
      }
    }
    return boonMap;
  }, [signedPacts]);

  return (
    <DebugName name="GuardianPactsTab">
      <div className="space-y-4">
        <PactHeaderSummary
          signedCount={signedPacts.length}
          pactSlots={pactSlots}
          defeatedCount={defeatedGuardians.length}
          cumulativeBoons={cumulativeBoons}
        />

        <TierFilter
          tiers={tiers}
          activeTier={activeTier}
          guardianFloors={guardianFloors}
          onSelectTier={setActiveTier}
        />

        <ScrollArea className="h-[500px] rounded border border-gray-700 p-3">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {filteredFloors.map((floor) => {
              const guardian = guardianMap[floor];
              if (!guardian) return null;
              return (
                <GuardianCard
                  key={floor}
                  floor={floor}
                  guardian={guardian}
                  status={getGuardianStatus(floor, defeatedGuardians, signedPacts)}
                  canAfford={rawMana >= guardian.pactCost}
                  hasSlot={signedPacts.length < pactSlots}
                  isRitualActive={pactRitualFloor === floor}
                  ritualProgress={pactRitualProgress}
                  onStartRitual={handleStartRitual}
                />
              );
            })}
          </div>
        </ScrollArea>
      </div>
    </DebugName>
  );
};

GuardianPactsTab.displayName = 'GuardianPactsTab';
