'use client';

import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { Card, CardContent } from '@/components/ui/card';
import { Zap, ChevronDown, ChevronUp } from 'lucide-react';
import { fmt, fmtDec } from '@/lib/game/stores';
import { ELEMENTS } from '@/lib/game/constants';
import { useState } from 'react';
import { DebugName } from '@/components/game/debug/debug-context';

/** Per-element regen breakdown: produced rate and downstream drains */
export interface ElementRegenBreakdown {
  /** Rate at which this element is produced from conversion */
  produced: number;
  /** Drains: destination element → rate consumed */
  drains: Record<string, number>;
}

interface ManaDisplayProps {
  rawMana: number;
  maxMana: number;
  effectiveRegen: number;
  meditationMultiplier: number;
  clickMana: number;
  isGathering: boolean;
  onGatherStart: () => void;
  onGatherEnd: () => void;
  elements: Record<string, { current: number; max: number; unlocked: boolean }>;
  /** Per-element net regen rates (from unified conversion system) */
  elementRegen?: Record<string, number>;
  /** Detailed per-element regen breakdown (produced rate + downstream drains) */
  elementRegenBreakdown?: Record<string, ElementRegenBreakdown>;
}

export function ManaDisplay({
  rawMana,
  maxMana,
  effectiveRegen,
  meditationMultiplier,
  clickMana,
  isGathering,
  onGatherStart,
  onGatherEnd,
  elements,
  elementRegen,
  elementRegenBreakdown,
}: ManaDisplayProps) {
  const [expanded, setExpanded] = useState(true);
  const [expandedElements, setExpandedElements] = useState<Record<string, boolean>>({});

  const toggleElementDetail = (id: string) => {
    setExpandedElements(prev => ({ ...prev, [id]: !prev[id] }));
  };

  const unlockedElements = Object.entries(elements)
    .filter(([, state]) => state.unlocked && state.current > 0)
    .sort((a, b) => b[1].current - a[1].current);

  return (
    <DebugName name="ManaDisplay">
      <Card className="bg-[var(--bg-panel)] border-[var(--border-subtle)]">
        <CardContent className="pt-4 space-y-3">
        {/* Raw Mana - Main Display */}
        <div>
          <div className="flex items-baseline gap-1">
            <span className="text-3xl font-bold game-mono" style={{ color: 'var(--mana-raw)' }}>{fmt(rawMana)}</span>
            <span className="text-sm" style={{ color: 'var(--text-muted)' }}>/ {fmt(maxMana)}</span>
          </div>
          <div className="text-xs" style={{ color: 'var(--text-muted)' }}>
            +{fmtDec(effectiveRegen)} mana/hr {meditationMultiplier > 1.01 && <span style={{ color: 'var(--mana-light)' }}>({fmtDec(meditationMultiplier, 1)}x med)</span>}
          </div>
        </div>

        <Progress
          value={(rawMana / maxMana) * 100}
          className="h-2 bg-[var(--bg-sunken)]"
          style={{ '--progress-bg': 'var(--mana-raw)' } as React.CSSProperties}
        />

        <Button
          className={`w-full transition-all text-[var(--font-display)] tracking-wider
            ${isGathering
              ? 'animate-gather-glow'
              : 'hover:scale-[1.02]'}
          `}
          style={{
            background: 'var(--mana-raw)',
            border: '1px solid var(--border-accent)',
            color: 'var(--bg-gather-btn)',
            fontWeight: 600,
          }}
          onMouseDown={onGatherStart}
          onMouseUp={onGatherEnd}
          onMouseLeave={onGatherEnd}
          onTouchStart={onGatherStart}
          onTouchEnd={onGatherEnd}
        >
          <Zap className="w-4 h-4 mr-2" />
          Gather +{clickMana} Mana
          {isGathering && <span className="ml-2 text-xs" style={{ opacity: 0.8 }}>(Holding...)</span>}
        </Button>

        {/* Elemental Mana Pools */}
        {unlockedElements.length > 0 && (
          <div className="border-t border-[var(--border-subtle)] pt-3 mt-3">
            <button
              onClick={() => setExpanded(!expanded)}
              className="flex items-center justify-between w-full text-xs transition-colors"
              style={{ color: 'var(--text-muted)' }}
            >
              <span style={{ fontFamily: 'var(--font-display)', letterSpacing: '0.5px' }}>ELEMENTAL MANA ({unlockedElements.length})</span>
              {expanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}</button>

            {expanded && (
              <div className="grid grid-cols-2 gap-2 mt-2">
                {unlockedElements.map(([id, state]) => {
                  const elem = ELEMENTS[id];
                  if (!elem) return null;
                  const regen = elementRegen?.[id];
                  const breakdown = elementRegenBreakdown?.[id];
                  const hasBreakdown = breakdown && (breakdown.produced > 0 || Object.keys(breakdown.drains).length > 0);
                  const isExpanded = expandedElements[id];

                  return (
                    <div
                      key={id}
                      className="p-2 transition-all border rounded-sm"
                      style={{
                        background: 'var(--bg-sunken)/30',
                        borderColor: `${elem.color}30`,
                      }}
                    >
                      <div className="flex items-center gap-1 mb-1">
                        <span style={{ color: elem.color }}>{elem.sym}</span>
                        <span className="text-xs font-medium" style={{ color: elem.color }}>
                          {elem.name}
                        </span>
                      </div>
                      <div className="h-1.5 rounded-full overflow-hidden" style={{ background: 'var(--bg-void)' }}>
                        <div
                          className="h-full transition-all rounded-full"
                          style={{
                            width: `${Math.min(100, (state.current / state.max) * 100)}%`,
                            backgroundColor: elem.color
                          }}
                        />
                      </div>
                      <div className="flex items-center justify-between">
                        <div className="text-xs game-mono" style={{ color: 'var(--text-muted)' }}>
                          {fmt(state.current)}/{fmt(state.max)}
                        </div>
                        {regen !== undefined && regen !== 0 && (
                          <div className="text-xs game-mono" style={{ color: regen > 0 ? 'var(--color-success)' : 'var(--color-error)' }}>
                            {regen > 0 ? '+' : ''}{fmtDec(regen, 2)}/hr
                          </div>
                        )}
                      </div>
                      {/* Expandable regen breakdown (DISC-8) */}
                      {hasBreakdown && (
                        <button
                          onClick={() => toggleElementDetail(id)}
                          className="flex items-center gap-0.5 mt-1 text-xs w-full"
                          style={{ color: 'var(--text-muted)' }}
                        >
                          {isExpanded ? <ChevronUp className="w-2.5 h-2.5" /> : <ChevronDown className="w-2.5 h-2.5" />}
                          <span>regen detail</span>
                        </button>
                      )}
                      {hasBreakdown && isExpanded && (
                        <div className="mt-1 pt-1 border-t border-[var(--border-subtle)] space-y-0.5" style={{ color: 'var(--text-muted)' }}>
                          {breakdown.produced > 0 && (
                            <div>
                              <span style={{ color: 'var(--color-success)' }}>+{fmtDec(breakdown.produced, 2)}/hr</span>
                              <span> converted from raw</span>
                            </div>
                          )}
                          {Object.entries(breakdown.drains).map(([destId, drainRate]) => {
                            const destElem = ELEMENTS[destId];
                            return (
                              <div key={destId}>
                                <span style={{ color: 'var(--color-warning)' }}>-{fmtDec(drainRate, 2)}/hr</span>
                                <span> → {destElem?.sym} {destElem?.name}</span>
                              </div>
                            );
                          })}
                          <div className="pt-0.5 border-t border-[var(--border-subtle)]" style={{ color: regen && regen >= 0 ? 'var(--color-success)' : 'var(--color-error)' }}>
                            Net: {regen && regen >= 0 ? '+' : ''}{fmtDec(regen || 0, 2)}/hr
                          </div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}
        </CardContent>
      </Card>
    </DebugName>
  );
}

ManaDisplay.displayName = "ManaDisplay";
