'use client';

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { DebugName } from '@/components/game/debug/debug-context';
import { Separator } from '@/components/ui/separator';
import { FlaskConical, ChevronDown, ChevronUp } from 'lucide-react';
import { ELEMENTS } from '@/lib/game/constants';
import { usePrestigeStore, useManaStore, useAttunementStore, useDisciplineStore, fmtDec } from '@/lib/game/stores';
import { computeDisciplineEffects } from '@/lib/game/effects/discipline-effects';
import { computeConversionRates } from '@/lib/game/utils/conversion-rates';
import { getGuardianForFloor } from '@/lib/game/data/guardian-encounters';
import { ATTUNEMENTS_DEF } from '@/lib/game/data/attunements';
import { useMemo, useState } from 'react';
import type { ElementState } from '@/lib/game/types';

interface ElementStatsSectionProps {
  elemMax: number;
  meditationMultiplier: number;
  baseRegen: number;
}

export function ElementStatsSection({ elemMax, meditationMultiplier, baseRegen }: ElementStatsSectionProps) {
  const prestigeUpgrades = usePrestigeStore((s) => s.prestigeUpgrades);
  const signedPacts = usePrestigeStore((s) => s.signedPacts);
  const elements = useManaStore((s) => s.elements);
  const attunements = useAttunementStore((s) => s.attunements);
  const disciplines = useDisciplineStore((s) => s.disciplines);
  const [formulaExpanded, setFormulaExpanded] = useState(false);

  // Compute conversion breakdown
  const conversionData = useMemo(() => {
    const disciplineEffects = computeDisciplineEffects();
    const pactElementMap: Record<number, string> = {};
    for (const floor of signedPacts) {
      const g = getGuardianForFloor(floor);
      if (g?.element?.length) pactElementMap[floor] = g.element[0];
    }
    const grossRegen: Record<string, number> = {};
    for (const [id, state] of Object.entries(attunements)) {
      if (!state.active) continue;
      const def = ATTUNEMENTS_DEF[id];
      if (def?.primaryManaType && def.rawManaRegen) {
        const levelMult = Math.pow(1.5, (state.level || 1) - 1);
        grossRegen[def.primaryManaType] = (grossRegen[def.primaryManaType] || 0)
          + def.rawManaRegen * levelMult;
      }
    }
    const invokerLevel = attunements.invoker?.active ? (attunements.invoker.level || 1) : 0;
    return computeConversionRates({
      disciplineEffects,
      attunements,
      signedPacts,
      pactElementMap,
      invokerLevel,
      meditationMultiplier,
      grossRegen,
      rawGrossRegen: baseRegen,
    });
  }, [disciplines, attunements, signedPacts]);

  const activeConversions = Object.values(conversionData.rates).filter(
    (e) => e.baseRate > 0 || e.disciplineRate > 0 || e.attunementBase > 0 || e.pactBase > 0,
  );

  return (
    <DebugName name="ElementStatsSection">
    <Card className="bg-[var(--bg-panel)] border-[var(--border-subtle)]">
      <CardHeader className="pb-2">
        <CardTitle className="text-[var(--color-success)] game-panel-title text-xs flex items-center gap-2">
          <FlaskConical className="w-4 h-4" />
          Element Stats
        </CardTitle>
      </CardHeader>
      <CardContent>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span style={{ color: 'var(--text-muted)' }}>Element Capacity:</span>
              <span style={{ color: 'var(--color-success)' }}>{elemMax}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span style={{ color: 'var(--text-muted)' }}>Prestige Attunement:</span>
              <span style={{ color: 'var(--color-success)' }}>+{(prestigeUpgrades.elementalAttune || 0) * 25}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span style={{ color: 'var(--text-muted)' }}>Raw Conversion Drain:</span>
              <span style={{ color: 'var(--color-warning)' }}>-{fmtDec(conversionData.totalRawDrain, 2)}/hr</span>
            </div>
          </div>
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span style={{ color: 'var(--text-muted)' }}>Unlocked Elements:</span>
              <span style={{ color: 'var(--color-success)' }}>{Object.values(elements || {}).filter((e: ElementState) => e.unlocked).length} / {Object.keys(ELEMENTS).length}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span style={{ color: 'var(--text-muted)' }}>Active Conversions:</span>
              <span style={{ color: 'var(--color-success)' }}>{activeConversions.filter(e => !e.paused).length}</span>
            </div>
          </div>
        </div>
        <Separator className="bg-[var(--border-subtle)] my-3" />
        <div className="text-xs" style={{ color: 'var(--text-muted)' }}>Elemental Mana Pools:</div>
        <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 gap-2">
          {Object.entries(elements || {})
            .filter((entry): entry is [string, ElementState] => entry[1].unlocked)
            .map(([id, state]) => {
              const def = ELEMENTS[id];
              const conv = conversionData.rates[id];
              return (
                <div key={id} className="p-2 rounded transition-colors" style={{ border: `1px solid ${def?.color}30`, background: 'var(--bg-sunken)/50', textAlign: 'center' }}>
                  <div className="text-lg" style={{ color: def?.color }}>{def?.sym}</div>
                  <div className="text-xs" style={{ color: 'var(--text-muted)' }}>{fmtDec(state.current, 2)}/{fmtDec(state.max, 0)}</div>
                  {conv && conv.finalRate > 0 && !conv.paused && (
                    <div className="text-xs mt-0.5" style={{ color: 'var(--color-success)' }}>+{fmtDec(conv.finalRate, 2)}/hr</div>
                  )}
                  {conv?.paused && (
                    <div className="text-xs mt-0.5" style={{ color: 'var(--color-error)' }}>⏸️</div>
                  )}
                </div>
              );
            })}
        </div>

        {/* ── Conversion Stats (dedicated section per spec §11) ── */}
        {activeConversions.length > 0 && (
          <>
            <Separator className="bg-[var(--border-subtle)] my-3" />
            <div className="text-xs font-medium mb-2" style={{ color: 'var(--text-muted)' }}>Conversion Stats:</div>

            {/* Collapsible formula reference (DISC-5) */}
            <div className="mb-3">
              <button
                onClick={() => setFormulaExpanded(!formulaExpanded)}
                className="flex items-center gap-1 text-xs font-medium transition-colors"
                style={{ color: 'var(--text-muted)' }}
              >
                {formulaExpanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
                Conversion Rate Formula
              </button>
              {formulaExpanded && (
                <div className="mt-2 p-2 rounded text-xs space-y-1" style={{ background: 'var(--bg-sunken)/40', color: 'var(--text-muted)' }}>
                  <div>finalRate = (disciplineRate + attunementBase + pactBase) × attunementMult × pactMult × meditationMult</div>
                  <div style={{ color: 'var(--text-muted)', opacity: 0.7 }}>where:</div>
                  <div style={{ paddingLeft: '8px' }}>attunementMult = 1 + Σ(relevantAttunementLevel × 0.5)</div>
                  <div style={{ paddingLeft: '8px' }}>pactMult = 1 + Σ(pactCount_element × invokerLevel × 0.25)</div>
                  <div style={{ paddingLeft: '8px' }}>meditationMult = 1 + (meditationMultiplier - 1) / elementDistance</div>
                  <div className="mt-1 pt-1 border-t border-[var(--border-subtle)]">
                    Cost per 1 unit of destination:
                  </div>
                  <div style={{ paddingLeft: '8px' }}>rawCost = 10^(distance+1)</div>
                  <div style={{ paddingLeft: '8px' }}>componentCost = 10 × (distance+1) per component</div>
                  <div className="mt-1 pt-1 border-t border-[var(--border-subtle)]" style={{ color: 'var(--color-warning)' }}>
                    All costs deducted from source regen (not from mana pool).
                  </div>
                  <div style={{ color: 'var(--color-warning)' }}>
                    Conversions pause if source regen &lt; conversion cost.
                  </div>
                </div>
              )}
            </div>

            <div className="space-y-2">
              {activeConversions.map((entry) => (
                <ConversionRow key={entry.element} entry={entry} elementDrain={conversionData.elementDrain} />
              ))}
            </div>
          </>
        )}
      </CardContent>
    </Card>
    </DebugName>
  );
}

function ConversionRow({ entry, elementDrain }: {
  entry: {
    element: string;
    distance: number;
    disciplineRate: number;
    attunementBase: number;
    pactBase: number;
    baseRate: number;
    attunementMult: number;
    pactMult: number;
    meditationMult: number;
    finalRate: number;
    paused: boolean;
    pauseReason: string | null;
    rawCost: number;
    componentCosts: Record<string, number>;
  };
  elementDrain: Record<string, number>;
}) {
  const def = ELEMENTS[entry.element];
  const effectiveRate = entry.paused ? 0 : entry.finalRate;
  const rawDrain = effectiveRate * entry.rawCost;
  const downstreamDrain = elementDrain[entry.element] || 0;

  // Net regen: produced - downstream consumption (DISC-6)
  const netRegen = entry.paused ? 0 : effectiveRate - downstreamDrain;

  return (
    <div className="p-2 rounded text-xs" style={{ border: `1px solid ${def?.color}20`, background: 'var(--bg-sunken)/30' }}>
      <div className="flex items-center gap-1 mb-1" style={{ color: def?.color }}>
        <span>{def?.sym}</span>
        <span className="font-medium">{def?.name}</span>
        <span style={{ color: 'var(--text-muted)' }}>(d={entry.distance})</span>
        {entry.paused && <span style={{ color: 'var(--color-error)' }}>⏸️ PAUSED</span>}
      </div>
      {/* Rate breakdown */}
      <div className="grid grid-cols-2 gap-x-4 gap-y-0.5" style={{ color: 'var(--text-muted)' }}>
        <div>Discipline: <span style={{ color: 'var(--color-success)' }}>+{fmtDec(entry.disciplineRate, 2)}/hr</span></div>
        <div>Attunement: <span style={{ color: 'var(--color-success)' }}>+{fmtDec(entry.attunementBase, 2)}/hr</span></div>
        <div>Pact: <span style={{ color: 'var(--color-success)' }}>+{fmtDec(entry.pactBase, 2)}/hr</span></div>
        <div>Base: <span>{fmtDec(entry.baseRate, 2)}/hr</span></div>
        <div>Att mult: <span>×{fmtDec(entry.attunementMult, 2)}</span></div>
        <div>Pact mult: <span>×{fmtDec(entry.pactMult, 2)}</span></div>
        <div>Med mult: <span>×{fmtDec(entry.meditationMult, 2)}</span></div>
        <div>Final: <span style={{ color: entry.paused ? 'var(--color-error)' : 'var(--color-success)' }}>{entry.paused ? '0.00' : fmtDec(entry.finalRate, 2)}/hr</span></div>
      </div>
      {/* Cost breakdown (per spec §11) */}
      {!entry.paused && effectiveRate > 0 && (
        <div className="mt-1.5 pt-1.5 border-t border-[var(--border-subtle)]">
          <div className="mb-0.5" style={{ color: 'var(--text-muted)' }}>Costs (deducted from regen):</div>
          <div className="grid grid-cols-2 gap-x-4 gap-y-0.5" style={{ color: 'var(--text-muted)' }}>
            <div>Raw: <span style={{ color: 'var(--color-warning)' }}>-{fmtDec(rawDrain, 2)} raw/hr</span> <span style={{ color: 'var(--text-muted)' }}>({entry.rawCost} × {fmtDec(effectiveRate, 2)})</span></div>
            {Object.entries(entry.componentCosts).map(([comp, cost]) => {
              const compDrain = effectiveRate * cost;
              const compDef = ELEMENTS[comp];
              return (
                <div key={comp}>
                  <span style={{ color: compDef?.color }}>{compDef?.sym} {comp}:</span>{' '}
                  <span style={{ color: 'var(--color-warning)' }}>-{fmtDec(compDrain, 2)}/hr</span>{' '}
                  <span style={{ color: 'var(--text-muted)' }}>({cost} × {fmtDec(effectiveRate, 2)})</span>
                </div>
              );
            })}
          </div>
          {/* Downstream drain (this element consumed by higher conversions) */}
          {downstreamDrain > 0 && (
            <div className="mt-1" style={{ color: 'var(--color-warning)' }}>
              ↓ Drained by downstream: -{fmtDec(downstreamDrain, 2)} {def?.name}/hr
            </div>
          )}
        </div>
      )}
      {/* Net regen summary line (DISC-6) */}
      {!entry.paused && (
        <div className="mt-1.5 pt-1.5 border-t border-[var(--border-subtle)]">
          <span style={{ color: 'var(--text-muted)' }}>Net {def?.name} Regen: </span>
          <span style={{ color: 'var(--color-success)' }}>+{fmtDec(effectiveRate, 2)}/hr</span>
          {downstreamDrain > 0 && (
            <>
              <span style={{ color: 'var(--text-muted)' }}> − </span>
              <span style={{ color: 'var(--color-warning)' }}>{fmtDec(downstreamDrain, 2)}/hr</span>
            </>
          )}
          <span style={{ color: 'var(--text-muted)' }}> = </span>
          <span style={{ color: netRegen >= 0 ? 'var(--color-success)' : 'var(--color-error)' }}>
            {netRegen >= 0 ? '+' : ''}{fmtDec(netRegen, 2)}/hr
          </span>
        </div>
      )}
      {entry.paused && entry.pauseReason && (
        <div className="mt-1" style={{ color: 'var(--color-error)' }}>⚠️ {entry.pauseReason}</div>
      )}
    </div>
  );
}
