import { useEffect, useState } from 'react';
import api from '../../api/client.js';
import { useToast } from '../../context/ToastContext.jsx';

export default function AdminImport() {
  const toast = useToast();
  const [courses, setCourses] = useState([]);
  const [courseId, setCourseId] = useState('');
  const [category, setCategory] = useState('PRACTICE');
  const [file, setFile] = useState(null);
  const [busy, setBusy] = useState(false);
  const [result, setResult] = useState(null);

  useEffect(() => {
    api.get('/courses/admin/all').then(({ data }) => setCourses(data.courses));
  }, []);

  const downloadTemplate = async (format) => {
    try {
      const { data } = await api.get('/questions/template', {
        params: { format },
        responseType: 'blob',
      });
      const url = URL.createObjectURL(data);
      const a = document.createElement('a');
      a.href = url;
      a.download = `questions-template.${format}`;
      document.body.appendChild(a);
      a.click();
      a.remove();
      URL.revokeObjectURL(url);
    } catch {
      toast.error('Could not download template');
    }
  };

  const upload = async (e) => {
    e.preventDefault();
    if (!courseId || !file) return toast.error('Choose a course and a file');
    setBusy(true);
    setResult(null);
    try {
      const fd = new FormData();
      fd.append('file', file);
      fd.append('courseId', courseId);
      fd.append('category', category);
      const { data } = await api.post('/questions/import', fd, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      setResult(data);
      toast.success(data.message);
    } catch (err) {
      toast.error(err.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="grid admin-split admin-split--even">
      <div className="card">
        <h3>Import questions</h3>
        <p className="muted">Upload a CSV or Excel file to bulk-add approved questions to a course.</p>
        <form onSubmit={upload}>
          <div className="field">
            <label className="label">Target course / exam</label>
            <select className="select" value={courseId} onChange={(e) => setCourseId(e.target.value)} required>
              <option value="">Select course…</option>
              {courses.map((c) => <option key={c.id} value={c.id}>{c.vendor.name} — {c.title}</option>)}
            </select>
          </div>
          <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' }}>
              Applied to every row in the uploaded file.
            </span>
          </div>
          <div className="field">
            <label className="label">File (.csv, .xlsx)</label>
            <input className="input" type="file" accept=".csv,.xls,.xlsx"
              onChange={(e) => setFile(e.target.files[0])} required />
          </div>
          <button className="btn btn-block" disabled={busy}>{busy ? 'Importing…' : 'Upload & import'}</button>
        </form>

        {result && (
          <div className="alert alert-success mt-3">
            Imported <b>{result.created}</b> of {result.totalRows} rows.
            {result.skipped?.length > 0 && (
              <div className="mt-2" style={{ color: 'var(--red)' }}>
                Skipped {result.skipped.length} rows:
                <ul style={{ margin: '6px 0 0' }}>
                  {result.skipped.slice(0, 8).map((s, i) => <li key={i}>Row {s.row}: {s.error}</li>)}
                </ul>
              </div>
            )}
          </div>
        )}
      </div>

      <div className="card">
        <h3>Expected format</h3>
        <p className="muted">First row = headers. Columns (case-insensitive):</p>
        <ul className="muted">
          <li><b>question</b> — the question text (required)</li>
          <li><b>option1…option6</b> or <b>optionA…optionF</b> (≥ 2)</li>
          <li><b>correct</b> — e.g. <code>A</code> or <code>A,C</code> or <code>1,3</code></li>
          <li><b>explanation</b> — optional</li>
          <li><b>type</b> — <code>single</code> / <code>multiple</code> (optional)</li>
        </ul>
        <p className="muted" style={{ fontSize: '0.82rem' }}>
          Practice vs. Exam is set by the <b>Question bank</b> selector — no column needed.
        </p>
        <div className="alert alert-info code-sample">
{`question,option1,option2,option3,option4,correct,explanation,type
"Default HTTPS port?","80","443","22","21","B","HTTPS uses 443",single`}
        </div>
        <p className="muted">Download a ready-made template with example rows:</p>
        <div className="row wrap" style={{ gap: 8 }}>
          <button type="button" className="btn btn-sm btn-ghost" onClick={() => downloadTemplate('csv')}>
            ⬇ CSV template
          </button>
          <button type="button" className="btn btn-sm btn-ghost" onClick={() => downloadTemplate('xlsx')}>
            ⬇ Excel template
          </button>
        </div>
      </div>
    </div>
  );
}
