// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
import { useState } from 'react';
import { useCommercial } from '../context/CommercialContext';
import { useModuleRegistry } from '../context/ModuleRegistryContext';

export default function ModulePricingMatrix() {
  const { modulePrices, updateModulePrice, activeCurrency, setActiveCurrency, formatDynamicCurrency } = useCommercial();
  const { registry, totalModules } = useModuleRegistry();
  
  // Local state for tracking which module is currently being edited
  const [editingModId, setEditingModId] = useState(null);
  const [editVal, setEditVal] = useState('');

  const handleEdit = (modId, currentPrice) => {
    setEditingModId(modId);
    setEditVal(currentPrice);
  };

  const handleSave = (modId) => {
    updateModulePrice(modId, editVal);
    setEditingModId(null);
  };

  const handleKeyDown = (e, modId) => {
    if (e.key === 'Enter') handleSave(modId);
    if (e.key === 'Escape') setEditingModId(null);
  };

  return (
    <div style={{animation: 'fadeIn 0.5s ease-out'}}>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '30px'}}>
        <div>
          <h2 style={{color: 'var(--text-main)', marginBottom: '10px', fontFamily: 'monospace', letterSpacing: '2px'}}>DECENTRALIZED MODULE PRICING</h2>
          <p style={{color: 'var(--text-muted)'}}>
            A La Carte Base Price configuration. This dictation affects all independent module acquisitions across the Multi-Tenant Gateways.
          </p>
        </div>
        
        <div style={{display: 'flex', gap: '15px', alignItems: 'center'}}>
          <button 
            onClick={() => {
              if(window.confirm(`WARNING: This will reset all ${totalModules} modules back to the default Base Price (Rp 1.500.000). Proceed?`)) {
                localStorage.removeItem('xcu_module_prices');
                window.location.reload();
              }
            }}
            style={{
              padding: '8px 16px', background: 'transparent', border: '1px solid var(--accent-yellow)',
              color: 'var(--accent-yellow)', borderRadius: '6px', cursor: 'pointer',
              fontFamily: 'monospace', transition: 'all 0.3s'
            }}
            onMouseOver={e => {e.target.style.background = 'rgba(255, 234, 0, 0.1)'}}
            onMouseOut={e => {e.target.style.background = 'transparent'}}
          >
            â†» RESTORE DEFAULT
          </button>

          {/* Multi-Currency Switcher */}
          <div style={{display: 'flex', background: 'var(--panel-bg)', padding: '5px', borderRadius: '8px', border: '1px solid var(--table-border)'}}>
            {['IDR', 'USD', 'BTC'].map(currency => (
              <button
                key={currency}
                onClick={() => setActiveCurrency(currency)}
                style={{
                  padding: '8px 16px',
                  background: activeCurrency === currency ? 'var(--accent-cyan)' : 'transparent',
                  color: activeCurrency === currency ? '#000' : 'var(--text-muted)',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontFamily: 'monospace',
                  fontWeight: activeCurrency === currency ? 'bold' : 'normal',
                  transition: 'all 0.3s'
                }}
              >
                {currency}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: '30px'}}>
        {Object.entries(registry).map(([coreKey, core]) => {
          // Determine core theme color
          let themeColor = 'var(--accent-cyan)';
          if (coreKey === 'beta') themeColor = 'var(--accent-yellow)';
          if (coreKey === 'gamma') themeColor = 'var(--accent-red)';
          if (coreKey === 'omega') themeColor = 'var(--accent-purple)';
          if (coreKey === 'transcendence') themeColor = 'var(--accent-green)';

          return (
            <div key={coreKey} className="glass-panel" style={{
              background: 'var(--panel-bg)',
              borderTop: `4px solid ${themeColor}`,
              borderRadius: '12px',
              padding: '25px',
              position: 'relative'
            }}>
              <h3 style={{color: themeColor, fontSize: '1.2rem', marginBottom: '20px', letterSpacing: '1px', borderBottom: `1px solid var(--table-border)`, paddingBottom: '10px'}}>
                {core.name}
              </h3>
              
              <div style={{display: 'flex', flexDirection: 'column', gap: '10px', maxHeight: '400px', overflowY: 'auto', paddingRight: '10px'}} className="custom-scrollbar">
                {core.modules.map(mod => {
                  const currentPrice = modulePrices[mod.id] || 0;
                  const isEditing = editingModId === mod.id;

                  return (
                    <div key={mod.id} style={{
                      display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                      background: 'var(--hover-bg)', padding: '12px 15px', borderRadius: '8px',
                      border: `1px solid var(--table-border)`, transition: 'all 0.2s',
                      boxShadow: isEditing ? `0 0 15px ${themeColor}20` : 'none'
                    }}>
                      <div style={{flex: 1}}>
                        <div style={{color: 'var(--text-main)', fontSize: '0.9rem', fontWeight: 'bold'}}>{mod.name}</div>
                        <div style={{color: 'var(--text-muted)', fontSize: '0.75rem', fontFamily: 'monospace', marginTop: '4px'}}>ID: {mod.id}</div>
                      </div>
                      
                      <div style={{display: 'flex', alignItems: 'center', gap: '10px'}}>
                        {!isEditing ? (
                          <div 
                            onClick={() => handleEdit(mod.id, currentPrice)}
                            style={{
                              color: themeColor, fontSize: '1.1rem', fontFamily: 'monospace', 
                              cursor: 'pointer', padding: '5px 10px', borderRadius: '4px',
                              background: 'rgba(0,0,0,0.1)'
                            }}
                            title="Click to edit Base Price"
                          >
                            {formatDynamicCurrency(currentPrice)}
                          </div>
                        ) : (
                          <div style={{display: 'flex', alignItems: 'center', gap: '5px'}}>
                            <span style={{color: 'var(--text-muted)', fontSize: '0.8rem'}}>IDR</span>
                            <input 
                              type="number"
                              autoFocus
                              value={editVal}
                              onChange={(e) => setEditVal(e.target.value)}
                              onKeyDown={(e) => handleKeyDown(e, mod.id)}
                              onBlur={() => handleSave(mod.id)}
                              style={{
                                width: '120px', padding: '6px 10px', background: 'var(--panel-bg)',
                                border: `1px solid ${themeColor}`, color: 'var(--text-main)',
                                borderRadius: '4px', fontFamily: 'monospace', fontSize: '1rem', outline: 'none'
                              }}
                            />
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
