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

function slugifyKey(raw) {
  return String(raw || '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_|_$/g, '')
    .slice(0, 48);
}

export default function AdminPrestigeServer() {
  const [preview, setPreview] = useState(null);
  const [error, setError] = useState('');
  const [message, setMessage] = useState('');
  const [busy, setBusy] = useState(false);

  const [achName, setAchName] = useState('Server Prestige');
  const [achKey, setAchKey] = useState('server_prestige');
  const [achKeyTouched, setAchKeyTouched] = useState(false);
  const [achDescription, setAchDescription] = useState(
    'Survived a Server Prestige wipe. Economy & prestige reset; stats & achievements kept.'
  );
  const [achIcon, setAchIcon] = useState('♛');
  const [password, setPassword] = useState('');
  const [confirmText, setConfirmText] = useState('');

  const loadPreview = async () => {
    const data = await api.adminPrestigeServerPreview();
    setPreview(data.preview);
  };

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const data = await api.adminPrestigeServerPreview();
        if (!cancelled) setPreview(data.preview);
      } catch (err) {
        if (!cancelled) setError(err.message);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const derivedKey = useMemo(() => {
    if (achKeyTouched) return achKey;
    const fromName = slugifyKey(achName);
    return fromName ? `server_${fromName}`.replace(/^server_server_/, 'server_') : 'server_prestige';
  }, [achName, achKey, achKeyTouched]);

  const canSubmit =
    !busy &&
    achName.trim() &&
    achDescription.trim() &&
    password.length >= 1 &&
    confirmText.trim().toUpperCase() === 'PRESTIGE SERVER';

  const onSubmit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;
    setError('');
    setMessage('');
    setBusy(true);
    try {
      const result = await api.adminPrestigeServer({
        password,
        achievement: {
          key: derivedKey,
          name: achName.trim(),
          description: achDescription.trim(),
          icon: achIcon.trim() || '♛',
        },
      });
      setPassword('');
      setConfirmText('');
      setMessage(
        `Server Prestige done · ${result.playersReset} players reset · achievement “${result.achievement.name}” granted`
      );
      await loadPreview();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div>
      <div className="section-head">
        <div>
          <h1>Prestige Server</h1>
          <p className="muted">
            Wipe economy &amp; prestige progress for every player. Kept: account (username, password,
            avatar, bio), <strong>Joined</strong>, <strong>play time</strong>,{' '}
            <strong>last connection</strong>, <strong>cases opened</strong>,{' '}
            <strong>jackpot / battle wins</strong>, and <strong>achievements</strong>. Then grants the
            wipe achievement configured below.
          </p>
        </div>
      </div>

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

      {preview && (
        <div className="admin-stat-grid" style={{ marginBottom: '1.25rem' }}>
          <div className="admin-stat">
            <span className="admin-stat-label">Players to reset</span>
            <strong>{preview.players}</strong>
          </div>
          <div className="admin-stat">
            <span className="admin-stat-label">Inventory wiped</span>
            <strong>{preview.inventoryItems}</strong>
          </div>
          <div className="admin-stat">
            <span className="admin-stat-label">Prestige logs wiped</span>
            <strong>{preview.prestigeLogs}</strong>
          </div>
          <div className="admin-stat">
            <span className="admin-stat-label">Stats txs kept</span>
            <strong>{preview.statsTransactionsKept}</strong>
            <span className="muted">opens / battle wins</span>
          </div>
        </div>
      )}

      <form className="admin-block form" onSubmit={onSubmit}>
        <h2>Wipe achievement</h2>
        <p className="muted">
          Configure this before activating. Every reset player receives it (existing achievements
          stay).
        </p>

        <div className="admin-form-grid">
          <label>
            Name
            <input
              value={achName}
              onChange={(e) => setAchName(e.target.value)}
              required
              maxLength={80}
              placeholder="Server Prestige"
            />
          </label>
          <label>
            Icon
            <input
              value={achIcon}
              onChange={(e) => setAchIcon(e.target.value)}
              maxLength={8}
              placeholder="♛"
            />
          </label>
          <label className="admin-form-span">
            Key (unique id)
            <input
              value={derivedKey}
              onChange={(e) => {
                setAchKeyTouched(true);
                setAchKey(slugifyKey(e.target.value));
              }}
              maxLength={48}
              placeholder="server_prestige"
            />
          </label>
          <label className="admin-form-span">
            Description
            <textarea
              value={achDescription}
              onChange={(e) => setAchDescription(e.target.value)}
              required
              maxLength={240}
              rows={3}
            />
          </label>
        </div>

        <h2 style={{ marginTop: '1.5rem' }}>Confirm activation</h2>
        <p className="muted">
          Type <strong>PRESTIGE SERVER</strong> and enter the admin password. This cannot be undone.
        </p>

        <div className="admin-form-grid">
          <label className="admin-form-span">
            Confirmation phrase
            <input
              value={confirmText}
              onChange={(e) => setConfirmText(e.target.value)}
              placeholder="PRESTIGE SERVER"
              autoComplete="off"
            />
          </label>
          <label className="admin-form-span">
            Admin password
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              autoComplete="current-password"
            />
          </label>
        </div>

        <div className="row-actions" style={{ marginTop: '1rem' }}>
          <button type="submit" className="btn" disabled={!canSubmit}>
            {busy ? 'Wiping…' : 'Activate Prestige Server'}
          </button>
        </div>
      </form>
    </div>
  );
}
