import React, { useMemo } from 'react';
import type { DisciplineDefinition, DisciplineState } from '@/lib/game/types/disciplines';
import { ELEMENTS } from '@/lib/game/constants/elements';
import { elementalAttunementDisciplines } from '@/lib/game/data/disciplines/elemental';
import { elementalRegenDisciplines } from '@/lib/game/data/disciplines/elemental-regen';
import { elementalRegenAdvancedDisciplines } from '@/lib/game/data/disciplines/elemental-regen-advanced';
import { ALL_DISCIPLINES } from '@/lib/game/data/disciplines';
import { checkDisciplinePrerequisites } from '@/lib/game/utils/discipline-math';
import { DisciplineCard } from './DisciplineCard';
import type { DisciplineCardProps } from './DisciplineCard';

// ─── Element Ordering ────────────────────────────────────────────────────────

interface ElementGroup {
  category: 'base' | 'utility' | 'composite' | 'exotic';
  categoryLabel: string;
  manaTypes: string[];
}

const ELEMENT_GROUPS: ElementGroup[] = [
  { category: 'base', categoryLabel: 'Base Elements', manaTypes: ['fire', 'water', 'air', 'earth', 'light', 'dark', 'death'] },
  { category: 'utility', categoryLabel: 'Utility', manaTypes: ['transference'] },
  { category: 'composite', categoryLabel: 'Composite', manaTypes: ['metal', 'sand', 'lightning'] },
  { category: 'exotic', categoryLabel: 'Exotic', manaTypes: ['crystal', 'stellar', 'void'] },
];

// ─── Discipline Map Builder ──────────────────────────────────────────────────

type DisciplineMap = Map<string, { capacity?: DisciplineDefinition; conversion?: DisciplineDefinition }>;

function buildElementalDisciplineMap(
  capacityDisciplines: DisciplineDefinition[],
  conversionDisciplines: DisciplineDefinition[],
): DisciplineMap {
  const map = new Map<string, { capacity?: DisciplineDefinition; conversion?: DisciplineDefinition }>();
  for (const d of capacityDisciplines) {
    const entry = map.get(d.manaType) ?? {};
    entry.capacity = d;
    map.set(d.manaType, entry);
  }
  for (const d of conversionDisciplines) {
    const entry = map.get(d.manaType) ?? {};
    entry.conversion = d;
    map.set(d.manaType, entry);
  }
  return map;
}

// ─── Shared Props ─────────────────────────────────────────────────────────────

interface SharedRenderProps {
  disciplines: Record<string, DisciplineState>;
  activeIds: string[];
  concurrentLimit: number;
  elements: DisciplineCardProps['missingSourceMana'] extends readonly string[]
    ? Record<string, { unlocked: boolean }>
    : never;
  onToggle: (id: string, paused: boolean) => void;
}

// ─── Elemental Discipline Group ──────────────────────────────────────────────

interface GroupProps extends SharedRenderProps {
  manaType: string;
  capacity?: DisciplineDefinition;
  conversion?: DisciplineDefinition;
}

const ElementalDisciplineGroup: React.FC<GroupProps & { activeIds: string[] }> = ({
  manaType, capacity, conversion, disciplines, activeIds, concurrentLimit, elements, onToggle,
}) => {
  const elementDef = ELEMENTS[manaType];
  const manaColor = elementDef?.color ?? '#888888';
  const manaIcon = elementDef?.sym ?? '✦';
  const manaName = elementDef?.name ?? manaType;

  if (!capacity && !conversion) return null;

  const entries: { def: DisciplineDefinition }[] = [];
  if (capacity) entries.push({ def: capacity });
  if (conversion) entries.push({ def: conversion });

  return (
    <div className="border rounded-lg p-4 space-y-3" style={{ borderColor: `${manaColor}40` }}>
      <div className="flex items-center gap-2">
        <span className="text-xl">{manaIcon}</span>
        <h3 className="text-lg font-semibold" style={{ color: manaColor }}>{manaName}</h3>
      </div>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        {entries.map(({ def }) => {
          const discState = disciplines[def.id] ?? { xp: 0, paused: true };
          const prereqCheck = checkDisciplinePrerequisites(def, disciplines, ALL_DISCIPLINES, elements as any);
          return (
            <DisciplineCard
              key={def.id}
              definition={def}
              xp={discState.xp}
              paused={discState.paused}
              autoPaused={discState.autoPaused}
              activeIds={activeIds}
              concurrentLimit={concurrentLimit}
              isLocked={!prereqCheck.canProceed}
              missingPrereqs={prereqCheck.missingPrereqs}
              missingSourceMana={def.sourceManaTypes
                ? def.sourceManaTypes
                    .filter((src) => src !== 'raw' && (!elements[src] || !elements[src].unlocked))
                    .map((src) => `${src} mana`)
                : []}
              onToggle={onToggle}
            />
          );
        })}
      </div>
    </div>
  );
};

// ─── Elemental Subtab ────────────────────────────────────────────────────────

interface ElementalSubtabProps extends SharedRenderProps {}

export const ElementalSubtab: React.FC<ElementalSubtabProps> = ({
  disciplines, activeIds, concurrentLimit, elements, onToggle,
}) => {
  const disciplineMap = useMemo(
    () => buildElementalDisciplineMap(
      elementalAttunementDisciplines,
      [...elementalRegenDisciplines, ...elementalRegenAdvancedDisciplines],
    ),
    [],
  );

  return (
    <div className="space-y-6">
      {ELEMENT_GROUPS.map((group) => {
        const hasAny = group.manaTypes.some(
          (mt) => disciplineMap.get(mt)?.capacity || disciplineMap.get(mt)?.conversion,
        );
        if (!hasAny) return null;

        return (
          <div key={group.category}>
            <h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">
              {group.categoryLabel}
            </h2>
            <div className="space-y-4">
              {group.manaTypes.map((manaType) => {
                const entry = disciplineMap.get(manaType);
                if (!entry?.capacity && !entry?.conversion) return null;
                return (
                  <ElementalDisciplineGroup
                    key={manaType}
                    manaType={manaType}
                    capacity={entry.capacity}
                    conversion={entry.conversion}
                    disciplines={disciplines}
                    activeIds={activeIds}
                    concurrentLimit={concurrentLimit}
                    elements={elements}
                    onToggle={onToggle}
                  />
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
};
