/* global React, YComps, YagodaStore */
const { useState, useEffect, useMemo, useRef } = React;
const Y = window.YagodaStore;
const { Chip, JsonView, useToast, I } = window.YComps;

// ============ SETTINGS ============
function SettingsPage({ store, setStore, resetSample, runTests }) {
  const toast = useToast();
  const s = store.settings;

  const setConn = (k, v) => setStore(prev => ({...prev, settings: {...prev.settings, connectors: {...prev.settings.connectors, [k]: v}}}));
  const setSrc  = (k, v) => setStore(prev => ({...prev, settings: {...prev.settings, dataSources: {...prev.settings.dataSources, [k]: v}}}));
  const setThr  = (k, v) => setStore(prev => ({...prev, settings: {...prev.settings, thresholds: {...prev.settings.thresholds, [k]: parseFloat(v)}}}));
  const setDemo = (k, v) => setStore(prev => ({...prev, settings: {...prev.settings, demo: {...prev.settings.demo, [k]: v}}}));

  const [importText, setImportText] = useState('');
  const fileRef = useRef(null);

  const importJson = (text, source) => {
    try {
      const parsed = JSON.parse(text);
      const arr = Array.isArray(parsed) ? parsed : [parsed];
      const imported = arr.map(r => {
        const norm = Y.genericImporter(r);
        return Y.buildEnrichedRuns([norm])[0];
      });
      setStore(prev => {
        const runs = [...prev.runs, ...imported];
        return { ...prev, runs, alerts: Y.regenerateAlerts(runs) };
      });
      toast.push('Imported', `${imported.length} run(s) from ${source}`, 'success');
    } catch (e) {
      toast.push('Import failed', e.message, 'error');
    }
  };

  const handleFile = (e) => {
    const f = e.target.files?.[0]; if (!f) return;
    const reader = new FileReader();
    reader.onload = () => importJson(reader.result, f.name);
    reader.readAsText(f);
  };

  return (
    <div>
      <div className="page-head"><div><h1 className="page-title">Settings</h1><div className="page-sub">MVP v0.1 · local-first</div></div></div>

      <div className="settings-section panel">
        <div className="panel-head"><div className="panel-title">A · Framework Connectors</div><span style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--muted)'}}>Research workflow adapters · all open in demo</span></div>
        <div className="panel-body">
          {[
            ['qcodes','QCoDeS-style connector','Imports QCoDeS-style run records and metadata.'],
            ['quantify','Quantify-style connector','Imports Quantify-style records via TUID-like context.'],
            ['qiskit','Qiskit job connector','Maps circuit/job context, backend labels, and result references.'],
            ['qibolab','Qibolab / Qibocal direction','Calibration workflow direction for future pilot mapping.'],
            ['laboneq','LabOne Q-style direction','Maps setup/sample metadata and experiment context.'],
            ['matlab','MATLAB output adapter','Maps MAT files, tables, scripts, and exported metrics.'],
            ['simulink','Simulink metadata adapter','Maps model version, scenario configuration, and output results.'],
            ['python','Python / notebook adapter','Maps notebooks, scripts, environment notes, and derived metrics.'],
            ['r','R analysis adapter','Maps analysis scripts, tables, and reproducibility context.'],
            ['hdf5','HDF5 adapter','Maps structured local measurement and simulation files.'],
            ['netcdf','NetCDF adapter','Maps Earth/space science datasets and pipeline products.'],
            ['csv','CSV adapter','Maps tabular exports and run records.'],
            ['json','JSON adapter','Maps custom structured project records.'],
            ['eln_lims','ELN / LIMS export adapter','Maps sample identity, method versions, and lab notes.'],
            ['instrument_logs','Instrument log adapter','Maps instrument state, timestamps, settings, and output references.'],
            ['hpc','HPC job metadata adapter','Maps job IDs, environment, node, runtime, and output products.'],
            ['custom_scripts','Custom lab scripts','Maps project-specific scripts and local conventions.'],
            ['custom','Bring-your-own adapter','Generic adapter for pilot-specific JSON shapes.'],
          ].map(([key,label,desc]) => (
            <ToggleRow key={key} label={label} desc={desc} on={!!s.connectors[key]} onChange={v=>setConn(key,v)}/>
          ))}
        </div>
      </div>

      <div className="settings-section panel">
        <div className="panel-head"><div className="panel-title">B · Data Sources · local paths</div></div>
        <div className="panel-body">
          {Object.entries(s.dataSources).map(([k,v]) => (
            <div key={k} style={{display:'grid', gridTemplateColumns:'200px 1fr', gap:12, padding:'8px 0', borderBottom:'1px solid var(--border)', alignItems:'center'}}>
              <span style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--muted)'}}>{k.replace(/_/g,' ')}</span>
              <input className="input" style={{width:'100%'}} value={v} onChange={e=>setSrc(k, e.target.value)}/>
            </div>
          ))}
          <div style={{fontSize:11, color:'var(--muted)', marginTop:10}}>Paths are descriptive in this MVP. Real connectors will resolve them on the lab machine — no cloud upload required.</div>
        </div>
      </div>

      <div className="settings-section panel">
        <div className="panel-head"><div className="panel-title">C · Alert Thresholds</div></div>
        <div className="panel-body" style={{display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:14}}>
          {[['drift_warning','Drift warning %','%'],['drift_critical','Drift critical %','%'],['benchmark_regression','Benchmark regression Δ','%'],['snapshot_completeness','Snapshot completeness threshold','%']].map(([k,label,unit]) => (
            <div key={k}>
              <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--dim)', letterSpacing:'0.12em', textTransform:'uppercase', marginBottom:6}}>{label}</div>
              <input type="number" step="0.1" className="input" value={s.thresholds[k]} onChange={e=>setThr(k, e.target.value)}/>
            </div>
          ))}
        </div>
      </div>

      <div className="settings-section panel">
        <div className="panel-head"><div className="panel-title">D · Import modes · local-first</div></div>
        <div className="panel-body">
          <div style={{display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:12}}>
            <div className="panel" style={{padding:14}}>
              <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--muted)', textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:6}}>1 · Bundled sample</div>
              <p style={{fontSize:12, color:'var(--muted)', margin:'0 0 10px'}}>Reload the 12 seeded runs.</p>
              <button className="btn btn-primary" onClick={resetSample}>{I.reset} Load sample data</button>
            </div>
            <div className="panel" style={{padding:14}}>
              <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--muted)', textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:6}}>2 · Upload JSON / CSV</div>
              <p style={{fontSize:12, color:'var(--muted)', margin:'0 0 10px'}}>QCoDeS- or Quantify-style records.</p>
              <input ref={fileRef} type="file" accept=".json,.csv" onChange={handleFile} style={{display:'none'}}/>
              <button className="btn" onClick={()=>fileRef.current?.click()}>{I.upload} Choose file</button>
              <textarea className="input" style={{width:'100%', height:80, marginTop:10, fontFamily:'var(--mono)', fontSize:11}} placeholder='Paste JSON: {"run_id":"...","exp_name":"..."} or [...]' value={importText} onChange={e=>setImportText(e.target.value)}/>
              <button className="btn" style={{marginTop:6}} onClick={()=>{ if(importText.trim()){ importJson(importText, 'pasted'); setImportText(''); } }}>Import paste</button>
            </div>
            <div className="panel" style={{padding:14}}>
              <div style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--muted)', textTransform:'uppercase', letterSpacing:'0.1em', marginBottom:6}}>3 · Local dataset directory</div>
              <p style={{fontSize:12, color:'var(--muted)', margin:'0 0 10px'}}>Configure path; connector reads on lab machine.</p>
              <input className="input" style={{width:'100%'}} placeholder="/data/lab/2026" value={s.dataSources.dataset_directory} onChange={e=>setSrc('dataset_directory', e.target.value)}/>
              <button className="btn btn-ghost" style={{marginTop:8}} onClick={()=>toast.push('Demo mode', 'Directory scan prepared. Real connector will scan on next launch.', 'info')}>Scan directory</button>
            </div>
          </div>
          <ToggleRow label="Sample data enabled" desc="Always load 12 seeded runs on reset." on={s.demo.sample_data_enabled} onChange={v=>setDemo('sample_data_enabled', v)}/>
          <div style={{display:'flex', gap:8, marginTop:8}}>
            <button className="btn btn-ghost" onClick={()=>{ downloadJSON('yagoda_demo_dataset.json', store.runs); toast.push('Exported', 'yagoda_demo_dataset.json downloaded', 'success'); }}>{I.download} Export demo dataset</button>
            <button className="btn btn-ghost" onClick={resetSample}>{I.reset} Reset sample data</button>
          </div>
        </div>
      </div>

      <div className="settings-section panel">
        <div className="panel-head"><div className="panel-title">E · In-browser test suite</div><span style={{fontFamily:'var(--mono)', fontSize:10, color:'var(--muted)'}}>mirrors the pytest suite in /backend/tests</span></div>
        <div className="panel-body">
          <TestRunner runTests={runTests}/>
        </div>
      </div>

      <div className="settings-section panel">
        <div className="panel-head"><div className="panel-title">F · Privacy</div></div>
        <div className="panel-body" style={{fontSize:12, color:'var(--muted)', display:'flex', flexDirection:'column', gap:6}}>
          <div>● <strong style={{color:'var(--leaf)'}}>Local-first</strong> — runs entirely on the lab machine.</div>
          <div>● <strong style={{color:'var(--leaf)'}}>No cloud upload required</strong> — all data, snapshots, and alerts persist locally.</div>
          <div>● <strong style={{color:'var(--leaf)'}}>Data stays inside the lab environment</strong> — exports are explicit, on-demand JSON downloads.</div>
        </div>
      </div>
    </div>
  );
}

function ToggleRow({ label, desc, on, disabled, onChange }) {
  return (
    <div className="toggle-row">
      <div>
        <div className="name">{label}{disabled && <span style={{marginLeft:8, fontFamily:'var(--mono)', fontSize:10, color:'var(--amber)', textTransform:'uppercase', letterSpacing:'0.1em'}}>planned</span>}</div>
        <div className="desc">{desc}</div>
      </div>
      <div className={`switch ${on?'on':''} ${disabled?'disabled':''}`} onClick={()=>!disabled && onChange(!on)}/>
    </div>
  );
}

function TestRunner({ runTests }) {
  const [results, setResults] = useState(null);
  const [running, setRunning] = useState(false);
  const run = async () => {
    setRunning(true); setResults(null);
    await new Promise(r=>setTimeout(r, 200));
    const out = runTests();
    setResults(out); setRunning(false);
  };
  return (
    <div>
      <button className="btn btn-primary" onClick={run} disabled={running}>{running?'Running…':'Run tests'}</button>
      {results && (
        <div style={{marginTop:14}}>
          <div style={{fontFamily:'var(--mono)', fontSize:11, color:'var(--muted)', marginBottom:8}}>
            {results.filter(t=>t.pass).length} passed · {results.filter(t=>!t.pass).length} failed · {results.length} total
          </div>
          {results.map((t,i) => (
            <div key={i} className="test-row">
              <span className={t.pass?'pass':'fail'}>{t.pass?'✔':'✘'}</span>
              <span>{t.name}</span>
              <span style={{color: t.pass?'var(--leaf)':'var(--strawberry)'}}>{t.pass?'PASS':'FAIL: '+t.error}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function downloadJSON(filename, data) {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a'); a.href = url; a.download = filename; a.click();
  setTimeout(()=>URL.revokeObjectURL(url), 1000);
}

window.YPages2 = { SettingsPage };
