import { useCallback, useEffect, useState } from 'react';
import { api } from '../api';

function emptyEdit(pack) {
  return {
    name: pack.name || '',
    osu: pack.osu ?? 0,
    priceCents: pack.priceCents ?? 0,
    currency: pack.currency || 'eur',
    badge: pack.badge || '',
    blurb: pack.blurb || '',
    perOsuLabel: pack.perOsuLabel || '',
    enabled: Boolean(pack.enabled),
    sortOrder: pack.sortOrder ?? 0,
  };
}

export default function AdminShop() {
  const [sectionEnabled, setSectionEnabled] = useState(true);
  const [packs, setPacks] = useState([]);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [busy, setBusy] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [edit, setEdit] = useState(null);

  const load = useCallback(async () => {
    const data = await api.adminShopOsuPacks();
    setSectionEnabled(Boolean(data.sectionEnabled));
    setPacks(data.packs || []);
  }, []);

  useEffect(() => {
    load().catch((err) => setError(err.message));
  }, [load]);

  const toggleSection = async () => {
    setBusy(true);
    setError('');
    setMessage('');
    try {
      const data = await api.adminShopOsuSection(!sectionEnabled);
      setSectionEnabled(Boolean(data.sectionEnabled));
      setPacks(data.packs || []);
      setMessage(
        data.sectionEnabled
          ? 'Get osu section enabled on the shop'
          : 'Get osu section disabled on the shop'
      );
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  const togglePack = async (pack) => {
    setBusy(true);
    setError('');
    try {
      const data = await api.adminUpdateShopOsuPack(pack.id, { enabled: !pack.enabled });
      setPacks((prev) => prev.map((p) => (p.id === pack.id ? data.pack : p)));
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  const saveEdit = async (e) => {
    e.preventDefault();
    if (!editingId || !edit) return;
    setBusy(true);
    setError('');
    setMessage('');
    try {
      const data = await api.adminUpdateShopOsuPack(editingId, {
        name: edit.name,
        osu: Number(edit.osu),
        priceCents: Number(edit.priceCents),
        currency: edit.currency,
        badge: edit.badge || null,
        blurb: edit.blurb,
        perOsuLabel: edit.perOsuLabel,
        enabled: Boolean(edit.enabled),
        sortOrder: Number(edit.sortOrder),
      });
      setPacks((prev) => prev.map((p) => (p.id === editingId ? data.pack : p)));
      setEditingId(null);
      setEdit(null);
      setMessage(`Saved ${data.pack.name}`);
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div>
      <div className="section-head">
        <div>
          <h1>Shop · osu packs</h1>
          <p className="muted">
            Configure real-money → osu top-ups shown on /shop. Disable the whole section or
            individual packs.
          </p>
        </div>
        <button
          type="button"
          className={`btn${sectionEnabled ? ' danger' : ''}`}
          disabled={busy}
          onClick={toggleSection}
        >
          {sectionEnabled ? 'Disable Get osu section' : 'Enable Get osu section'}
        </button>
      </div>

      {error && <div className="error">{error}</div>}
      {message && <div className="ok-msg">{message}</div>}

      {!sectionEnabled && (
        <div className="admin-block">
          <p className="muted" style={{ margin: 0 }}>
            The <strong>Get osu</strong> grid is hidden for players. Packs below can still be
            edited.
          </p>
        </div>
      )}

      <div className="admin-card-list">
        {packs.map((pack) => (
          <div key={pack.id} className="admin-block">
            {editingId === pack.id && edit ? (
              <form className="form admin-form-grid" onSubmit={saveEdit}>
                <h3 className="admin-form-span">
                  Edit {pack.id}
                </h3>
                <label>
                  Name
                  <input
                    value={edit.name}
                    onChange={(e) => setEdit({ ...edit, name: e.target.value })}
                    required
                  />
                </label>
                <label>
                  Osu amount
                  <input
                    type="number"
                    min="1"
                    step="1"
                    value={edit.osu}
                    onChange={(e) => setEdit({ ...edit, osu: e.target.value })}
                    required
                  />
                </label>
                <label>
                  Price (EUR cents)
                  <input
                    type="number"
                    min="0"
                    step="1"
                    value={edit.priceCents}
                    onChange={(e) => setEdit({ ...edit, priceCents: e.target.value })}
                    required
                  />
                </label>
                <label>
                  Currency
                  <input
                    value={edit.currency}
                    onChange={(e) => setEdit({ ...edit, currency: e.target.value })}
                    required
                  />
                </label>
                <label>
                  Badge
                  <input
                    value={edit.badge}
                    onChange={(e) => setEdit({ ...edit, badge: e.target.value })}
                    placeholder="Popular, Best value…"
                  />
                </label>
                <label>
                  Sort order
                  <input
                    type="number"
                    step="1"
                    value={edit.sortOrder}
                    onChange={(e) => setEdit({ ...edit, sortOrder: e.target.value })}
                  />
                </label>
                <label className="admin-form-span">
                  Blurb
                  <input
                    value={edit.blurb}
                    onChange={(e) => setEdit({ ...edit, blurb: e.target.value })}
                  />
                </label>
                <label className="admin-form-span">
                  Per-osu label
                  <input
                    value={edit.perOsuLabel}
                    onChange={(e) => setEdit({ ...edit, perOsuLabel: e.target.value })}
                    placeholder="€0.10 / osu"
                  />
                </label>
                <label className="admin-form-span" style={{ flexDirection: 'row', gap: '0.5rem' }}>
                  <input
                    type="checkbox"
                    checked={edit.enabled}
                    onChange={(e) => setEdit({ ...edit, enabled: e.target.checked })}
                  />
                  Pack enabled
                </label>
                <div className="row-actions admin-form-span">
                  <button className="btn" type="submit" disabled={busy}>
                    Save
                  </button>
                  <button
                    type="button"
                    className="btn secondary"
                    onClick={() => {
                      setEditingId(null);
                      setEdit(null);
                    }}
                  >
                    Cancel
                  </button>
                </div>
              </form>
            ) : (
              <div className="admin-row">
                <div className="admin-row-main">
                  <strong>
                    {pack.name}{' '}
                    <span className="muted">({pack.id})</span>
                  </strong>
                  <div className="muted">
                    {pack.osu} osu · {pack.displayPrice} · sort {pack.sortOrder}
                    {pack.badge ? ` · ${pack.badge}` : ''}
                    {' · '}
                    <span className={pack.enabled ? 'admin-pill-on' : 'admin-pill-off'}>
                      {pack.enabled ? 'enabled' : 'disabled'}
                    </span>
                  </div>
                  {pack.blurb ? <div className="muted">{pack.blurb}</div> : null}
                </div>
                <button
                  type="button"
                  className="btn secondary"
                  disabled={busy}
                  onClick={() => {
                    setEditingId(pack.id);
                    setEdit(emptyEdit(pack));
                  }}
                >
                  Edit
                </button>
                <button
                  type="button"
                  className={`btn${pack.enabled ? ' ghost' : ''}`}
                  disabled={busy}
                  onClick={() => togglePack(pack)}
                >
                  {pack.enabled ? 'Disable' : 'Enable'}
                </button>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
