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

const blank = { name: '', description: '', logoUrl: '' };

export default function AdminVendors() {
  const toast = useToast();
  const confirm = useConfirm();
  const [vendors, setVendors] = 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));
  useEffect(() => { load(); }, []);

  const startEdit = (v) => {
    setEditingId(v.id);
    setForm({ name: v.name || '', description: v.description || '', logoUrl: v.logoUrl || '' });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

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

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);
    try {
      if (editingId) {
        await api.patch(`/vendors/${editingId}`, form);
        toast.success('Vendor updated');
      } else {
        await api.post('/vendors', form);
        toast.success('Vendor added');
      }
      cancelEdit();
      load();
    } catch (err) {
      toast.error(err.message);
    } finally {
      setBusy(false);
    }
  };

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

  return (
    <div className="grid admin-split">
      <div className="card">
        <h3>{editingId ? 'Edit vendor' : 'Add vendor'}</h3>
        <form onSubmit={submit}>
          <div className="field">
            <label className="label">Name</label>
            <input className="input" value={form.name} required
              onChange={(e) => setForm({ ...form, name: e.target.value })} placeholder="e.g. Microsoft" />
          </div>
          <div className="field">
            <label className="label">Description</label>
            <textarea className="textarea" value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })} placeholder="Short description" />
          </div>
          <div className="field">
            <label className="label">Logo URL (optional)</label>
            <input className="input" value={form.logoUrl}
              onChange={(e) => setForm({ ...form, logoUrl: e.target.value })} placeholder="https://…" />
          </div>
          <button className="btn btn-block" disabled={busy}>
            {busy ? 'Saving…' : editingId ? 'Save changes' : 'Add vendor'}
          </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>Vendor</th><th>Courses</th><th>Actions</th></tr></thead>
          <tbody>
            {vendors.map((v) => (
              <tr key={v.id}>
                <td><b>{v.name}</b><div className="muted" style={{ fontSize: '0.85rem' }}>{v.description}</div></td>
                <td>{v._count?.courses || 0}</td>
                <td>
                  <div className="table-actions">
                    <button className="btn btn-sm btn-ghost" onClick={() => startEdit(v)}>Edit</button>
                    <button className="btn btn-sm btn-danger" onClick={() => remove(v.id)}>Delete</button>
                  </div>
                </td>
              </tr>
            ))}
            {vendors.length === 0 && <tr><td colSpan="3" className="muted">No vendors yet.</td></tr>}
          </tbody>
        </table>
        </div>
      </div>
    </div>
  );
}
