import { useState } from 'react';

const LETTERS = ['A', 'B', 'C', 'D', 'E', 'F'];

const emptyOption = () => ({ text: '', isCorrect: false });

export default function QuestionForm({ initial, onSubmit, submitLabel = 'Save question', busy, showCategory = true }) {
  const [text, setText] = useState(initial?.text || '');
  const [explanation, setExplanation] = useState(initial?.explanation || '');
  const [type, setType] = useState(initial?.type || 'SINGLE');
  const [category, setCategory] = useState(initial?.category || 'PRACTICE');
  const [options, setOptions] = useState(
    initial?.options?.length ? initial.options.map((o) => ({ text: o.text, isCorrect: o.isCorrect })) : [emptyOption(), emptyOption()]
  );
  const [error, setError] = useState('');

  const setOpt = (i, patch) =>
    setOptions((opts) => opts.map((o, idx) => (idx === i ? { ...o, ...patch } : o)));

  const toggleCorrect = (i) => {
    setOptions((opts) =>
      opts.map((o, idx) => {
        if (type === 'SINGLE') return { ...o, isCorrect: idx === i };
        return idx === i ? { ...o, isCorrect: !o.isCorrect } : o;
      })
    );
  };

  const addOption = () => options.length < 6 && setOptions((o) => [...o, emptyOption()]);
  const removeOption = (i) => options.length > 2 && setOptions((o) => o.filter((_, idx) => idx !== i));

  const submit = (e) => {
    e.preventDefault();
    setError('');
    const cleaned = options.map((o) => ({ ...o, text: o.text.trim() })).filter((o) => o.text);
    if (!text.trim()) return setError('Question text is required.');
    if (cleaned.length < 2) return setError('Provide at least 2 options.');
    const correct = cleaned.filter((o) => o.isCorrect).length;
    if (correct === 0) return setError('Mark at least one option as correct.');
    if (type === 'SINGLE' && correct > 1) return setError('Single-answer questions can have only one correct option.');
    onSubmit({ text: text.trim(), explanation: explanation.trim() || null, type, category, options: cleaned });
  };

  return (
    <form onSubmit={submit}>
      {error && <div className="alert alert-error">{error}</div>}

      <div className="field">
        <label className="label">Question</label>
        <textarea className="textarea" value={text} onChange={(e) => setText(e.target.value)}
          placeholder="Type the question here…" required />
      </div>

      {showCategory && (
        <div className="field">
          <label className="label">Question bank</label>
          <select className="select" value={category} onChange={(e) => setCategory(e.target.value)}>
            <option value="PRACTICE">Practice</option>
            <option value="EXAM">Exam</option>
          </select>
          <span className="muted" style={{ fontSize: '0.82rem' }}>
            Practice and Exam questions are kept in separate banks.
          </span>
        </div>
      )}

      <div className="field">
        <label className="label">Answer type</label>
        <select className="select" value={type} onChange={(e) => {
          const t = e.target.value;
          setType(t);
          if (t === 'SINGLE') {
            // keep only first correct
            let seen = false;
            setOptions((opts) => opts.map((o) => {
              if (o.isCorrect && !seen) { seen = true; return o; }
              return { ...o, isCorrect: false };
            }));
          }
        }}>
          <option value="SINGLE">Single answer</option>
          <option value="MULTIPLE">Multiple answers</option>
        </select>
      </div>

      <label className="label">Options <span className="muted">(tick the correct one{type === 'MULTIPLE' ? 's' : ''})</span></label>
      {options.map((o, i) => (
        <div key={i} className="row mb-2" style={{ alignItems: 'center', gap: 10 }}>
          <input
            type={type === 'SINGLE' ? 'radio' : 'checkbox'}
            checked={o.isCorrect}
            onChange={() => toggleCorrect(i)}
            name="correct"
            title="Mark correct"
            style={{ width: 20, height: 20 }}
          />
          <span className="option-marker" style={{ flex: '0 0 26px' }}>{LETTERS[i]}</span>
          <input className="input" value={o.text} placeholder={`Option ${LETTERS[i]}`}
            onChange={(e) => setOpt(i, { text: e.target.value })} />
          {options.length > 2 && (
            <button type="button" className="btn btn-sm btn-ghost" onClick={() => removeOption(i)}>✕</button>
          )}
        </div>
      ))}
      {options.length < 6 && (
        <button type="button" className="btn btn-sm btn-ghost mb-2" onClick={addOption}>+ Add option</button>
      )}

      <div className="field mt-2">
        <label className="label">Explanation <span className="muted">(optional)</span></label>
        <textarea className="textarea" value={explanation} onChange={(e) => setExplanation(e.target.value)}
          placeholder="Explain why the correct answer is right…" />
      </div>

      <button className="btn btn-lg" disabled={busy}>{busy ? 'Saving…' : submitLabel}</button>
    </form>
  );
}
