const QB_TYPES = ['Objective', 'Fill Blanks', 'Match', 'Drag & Drop', 'Select Answer'];
const QB_DIFFS = ['Easy', 'Medium', 'Difficult'];

function QuestionBank({ onNavigate }) {
  const [trade, setTrade] = React.useState('Fitter');
  const [diff, setDiff] = React.useState('All');
  const [selected, setSelected] = React.useState({});
  const [adding, setAdding] = React.useState(false);
  const [draft, setDraft] = React.useState({ q: '', type: 'Objective', diff: 'Easy', topic: '', marks: 1 });
  const nextId = React.useRef(150);

  const trades = ['Fitter', 'Electrician', 'Welder', 'Turner', 'COPA'];
  const diffs = ['All', 'Easy', 'Medium', 'Difficult'];

  const types = {
    Objective: 'var(--navy-700)', 'Fill Blanks': 'var(--saffron-600)', 'Match': 'var(--green-600)',
    'Drag & Drop': 'var(--navy-600)', 'Select Answer': 'var(--red-600)',
  };

  const [questions, setQuestions] = React.useState([
    { id: 'FTR-0142', q: 'Which file is used for finishing a flat surface?', type: 'Objective', diff: 'Easy', topic: 'Bench Work', marks: 1 },
    { id: 'FTR-0143', q: 'The included angle of a centre punch is ____ degrees.', type: 'Fill Blanks', diff: 'Medium', topic: 'Marking', marks: 1 },
    { id: 'FTR-0144', q: 'Match the fit type to its allowance value.', type: 'Match', diff: 'Difficult', topic: 'Fits & Tolerances', marks: 2 },
    { id: 'FTR-0145', q: 'Arrange the drilling operation steps in correct sequence.', type: 'Drag & Drop', diff: 'Medium', topic: 'Drilling', marks: 2 },
    { id: 'FTR-0146', q: 'Select the correct vernier caliper reading from the 3D image.', type: 'Select Answer', diff: 'Medium', topic: 'Measuring', marks: 2 },
    { id: 'FTR-0147', q: 'What is the standard taper for a Morse taper shank?', type: 'Objective', diff: 'Difficult', topic: 'Machining', marks: 2 },
    { id: 'FTR-0148', q: 'Least count of a metric vernier caliper is ____ mm.', type: 'Fill Blanks', diff: 'Easy', topic: 'Measuring', marks: 1 },
    { id: 'FTR-0149', q: 'Identify the correct thread profile for a metric bolt.', type: 'Select Answer', diff: 'Easy', topic: 'Threading', marks: 1 },
  ]);

  const filtered = questions.filter(q => diff === 'All' || q.diff === diff);
  const selCount = Object.values(selected).filter(Boolean).length;
  const selMarks = questions.filter(q => selected[q.id]).reduce((a, q) => a + q.marks, 0);

  const toggle = id => setSelected(s => ({ ...s, [id]: !s[id] }));

  const openAdd = () => { setDraft({ q: '', type: 'Objective', diff: 'Easy', topic: '', marks: 1 }); setAdding(true); };
  const saveQuestion = () => {
    if (!draft.q.trim()) { window.toast('Please enter the question text'); return; }
    const code = trade.slice(0, 3).toUpperCase();
    nextId.current += 1;
    const id = `${code}-${String(nextId.current).padStart(4, '0')}`;
    const rec = { id, q: draft.q.trim(), type: draft.type, diff: draft.diff, topic: draft.topic.trim() || 'General', marks: Number(draft.marks) || 1 };
    setQuestions(qs => [rec, ...qs]);
    setAdding(false);
    window.toast('Question ' + id + ' added to the bank');
  };

  return (
    <div className="content">
      <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 20, gap: 20, flexWrap: 'wrap' }}>
        <div>
          <div className="section-eyebrow">Question Bank</div>
          <h1 className="section-title" style={{ fontSize: 30 }}>500+ questions per trade, NCVT-aligned.</h1>
          <p className="section-sub">Filter by weightage & type, add your own questions, and assign timed tests to your batch.</p>
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <button className="btn btn-ghost" onClick={() => window.toast('CSV import — download the template, fill rows, and upload (demo)')}><window.IconUpload size={13}/> Import (CSV)</button>
          <button className="btn btn-primary" onClick={openAdd}><window.IconPlus size={13}/> Add question</button>
        </div>
      </div>

      {/* Stat row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 20 }}>
        {[
          { k: '512', v: 'Questions in bank', s: 'Fitter trade' },
          { k: '5', v: 'Question types', s: 'MCQ · Fill · Match · Drag · Select' },
          { k: '38', v: 'Added by you', s: 'This academic year' },
          { k: '14', v: 'Tests assigned', s: '3 currently active' },
        ].map(s => (
          <div key={s.v} className="card" style={{ padding: 20 }}>
            <div className="stat-num">{s.k}</div>
            <div className="stat-label">{s.v}</div>
            <div style={{ fontSize: 11, color: 'var(--ink-600)', marginTop: 8 }}>{s.s}</div>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 20 }}>
        {/* Question list */}
        <div className="card">
          <div className="card-header" style={{ flexWrap: 'wrap', gap: 12 }}>
            <div style={{ display: 'flex', gap: 6 }}>
              {trades.map(t => (
                <button key={t} onClick={() => setTrade(t)} style={{ padding: '6px 12px', fontSize: 12, fontWeight: 600, borderRadius: 999, background: trade === t ? 'var(--navy-800)' : 'var(--ink-100)', color: trade === t ? 'white' : 'var(--ink-700)' }}>{t}</button>
              ))}
            </div>
            <div style={{ marginLeft: 'auto', display: 'flex', gap: 4, alignItems: 'center' }}>
              <window.IconFilter size={13} style={{ color: 'var(--ink-500)' }} />
              {diffs.map(d => (
                <button key={d} onClick={() => setDiff(d)} style={{ padding: '5px 10px', fontSize: 11.5, fontWeight: 600, borderRadius: 6, color: diff === d ? 'white' : 'var(--ink-600)', background: diff === d ? (d === 'Easy' ? 'var(--green-600)' : d === 'Difficult' ? 'var(--red-600)' : d === 'Medium' ? 'var(--saffron-500)' : 'var(--navy-700)') : 'transparent', border: diff === d ? 'none' : '1px solid var(--ink-200)' }}>{d}</button>
              ))}
            </div>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--ink-50)', fontFamily: 'var(--font-mono)', fontSize: 10, textAlign: 'left', letterSpacing: '0.08em', color: 'var(--ink-600)' }}>
                <th style={{ padding: '10px 16px', width: 30 }}></th>
                <th style={{ padding: '10px 8px', fontWeight: 600 }}>QUESTION</th>
                <th style={{ padding: '10px 8px', fontWeight: 600 }}>TYPE</th>
                <th style={{ padding: '10px 8px', fontWeight: 600 }}>LEVEL</th>
                <th style={{ padding: '10px 16px', fontWeight: 600 }}>MARKS</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(q => (
                <tr key={q.id} style={{ borderTop: '1px solid var(--ink-100)', background: selected[q.id] ? 'var(--navy-50)' : 'white', cursor: 'pointer' }} onClick={() => toggle(q.id)}>
                  <td style={{ padding: '12px 16px' }}>
                    <div style={{ width: 18, height: 18, borderRadius: 4, border: `2px solid ${selected[q.id] ? 'var(--navy-800)' : 'var(--ink-300)'}`, background: selected[q.id] ? 'var(--navy-800)' : 'white', display: 'grid', placeItems: 'center' }}>
                      {selected[q.id] && <window.IconCheck size={11} style={{ color: 'white' }} />}
                    </div>
                  </td>
                  <td style={{ padding: '12px 8px' }}>
                    <div style={{ fontSize: 13, color: 'var(--ink-900)', fontWeight: 500, lineHeight: 1.35 }}>{q.q}</div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--ink-500)', marginTop: 2 }}>{q.id} · {q.topic}</div>
                  </td>
                  <td style={{ padding: '12px 8px' }}><span className="badge mono" style={{ background: 'var(--ink-100)', color: types[q.type], fontSize: 9 }}>{q.type}</span></td>
                  <td style={{ padding: '12px 8px' }}>
                    <span className={`badge ${q.diff === 'Easy' ? 'green' : q.diff === 'Difficult' ? 'red' : 'saffron'}`} style={{ fontSize: 10 }}>{q.diff}</span>
                  </td>
                  <td style={{ padding: '12px 16px', fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--ink-900)', fontWeight: 600 }}>{q.marks}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Assign test panel */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          <div className="card" style={{ padding: 20, position: 'sticky', top: 20 }}>
            <div className="card-title" style={{ marginBottom: 4 }}>Build a test</div>
            <div style={{ fontSize: 12, color: 'var(--ink-600)', marginBottom: 16 }}>Select questions from the bank to assemble a paper.</div>

            <div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
              <div style={{ flex: 1, padding: 14, background: 'var(--navy-50)', borderRadius: 10, textAlign: 'center' }}>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28, fontWeight: 500, color: 'var(--navy-800)' }}>{selCount}</div>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-600)' }}>Questions</div>
              </div>
              <div style={{ flex: 1, padding: 14, background: 'var(--saffron-100)', borderRadius: 10, textAlign: 'center' }}>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28, fontWeight: 500, color: 'var(--saffron-600)' }}>{selMarks}</div>
                <div style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--ink-600)' }}>Total marks</div>
              </div>
            </div>

            <div style={{ marginBottom: 14 }}>
              {[
                { l: 'Assign to', v: 'Batch F-2024-A (38)' },
                { l: 'Duration', v: '45 minutes · timed' },
                { l: 'Random order', v: 'Enabled' },
                { l: 'Result visibility', v: 'Instructor only' },
              ].map(x => (
                <div key={x.l} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px dashed var(--ink-200)', fontSize: 12.5 }}>
                  <span style={{ color: 'var(--ink-600)' }}>{x.l}</span>
                  <span style={{ color: 'var(--ink-900)', fontWeight: 600 }}>{x.v}</span>
                </div>
              ))}
            </div>

            <button className="btn btn-saffron" disabled={selCount === 0} onClick={() => window.toast('Test assigned — ' + selCount + ' question' + (selCount === 1 ? '' : 's') + ' · ' + selMarks + ' marks · Batch F-2024-A')} style={{ width: '100%', justifyContent: 'center', opacity: selCount === 0 ? 0.5 : 1 }}>
              <window.IconClipboard size={13}/> Assign test to batch
            </button>
            <button className="btn btn-ghost" style={{ width: '100%', justifyContent: 'center', marginTop: 8 }} onClick={() => onNavigate('assess')}>Preview as student</button>
          </div>
        </div>
      </div>

      <window.Modal
        open={adding}
        title="Add a question"
        subtitle={trade + ' · Question Bank'}
        onClose={() => setAdding(false)}
        width={520}
        footer={<>
          <button className="btn btn-ghost" onClick={() => setAdding(false)}>Cancel</button>
          <button className="btn btn-primary" onClick={saveQuestion}><window.IconPlus size={13}/> Add question</button>
        </>}
      >
        <window.Field label="Question">
          <textarea
            value={draft.q}
            onChange={e => setDraft(d => ({ ...d, q: e.target.value }))}
            placeholder="Type the question as it should appear to students…"
            rows={3}
            style={{ ...window.fieldInputStyle, resize: 'vertical', minHeight: 72 }}
          />
        </window.Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <window.Field label="Type">
            <select value={draft.type} onChange={e => setDraft(d => ({ ...d, type: e.target.value }))} style={window.fieldInputStyle}>
              {QB_TYPES.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </window.Field>
          <window.Field label="Difficulty">
            <select value={draft.diff} onChange={e => setDraft(d => ({ ...d, diff: e.target.value }))} style={window.fieldInputStyle}>
              {QB_DIFFS.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          </window.Field>
          <window.Field label="Topic">
            <input value={draft.topic} onChange={e => setDraft(d => ({ ...d, topic: e.target.value }))} placeholder="e.g. Measuring" style={window.fieldInputStyle} />
          </window.Field>
          <window.Field label="Marks">
            <input type="number" min="1" value={draft.marks} onChange={e => setDraft(d => ({ ...d, marks: e.target.value }))} style={window.fieldInputStyle} />
          </window.Field>
        </div>
      </window.Modal>
    </div>
  );
}

window.QuestionBank = QuestionBank;
