import { useState, useEffect } from 'react'

function App() {
  const [scenarios, setScenarios] = useState([])
  const [selectedScenario, setSelectedScenario] = useState('')
  const [pricingDates, setPricingDates] = useState([])
  const [selectedDate, setSelectedDate] = useState('')
  const [matrixData, setMatrixData] = useState(null)
  const [activeTab, setActiveTab] = useState('Equity')

  const API_URL = 'http://127.0.0.1:8000/api'

  useEffect(() => {
    fetch(`${API_URL}/scenarios`)
      .then(r => r.json())
      .then(data => {
        if (!Array.isArray(data)) return;
        const list = data.map(d => d.scenario)
        setScenarios(list)
        if (list.length > 0) setSelectedScenario(list[0])
      })
      .catch(e => console.error('Failed to fetch scenarios:', e))

    fetch(`${API_URL}/dates`)
      .then(r => {
        if (!r.ok) throw new Error('API /dates not found. Restart Uvicorn!');
        return r.json();
      })
      .then(data => {
        if (!Array.isArray(data)) return;
        setPricingDates(data)
        if (data.length > 0) setSelectedDate(data[0])
      })
      .catch(e => {
        console.error('Failed to fetch dates:', e);
        setPricingDates(['Backend Restart Required (404)']);
        setSelectedDate('Backend Restart Required (404)');
      })
  }, [])

  useEffect(() => {
    if (selectedScenario && selectedDate && !selectedDate.includes('Required')) {
      setMatrixData(null)
      fetch(`${API_URL}/matrix/${encodeURIComponent(selectedScenario)}?date=${encodeURIComponent(selectedDate)}`)
        .then(r => r.json())
        .then(setMatrixData)
        .catch(e => console.error('Failed to fetch matrix:', e))
    }
  }, [selectedScenario, selectedDate])

  const filteredAssets = matrixData?.assets.filter(a => a.type === activeTab) || []

  return (
    <>
      <header className="quant-header">
        <div className="brand-title">Deriva ISDA Pre-Calc Hub</div>
        <div className="controls-group">
          <span className="controls-label">Pricing Date:</span>
          <select 
            value={selectedDate} 
            onChange={e => setSelectedDate(e.target.value)}
          >
            {pricingDates.map(pd => (
              <option key={pd} value={pd}>{pd}</option>
            ))}
          </select>

          <span className="controls-label" style={{marginLeft: '15px'}}>Stress Scenario:</span>
          <select 
            value={selectedScenario} 
            onChange={e => setSelectedScenario(e.target.value)}
          >
            {scenarios.map(sc => (
              <option key={sc} value={sc}>{sc}</option>
            ))}
          </select>
        </div>
      </header>

      <div className="workspace">
        
        {matrixData && (
          <>
            {/* Sidebar / Rules Panel */}
            <aside className="panel-rules">
              <div className="panel-header">
                <span>ISDA Structural Math (Merton)</span>
                <span style={{color: 'var(--accent-gold)'}}>Active</span>
              </div>
              <div className="panel-content">
                <div className="rule-card">
                  <div className="rule-title">Equity Parameters</div>
                  <div className="rule-math">{matrixData.global_rules.equity_rule}</div>
                </div>
                <div className="rule-card">
                  <div className="rule-title">Credit Spread Jump</div>
                  <div className="rule-math">{matrixData.global_rules.credit_rule}</div>
                </div>
                <div className="rule-card gold">
                  <div className="rule-title">Yield Curve Vector</div>
                  <div className="rule-math">{matrixData.global_rules.curve_rule}</div>
                </div>
                <div className="rule-card gold">
                  <div className="rule-title">FX Volatility/Spot</div>
                  <div className="rule-math">{matrixData.global_rules.fx_rule}</div>
                </div>
                <div style={{marginTop: 'auto', fontSize: '0.75rem', color: 'var(--text-muted)'}}>
                  System outputting rigorous SciPy Merton/HW configurations for downstream Deriva Monte Carlo engine ingestion.
                </div>
              </div>
            </aside>

            {/* Matrix Viewer */}
            <main className="panel-matrix">
              <div className="tabs-row">
                <button className={`tab-btn ${activeTab === 'Equity' ? 'active' : ''}`} onClick={() => setActiveTab('Equity')}>
                  Equities ({matrixData.assets.filter(a => a.type === 'Equity').length})
                </button>
                <button className={`tab-btn ${activeTab === 'Credit/Bond' ? 'active' : ''}`} onClick={() => setActiveTab('Credit/Bond')}>
                  Fixed Income ({matrixData.assets.filter(a => a.type === 'Credit/Bond').length})
                </button>
                <button className={`tab-btn ${activeTab === 'Yield Curve' ? 'active' : ''}`} onClick={() => setActiveTab('Yield Curve')}>
                  Rates Curves ({matrixData.assets.filter(a => a.type === 'Yield Curve').length})
                </button>
                <button className={`tab-btn ${activeTab === 'FX Pair' ? 'active' : ''}`} onClick={() => setActiveTab('FX Pair')}>
                  Currencies ({matrixData.assets.filter(a => a.type === 'FX Pair').length})
                </button>
              </div>

              <div className="matrix-container">
                <table className="data-table">
                  <thead>
                    <tr>
                      <th>Ticker / Code</th>
                      <th>Class</th>
                      <th>Tenor</th>
                      <th>Base Value</th>
                      <th style={{color: 'var(--accent-gold)'}}>Stressed Spot/Mtm (T=5)</th>
                      <th>Base Vol / PD</th>
                      <th style={{color: 'var(--accent-gold)'}}>Stressed Vol / PD</th>
                    </tr>
                  </thead>
                  <tbody>
                    {filteredAssets.map((row, i) => (
                      <tr key={i}>
                        <td className="sym-code">{row.asset_code}</td>
                        <td>{row.type}</td>
                        <td><span style={{color: 'var(--accent-cyan)'}}>{row.tenor}</span></td>
                        <td className="val-base">{row.base_val}</td>
                        <td className="val-stress">{row.stress_val}</td>
                        <td className="val-base">{row.base_vol}</td>
                        <td><span className="vol-change">{row.stress_vol}</span></td>
                      </tr>
                    ))}
                    {filteredAssets.length === 0 && (
                      <tr>
                        <td colSpan="7" style={{textAlign: 'center', padding: '100px 0', color: 'var(--text-muted)'}}>
                          No underlying assets generated for this subset.
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            </main>
          </>
        )}

      </div>
    </>
  )
}

export default App
