import React, { useMemo } from 'react';
import type { DisciplineDefinition } from '@/lib/game/types/disciplines';
import { ELEMENTS } from '@/lib/game/constants/elements';
import { calculateStatBonus } from '@/lib/game/utils/discipline-math';
import clsx from 'clsx';
import { computePerkCurrentEffect, computeTotalPerkBonusForStat, isRateStat } from './disciplines-utils';
import type { ComputedPerkEffect } from './disciplines-utils';

// ─── Props ────────────────────────────────────────────────────────────────────

export interface DisciplineCardProps {
  definition: DisciplineDefinition;
  xp: number;
  paused: boolean;
  autoPaused?: boolean;
  activeIds: string[];
  concurrentLimit: number;
  isLocked: boolean;
  missingPrereqs: string[];
  missingSourceMana: string[];
  onToggle: (id: string, paused: boolean) => void;
}

// ─── Component ────────────────────────────────────────────────────────────────

export const DisciplineCard: React.FC<DisciplineCardProps> = ({
  definition, xp, paused: isPaused, autoPaused, activeIds, concurrentLimit,
  isLocked, missingPrereqs, missingSourceMana, onToggle,
}) => {
  const {
    id, name, description, manaType, perks,
    statBonus, scalingFactor,
    conversionRate, sourceManaTypes,
  } = definition;

  const displayXp = xp;
  const progressPercent = Math.min(displayXp / Math.max(1, concurrentLimit * 100), 100);
  const activeStatBonus = calculateStatBonus(statBonus.baseValue, displayXp, scalingFactor);

  const elementDef = ELEMENTS[manaType];
  const manaColor = elementDef?.color ?? '#888888';
  const manaIcon = elementDef?.sym ?? '✦';
  const manaName = elementDef?.name ?? manaType;
  const isActive = activeIds.includes(id);
  const _activeNotPaused = activeIds.filter((aid) => {
    // Count how many active disciplines are not paused
    return aid === id ? !isPaused : true;
  }).length;
  const atConcurrentLimit = !isActive && activeIds.length >= concurrentLimit;
  const effectiveIsLocked = isLocked || missingSourceMana.length > 0;
  const statBonusLabel = statBonus.label;

  const computedPerks = useMemo((): ComputedPerkEffect[] => {
    if (!perks) return [];
    return perks.map((perk) => ({
      description: perk.description,
      currentEffect: computePerkCurrentEffect(perk, displayXp),
    }));
  }, [perks, displayXp]);

  const perkBonusTotal = useMemo(() => {
    if (!perks || perks.length === 0) return 0;
    return computeTotalPerkBonusForStat(perks, displayXp, statBonus.stat);
  }, [perks, displayXp, statBonus.stat]);

  const statBonusTotal = activeStatBonus + perkBonusTotal;

  return (
    <div className={clsx('border rounded-lg p-4 shadow-sm space-y-3', effectiveIsLocked && 'opacity-60 border-gray-600')}>
      <div className="flex items-center justify-between gap-2">
        <h3 className="text-lg font-medium">{name}</h3>
        <span
          className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium"
          style={{
            backgroundColor: `${manaColor}20`,
            borderColor: `${manaColor}60`,
            borderWidth: 1,
            color: manaColor,
          }}
        >
          <span>{manaIcon}</span>
          <span>{manaName}</span>
        </span>
      </div>
      <p className="text-sm text-gray-400">{description}</p>

      {/* XP Progress */}
      <div className="flex items-center gap-2">
        <span className="text-xs font-mono whitespace-nowrap">{Math.round(progressPercent)}%</span>
        <div className="flex-1 bg-gray-200 rounded-full overflow-hidden h-3">
          <div
            className={`transition-all duration-300 ${activeStatBonus > 0 ? 'bg-green-500' : 'bg-red-500'}`}
            style={{ width: `${Math.round(progressPercent)}%` }}
          />
        </div>
      </div>

      {/* Stats Row */}
      <div className="flex flex-wrap gap-x-4 gap-y-1 text-sm text-gray-400">
        <span><strong>XP:</strong> {displayXp}</span>
      </div>

      {/* Conversion Info */}
      {conversionRate != null && sourceManaTypes && (
        <div className="mt-2 text-xs text-gray-400">
          <strong>Converts:</strong> {sourceManaTypes.map(s => s === 'raw' ? 'raw' : ELEMENTS[s]?.name ?? s).join(' + ')} → {manaName}
        </div>
      )}

      {/* Stat Bonus with Perk Total */}
      {(() => {
        const safeActive = Number.isFinite(activeStatBonus) ? activeStatBonus : 0;
        const safePerk = Number.isFinite(perkBonusTotal) ? perkBonusTotal : 0;
        const safeTotal = Number.isFinite(statBonusTotal) ? statBonusTotal : 0;
        const rateSuffix = isRateStat(statBonus.stat) ? '/sec' : '';
        return (
          <div className="mt-2 text-sm">
            <strong>Stat Bonus:</strong> {safeActive.toFixed(2)}{rateSuffix} on {statBonusLabel}
            {safePerk > 0 && (
              <span className="text-green-400 ml-1">
                ({safeTotal.toFixed(2)}{rateSuffix} with perks)
              </span>
            )}
          </div>
        );
      })()}

      {/* Perks */}
      <div className="mt-2">
        <strong>Perks:</strong>
        <ul className="mt-1 list-disc list-inside space-y-1 text-xs">
          {computedPerks.length > 0 ? (
            computedPerks.map((p) => (
              <li key={p.description} className={clsx(
                p.currentEffect.startsWith('at ') ? 'text-gray-400' : 'text-green-500',
              )}>
                {p.description}
                <span className="text-gray-300 ml-1">— {p.currentEffect}</span>
              </li>
            ))
          ) : (
            <li className="text-gray-400">— none —</li>
          )}
        </ul>
      </div>

      {/* Lock Reasons */}
      {(effectiveIsLocked || atConcurrentLimit) && (missingPrereqs.length > 0 || missingSourceMana.length > 0 || atConcurrentLimit) && (
        <div className="mt-2 text-xs text-red-400">
          {atConcurrentLimit && <div><strong>At limit:</strong> {activeIds.length}/{concurrentLimit} disciplines active</div>}
          {missingPrereqs.length > 0 && <div><strong>Requires:</strong> {missingPrereqs.join(', ')}</div>}
          {missingSourceMana.length > 0 && <div><strong>Missing mana:</strong> {missingSourceMana.join(', ')}</div>}
        </div>
      )}
      {atConcurrentLimit && missingPrereqs.length === 0 && missingSourceMana.length === 0 && (
        <div className="mt-2 text-xs text-amber-400">
          <strong>At limit:</strong> {activeIds.length}/{concurrentLimit} disciplines active. Gain XP to unlock more slots.
        </div>
      )}

      {/* Action Button */}
      <div className="mt-4 flex justify-end">
        <button
          onClick={() => onToggle(id, isPaused)}
          disabled={effectiveIsLocked || atConcurrentLimit}
          className={clsx(
            'rounded px-3 py-1 text-sm font-medium',
            effectiveIsLocked || atConcurrentLimit
              ? 'bg-gray-600 text-gray-400 cursor-not-allowed'
              : isPaused
                ? 'bg-yellow-600 text-white hover:bg-yellow-500'
                : 'bg-blue-600 text-white hover:bg-blue-500',
          )}
        >
          {effectiveIsLocked
            ? 'Locked'
            : atConcurrentLimit
              ? `At Limit (${activeIds.length}/${concurrentLimit})`
              : isPaused
                ? 'Start Practicing'
                : 'Stop Practicing'}
        </button>
      </div>
    </div>
  );
};
