// [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 CommercialTiers() {
  const { tiers, setTiers, activeCurrency, setActiveCurrency, formatDynamicCurrency } = useCommercial();
  const { allModules } = useModuleRegistry();
  
  // Edit State
  const [editingTierId, setEditingTierId] = useState(null);
  const [editName, setEditName] = useState('');
  const [editDesc, setEditDesc] = useState('');
  const [editPrice, setEditPrice] = useState('');
  const [editModules, setEditModules] = useState({});

  const handleEditClick = (tier) => {
    setEditingTierId(tier.id);
    setEditName(tier.name);
    setEditDesc(tier.description);
    setEditPrice(tier.price);
    
    const modMap = {};
    tier.modules.forEach(m => modMap[m] = true);
    setEditModules(modMap);
  };

  const handleToggleEditModule = (modId) => {
    setEditModules(prev => ({ ...prev, [modId]: !prev[modId] }));
  };

  const saveEdit = (tierId) => {
    const selectedMods = Object.keys(editModules).filter(k => editModules[k]);
    
    setTiers(prev => prev.map(t => {
      if (t.id === tierId) {
        return { 
          ...t, 
          name: editName,
          description: editDesc,
          price: Number(editPrice),
          modules: selectedMods
        };
      }
      return t;
    }));
    setEditingTierId(null);
  };

  const annihilateTier = (tierId) => {
    setTiers(prev => prev.filter(t => t.id !== tierId));
    setEditingTierId(null);
  };

  const spawnNewTier = () => {
    const newId = 'tier_' + Math.random().toString(36).substr(2, 6);
    const blankTier = {
      id: newId,
      name: 'NEW CUSTOM TIER',
      price: 0,
      description: 'Deskripsi paket baru...',
      modules: []
    };
    // Append to end
    setTiers(prev => [...prev, blankTier]);
    // Auto-enter edit mode for the new tier
    handleEditClick(blankTier);
  };

  return (
    <div className="glass-panel" style={{padding: '40px', borderColor: 'var(--accent-purple)'}}>
      <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '20px'}}>
        <div>
          <h2 style={{color: 'var(--text-main)', marginBottom: '10px', fontFamily: 'monospace', letterSpacing: '2px'}}>QUANTUM FOREX MATRIX (MODUL 21)</h2>
          <p style={{color: 'var(--text-muted)'}}>
            Konfigurasi Paket Penagihan Klien. Transmutasi nilai berjalan secara real-time.
          </p>
        </div>
        
        {/* Multi-Currency Switcher */}
        <div style={{display: 'flex', background: 'var(--panel-bg)', padding: '5px', borderRadius: '8px', border: '1px solid rgba(255,255,255,0.1)'}}>
          {['IDR', 'USD', 'BTC'].map(currency => (
            <button
              key={currency}
              onClick={() => setActiveCurrency(currency)}
              style={{
                padding: '8px 16px', border: 'none', borderRadius: '4px', cursor: 'pointer',
                fontFamily: 'monospace', fontWeight: 'bold', transition: 'all 0.3s',
                background: activeCurrency === currency ? 'var(--accent-purple)' : 'transparent',
                color: activeCurrency === currency ? 'var(--text-main)' : 'var(--text-muted)'
              }}
            >
              {currency === 'IDR' ? 'Rp IDR' : currency === 'USD' ? '$ USD' : 'â‚¿ BTC'}
            </button>
          ))}
        </div>
      </div>

      <div style={{display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '30px', marginTop: '40px'}}>
        {tiers.map((tier, index) => {
          let themeColor = 'var(--accent-cyan)';
          if (index === 1) themeColor = 'var(--accent-yellow)';
          if (index === 2) themeColor = 'var(--accent-red)';
          if (index === 3) themeColor = 'var(--accent-green)';

          const isEditing = editingTierId === tier.id;

          return (
            <div key={tier.id} style={{
              background: isEditing ? 'var(--bg-panel)' : 'var(--panel-bg)',
              border: `1px solid ${themeColor}`,
              borderRadius: '12px',
              padding: '30px',
              position: 'relative',
              overflow: 'hidden',
              transition: 'all 0.4s ease',
              transform: isEditing ? 'scale(1.02)' : 'scale(1)',
              boxShadow: isEditing ? `0 0 30px ${themeColor}40` : 'none',
              backdropFilter: 'blur(10px)'
            }}>
              <div style={{
                position: 'absolute', top: 0, left: '50%', transform: 'translateX(-50%)',
                width: isEditing ? '100%' : '50%', height: '4px', background: themeColor,
                boxShadow: `0 0 20px ${themeColor}`, transition: 'all 0.4s'
              }}></div>

              {!isEditing ? (
                <h3 style={{color: themeColor, fontSize: '1.2rem', marginBottom: '5px', letterSpacing: '1px'}}>{tier.name}</h3>
              ) : (
                <input
                  type="text"
                  value={editName}
                  onChange={(e) => setEditName(e.target.value)}
                  style={{
                    width: '100%', padding: '8px', background: 'var(--hover-bg)', 
                    border: `1px solid ${themeColor}`, color: themeColor, 
                    borderRadius: '4px', fontFamily: 'monospace', outline: 'none', fontSize: '1.2rem', marginBottom: '10px', fontWeight: 'bold'
                  }}
                />
              )}
              
              {!isEditing ? (
                <>
                  <div style={{fontSize: '2rem', fontWeight: 'bold', color: themeColor, marginBottom: '15px', fontFamily: 'monospace', animation: 'fadeIn 0.3s'}}>
                    {formatDynamicCurrency(tier.price)} <span style={{fontSize: '1rem', color: 'var(--text-muted)', fontWeight: 'normal'}}>/ bln</span>
                  </div>
                  <p style={{color: 'var(--text-muted)', fontSize: '0.9rem', lineHeight: '1.5', marginBottom: '25px', minHeight: '40px'}}>
                    {tier.description}
                  </p>
                </>
              ) : (
                <div style={{marginBottom: '25px', marginTop: '15px', animation: 'fadeIn 0.3s'}}>
                  <label style={{display: 'block', color: 'var(--text-muted)', fontSize: '0.8rem', marginBottom: '8px'}}>NILAI DASAR (IDR)</label>
                  <input 
                    type="number" 
                    value={editPrice}
                    onChange={(e) => setEditPrice(e.target.value)}
                    style={{
                      width: '100%', padding: '12px', background: 'var(--hover-bg)', 
                      border: `1px solid ${themeColor}`, color: 'var(--text-main)', 
                      borderRadius: '6px', fontFamily: 'monospace', outline: 'none', fontSize: '1.2rem'
                    }}
                  />
                  <div style={{fontSize: '0.8rem', color: 'var(--text-muted)', marginTop: '10px'}}>
                    Estimasi USD: {formatDynamicCurrency(Number(editPrice))} (Bila di-switch)
                  </div>
                  
                  <label style={{display: 'block', color: 'var(--text-muted)', fontSize: '0.8rem', marginTop: '15px', marginBottom: '8px'}}>DESKRIPSI PAKET</label>
                  <textarea
                    value={editDesc}
                    onChange={(e) => setEditDesc(e.target.value)}
                    style={{
                      width: '100%', padding: '12px', background: 'var(--hover-bg)', 
                      border: `1px solid ${themeColor}`, color: 'var(--text-main)', 
                      borderRadius: '6px', fontFamily: 'monospace', outline: 'none', fontSize: '0.9rem', minHeight: '60px', resize: 'vertical'
                    }}
                  />
                </div>
              )}

              <div style={{background: 'var(--hover-bg)', padding: '15px', borderRadius: '8px'}}>
                <div style={{color: themeColor, fontSize: '0.85rem', fontWeight: 'bold', marginBottom: '10px', display: 'flex', justifyContent: 'space-between', letterSpacing: '1px'}}>
                  <span>MODUL DIAKSES:</span>
                  <span style={{color: themeColor, fontWeight: 'bold'}}>{!isEditing ? tier.modules.length : Object.values(editModules).filter(v=>v).length} MODUL</span>
                </div>
                
                <div style={{display: 'flex', flexWrap: 'wrap', gap: '5px', maxHeight: isEditing ? '250px' : '100px', overflowY: 'auto'}} className="custom-scrollbar">
                  {!isEditing ? (
                    tier.modules.map(m => (
                      <span key={m} style={{
                        background: 'var(--bg-panel)', border: '1px solid var(--table-border)',
                        color: 'var(--text-main)', fontSize: '0.7rem', padding: '2px 6px', borderRadius: '4px', fontFamily: 'monospace'
                      }}>
                        {m}
                      </span>
                    ))
                  ) : (
                    allModules.map(mod => (
                      <div 
                        key={mod.id} 
                        onClick={() => handleToggleEditModule(mod.id)}
                        style={{
                          background: editModules[mod.id] ? `${themeColor}20` : 'var(--hover-bg)', 
                          border: `1px solid ${editModules[mod.id] ? themeColor : 'var(--table-border)'}`,
                          color: editModules[mod.id] ? 'var(--text-main)' : 'var(--text-muted)', 
                          fontSize: '0.7rem', padding: '4px 8px', borderRadius: '4px', fontFamily: 'monospace',
                          cursor: 'pointer', transition: 'all 0.2s', width: '100%', display: 'flex', justifyContent: 'space-between'
                        }}
                      >
                        <span>{mod.name}</span>
                        {editModules[mod.id] && <span style={{color: themeColor}}>[ON]</span>}
                      </div>
                    ))
                  )}
                </div>
              </div>
              
              {!isEditing ? (
                <button style={{
                  width: '100%', marginTop: '25px', padding: '12px',
                  background: 'transparent', border: `1px solid ${themeColor}`, color: themeColor,
                  borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace', letterSpacing: '1px',
                  transition: 'all 0.2s'
                }}
                onMouseOver={e => {e.target.style.background = themeColor; e.target.style.color = '#000'}}
                onMouseOut={e => {e.target.style.background = 'transparent'; e.target.style.color = themeColor}}
                onClick={() => handleEditClick(tier)}>
                  EDIT KONFIGURASI HARGA
                </button>
              ) : (
                <div style={{display: 'flex', flexDirection: 'column', gap: '10px', marginTop: '25px'}}>
                  <div style={{display: 'flex', gap: '10px'}}>
                    <button style={{
                      flex: 1, padding: '12px', background: 'transparent', border: '1px solid #555', color: 'var(--text-muted)',
                      borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace'
                    }} onClick={() => setEditingTierId(null)}>BATAL</button>
                    <button style={{
                      flex: 1, padding: '12px', background: themeColor, border: 'none', color: '#000',
                      borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold'
                    }} onClick={() => saveEdit(tier.id)}>SIMPAN TARIF</button>
                  </div>
                  <button style={{
                    width: '100%', padding: '12px', background: 'rgba(255,0,60,0.1)', border: '1px solid var(--accent-red)', color: 'var(--accent-red)',
                    borderRadius: '6px', cursor: 'pointer', fontFamily: 'monospace', fontWeight: 'bold'
                  }} onClick={() => annihilateTier(tier.id)}>DECOMMISSION PACKAGE</button>
                </div>
              )}
            </div>
          );
        })}
        
        {/* FORGE NEW TIER BUTTON */}
        <div 
          onClick={spawnNewTier}
          style={{
            background: 'var(--hover-bg)',
            border: `1px dashed var(--accent-purple)`,
            borderRadius: '12px',
            padding: '30px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            transition: 'all 0.3s ease',
            minHeight: '400px'
          }}
          onMouseOver={(e) => {
            e.currentTarget.style.background = 'rgba(168, 85, 247, 0.1)';
            e.currentTarget.style.boxShadow = '0 0 30px rgba(168, 85, 247, 0.4)';
          }}
          onMouseOut={(e) => {
            e.currentTarget.style.background = 'var(--hover-bg)';
            e.currentTarget.style.boxShadow = 'none';
          }}
        >
          <div style={{fontSize: '3rem', color: 'var(--accent-purple)', marginBottom: '10px'}}>+</div>
          <h3 style={{color: 'var(--text-main)', letterSpacing: '1px'}}>FORGE NEW TIER</h3>
          <p style={{color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center', marginTop: '10px'}}>
            Create a custom modular package<br/>for specific tenant needs.
          </p>
        </div>

        {/* RESTORE DEFAULT PACKAGES BUTTON */}
        <div 
          onClick={() => {
            if(window.confirm('WARNING: This will overwrite all custom tiers and restore the original 4 XCU Factory Packages. Proceed?')) {
              localStorage.removeItem('xcu_commercial_tiers');
              window.location.reload();
            }
          }}
          style={{
            background: 'var(--hover-bg)',
            border: `1px dashed var(--accent-yellow)`,
            borderRadius: '12px',
            padding: '30px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            transition: 'all 0.3s'
          }}
          onMouseOver={e => {e.currentTarget.style.background = 'rgba(255, 234, 0, 0.1)'}}
          onMouseOut={e => {e.currentTarget.style.background = 'var(--hover-bg)'}}
        >
          <div style={{fontSize: '3rem', color: 'var(--accent-yellow)', marginBottom: '10px'}}>â†»</div>
          <h3 style={{color: 'var(--text-main)', letterSpacing: '1px'}}>RESTORE FACTORY TIERS</h3>
          <p style={{color: 'var(--text-muted)', fontSize: '0.8rem', textAlign: 'center', marginTop: '10px'}}>
            Recover lost Default Packages<br/>(Perintis, Omni-Engine, dll).
          </p>
        </div>
      </div>
    </div>
  );
}
