'use client';

import { useState } from 'react';

export default function AdminInstanceSettings({
  initialSignupsOpen,
}: {
  initialSignupsOpen: boolean;
}) {
  const [signupsOpen, setSignupsOpen] = useState(initialSignupsOpen);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  const toggle = async (next: boolean) => {
    setSaving(true);
    setError('');
    const previous = signupsOpen;
    setSignupsOpen(next); // optimistic
    try {
      const res = await fetch('/api/admin/signups', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ signupsOpen: next }),
      });
      if (!res.ok) {
        setSignupsOpen(previous);
        const body = await res.json().catch(() => ({}));
        setError(body.error ?? `Save failed (${res.status})`);
      }
    } catch (e) {
      setSignupsOpen(previous);
      setError('Network error');
    } finally {
      setSaving(false);
    }
  };

  return (
    <section className="bg-zinc-900 rounded border border-zinc-800 p-6 space-y-4">
      <header>
        <h2 className="text-sm font-semibold text-white uppercase tracking-wider">
          Instance settings
        </h2>
        <p className="text-xs text-zinc-500 mt-1">
          Admin only. Visible to admin accounts only.
        </p>
      </header>

      <div className="flex items-start justify-between gap-4">
        <div className="flex-1">
          <p className="text-sm font-medium text-white">Allow new sign-ups</p>
          <p className="text-xs text-zinc-500 mt-1">
            When enabled, anyone with the URL can create an account on this
            instance. New users start with the curated exercise library and
            no admin privileges.
          </p>
        </div>
        <button
          type="button"
          role="switch"
          aria-checked={signupsOpen}
          onClick={() => toggle(!signupsOpen)}
          disabled={saving}
          className={`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors ${
            signupsOpen ? 'bg-white' : 'bg-zinc-700'
          } disabled:opacity-50`}
        >
          <span
            className={`inline-block h-4 w-4 transform rounded-full bg-zinc-900 transition-transform ${
              signupsOpen ? 'translate-x-6' : 'translate-x-1'
            }`}
          />
        </button>
      </div>

      {error && (
        <div className="rounded bg-red-900/50 px-3 py-2 border border-red-800 text-xs text-red-400">
          {error}
        </div>
      )}

      <div className="pt-4 border-t border-zinc-800">
        <a
          href="/main/admin/users"
          className="inline-block text-xs uppercase tracking-wider text-white underline hover:text-zinc-300"
        >
          Manage users &rarr;
        </a>
      </div>
    </section>
  );
}
