import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import api from '../../api/client.js';
import { useToast } from '../../context/ToastContext.jsx';
import { useConfirm } from '../../context/ConfirmContext.jsx';

const blank = { vendorId: '', title: '', code: '', description: '', price: '', isFree: false, freeQuestionLimit: 5, examMinutes: 0 };

export default function AdminCourses() {
  const toast = useToast();
  const confirm = useConfirm();
  const [vendors, setVendors] = useState([]);
  const [courses, setCourses] = useState([]);
  const [form, setForm] = useState(blank);
  const [editingId, setEditingId] = useState(null);
  const [busy, setBusy] = useState(false);

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

  const startEdit = (c) => {
    setEditingId(c.id);
    setForm({
      vendorId: c.vendorId || c.vendor?.id || '',
      title: c.title || '',
      code: c.code || '',
      description: c.description || '',
      price: c.priceCents ? (c.priceCents / 100).toString() : '',
      isFree: c.isFree || c.priceCents === 0,
      freeQuestionLimit: c.freeQuestionLimit ?? 5,
      examMinutes: c.examMinutes ?? 0,
    });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const cancelEdit = () => {
    setEditingId(null);
    setForm(blank);
  };

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      const priceCents = form.isFree ? 0 : Math.round(parseFloat(form.price || '0') * 100);
      const payload = {
        vendorId: form.vendorId,
        title: form.title,
        code: form.code || null,
        description: form.description || null,
        priceCents,
        isFree: form.isFree,
        freeQuestionLimit: Number(form.freeQuestionLimit),
        examMinutes: Number(form.examMinutes) || 0,
      };
      if (editingId) {
        await api.patch(`/courses/${editingId}`, payload);
        toast.success('Course / exam updated');
      } else {
        await api.post('/courses', payload);
        toast.success('Course / exam created');
      }
      cancelEdit();
      load();
    } catch (err) {
      toast.error(err.message);
    } finally {
      setBusy(false);
    }
  };

  const remove = async (id) => {
    const ok = await confirm({
      title: 'Delete this course?',
      message: 'The course and all of its practice and exam questions will be permanently deleted.',
      confirmLabel: 'Delete course',
      tone: 'danger',
    });
    if (!ok) return;
    try {
      await api.delete(`/courses/${id}`);
      toast.success('Course deleted');
      if (editingId === id) cancelEdit();
      load();
    } catch (err) {
      toast.error(err.message);
    }
  };

  return (
    <div className="grid admin-split">
      <div className="card">
        <h3>{editingId ? 'Edit course / exam' : 'Add course / exam'}</h3>
        <form onSubmit={submit}>
          <div className="field">
            <label className="label">Vendor</label>
            <select className="select" value={form.vendorId} required
              onChange={(e) => setForm({ ...form, vendorId: e.target.value })}>
              <option value="">Select vendor…</option>
              {vendors.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
            </select>
          </div>
          <div className="field">
            <label className="label">Title</label>
            <input className="input" value={form.title} required
              onChange={(e) => setForm({ ...form, title: e.target.value })} placeholder="e.g. CCNP Enterprise" />
          </div>
          <div className="field">
            <label className="label">Exam code (optional)</label>
            <input className="input" value={form.code}
              onChange={(e) => setForm({ ...form, code: e.target.value })} placeholder="e.g. 350-401" />
          </div>
          <div className="field">
            <label className="label">Description</label>
            <textarea className="textarea" value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })} />
          </div>
          <div className="field">
            <label className="label">Exam time limit (minutes)</label>
            <input className="input" type="number" min="0" max="600" value={form.examMinutes}
              onChange={(e) => setForm({ ...form, examMinutes: e.target.value })} placeholder="e.g. 90" />
            <span className="muted" style={{ fontSize: '0.82rem' }}>
              Total time for the whole exam. 0 = no fixed limit (falls back to 1 minute per question).
            </span>
          </div>
          <div className="field">
            <label className="label" style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <input type="checkbox" checked={form.isFree}
                onChange={(e) => setForm({ ...form, isFree: e.target.checked })} />
              Free exam (no payment)
            </label>
          </div>
          {!form.isFree && (
            <div className="row">
              <div className="field" style={{ flex: 1 }}>
                <label className="label">Price (USD)</label>
                <input className="input" type="number" min="0" step="0.01" value={form.price}
                  onChange={(e) => setForm({ ...form, price: e.target.value })} placeholder="19.99" />
              </div>
              <div className="field" style={{ flex: 1 }}>
                <label className="label">Free preview Qs</label>
                <input className="input" type="number" min="0" value={form.freeQuestionLimit}
                  onChange={(e) => setForm({ ...form, freeQuestionLimit: e.target.value })} />
              </div>
            </div>
          )}
          <button className="btn btn-block" disabled={busy}>
            {busy ? 'Saving…' : editingId ? 'Save changes' : 'Create course'}
          </button>
          {editingId && (
            <button type="button" className="btn btn-ghost btn-block mt-2" onClick={cancelEdit}>Cancel</button>
          )}
        </form>
      </div>

      <div className="card table-card">
        <div className="table-scroll">
        <table className="table">
          <thead><tr><th>Exam</th><th>Vendor</th><th>Price</th><th>Qs</th><th>Actions</th></tr></thead>
          <tbody>
            {courses.map((c) => (
              <tr key={c.id}>
                <td><b>{c.title}</b>{c.code && <span className="badge" style={{ marginLeft: 6 }}>{c.code}</span>}</td>
                <td className="muted">{c.vendor.name}</td>
                <td>{c.isFree || c.priceCents === 0 ? <span className="badge badge-free">Free</span> : `$${(c.priceCents / 100).toFixed(2)}`}</td>
                <td>{c._count?.questions || 0}</td>
                <td>
                  <div className="table-actions">
                    <Link to={`/admin/courses/${c.id}/questions`} className="btn btn-sm btn-ghost">Questions</Link>
                    <button className="btn btn-sm btn-ghost" onClick={() => startEdit(c)}>Edit</button>
                    <button className="btn btn-sm btn-danger" onClick={() => remove(c.id)}>Delete</button>
                  </div>
                </td>
              </tr>
            ))}
            {courses.length === 0 && <tr><td colSpan="5" className="muted">No courses yet.</td></tr>}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}
