"use client";

/**
 * OrgOnboardingClient — Create org / Join with code, plus explicit-Accept for any
 * pending email invites. Two stacked, equal-weight options (no AI-slop card grid).
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';

export default function OrgOnboardingClient({ email = '', pendingInvites = [] }) {
  const router = useRouter();
  const [name, setName] = useState('');
  const [code, setCode] = useState('');
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  // Link-join completion is handled server-side: the token rides an httpOnly
  // cookie set by /api/auth/join-bootstrap and is redeemed by
  // /api/orgs/join-complete (routed from the onboarding page when the cookie is
  // present). No client-side token handling here.

  async function createOrg(e) {
    e.preventDefault();
    setError('');
    setBusy('create');
    try {
      const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'org';
      const res = await fetch('/api/orgs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), slug }),
      });
      if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || 'Could not create organization');
      router.push('/');
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy('');
    }
  }

  async function joinWithCode(e) {
    e.preventDefault();
    setError('');
    setBusy('join');
    try {
      const res = await fetch('/api/orgs/join', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token: code.trim() }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.message || 'This invite is invalid or has expired.');
      router.push('/');
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy('');
    }
  }

  async function acceptPending() {
    setError('');
    setBusy('accept');
    try {
      const res = await fetch('/api/orgs/invites/pending', { method: 'POST' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.message || data.error || "Couldn't accept the invite.");
      router.push('/');
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy('');
    }
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, maxWidth: 560 }}>
      {error ? (
        <div className="admin-panel" role="alert" style={{ borderColor: 'var(--accent-500)' }}>
          {error}
        </div>
      ) : null}

      {pendingInvites.length > 0 ? (
        <div className="admin-panel">
          <div className="admin-panel-head">Pending invitations</div>
          {pendingInvites.map((inv) => (
            <div key={inv.id} className="admin-record">
              <div>
                <strong>{inv.org_name || inv.org_id}</strong> invited you · {inv.role}
              </div>
              <button className="admin-btn-primary admin-btn-sm" disabled={busy === 'accept'} onClick={acceptPending}>
                {busy === 'accept' ? 'Joining…' : 'Accept'}
              </button>
            </div>
          ))}
        </div>
      ) : null}

      <form className="admin-panel" onSubmit={createOrg}>
        <div className="admin-panel-head">Create an organization</div>
        <p className="account-meta">Start fresh. You'll be the owner.</p>
        <label htmlFor="org-name" style={{ display: 'block', marginBottom: 6 }}>Organization name</label>
        <input
          id="org-name"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Acme Robotics"
          required
          style={{ width: '100%', marginBottom: 12 }}
        />
        <button className="admin-btn-primary" type="submit" disabled={busy === 'create' || !name.trim()}>
          {busy === 'create' ? 'Creating…' : 'Create org →'}
        </button>
      </form>

      <form className="admin-panel" onSubmit={joinWithCode}>
        <div className="admin-panel-head">Join with an invite</div>
        <p className="account-meta">Paste an invite code, or open the invite link you were sent.</p>
        <label htmlFor="invite-code" style={{ display: 'block', marginBottom: 6 }}>Invite code</label>
        <input
          id="invite-code"
          value={code}
          onChange={(e) => setCode(e.target.value)}
          placeholder="paste invite code"
          style={{ width: '100%', marginBottom: 12 }}
        />
        <button className="admin-btn-primary" type="submit" disabled={busy === 'join' || !code.trim()}>
          {busy === 'join' ? 'Joining…' : 'Join →'}
        </button>
      </form>
    </div>
  );
}
