/**
 * Create an account.
 *
 * For someone who has an invite code but no account at all — the common case,
 * because the identity provider's own self-registration is deliberately shut.
 * PIG mints the account server-side once the invite validates, then signs the
 * person straight in so they land on the dashboard rather than being returned
 * to a login form having just typed their password.
 */
import { useState } from 'react';
import { ArrowLeft } from 'lucide-react';
import { TEAMS, TEAM_DESCRIPTIONS, TEAM_LABELS, type Team } from '@pig/core';
import { ApiError, getSupabase, post, type PublicConfig } from '@/lib/api';
import { Button, Input } from '@/components/ui';
import { AuthShell } from '@/components/AuthShell';
import { usePageTitle } from '@/lib/title';

export function Register({
  config,
  onBack,
  onRegistered,
}: {
  config: PublicConfig;
  onBack: () => void;
  onRegistered: () => void;
}) {
  usePageTitle('Create account');

  const [form, setForm] = useState({
    name: '',
    email: '',
    password: '',
    inviteCode: '',
    title: '',
  });
  const [team, setTeam] = useState<Team>('demand');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  const set = (key: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm((f) => ({ ...f, [key]: e.target.value }));

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setBusy(true);
    setError(null);

    try {
      await post('/api/register', {
        email: form.email.trim(),
        password: form.password,
        name: form.name.trim(),
        team,
        inviteCode: form.inviteCode.trim(),
        title: form.title.trim() || undefined,
      });

      // Sign in immediately. Making someone re-enter the password they typed
      // ten seconds ago reads as though registration silently failed.
      const supabase = getSupabase();
      if (supabase) {
        await supabase.auth.signInWithPassword({
          email: form.email.trim(),
          password: form.password,
        });
      }
      onRegistered();
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'Could not create your account. Try again.');
    } finally {
      setBusy(false);
    }
  }

  if (!config.canSelfRegister) {
    return (
      <AuthShell onSignIn={onBack}>
        <div className="auth-panel flex flex-col gap-4 rounded-2xl border border-border/80 bg-surface/90 p-6 text-center shadow-2xl backdrop-blur-xl sm:p-8 lg:rounded-none lg:border-0 lg:bg-transparent lg:shadow-none lg:backdrop-blur-none">
          <p className="font-medium">Registration is not open here</p>
          <p className="text-sm text-muted">
            This deployment cannot create accounts on its own. Ask an administrator to provision one
            for you, then sign in.
          </p>
          <Button variant="outline" onClick={onBack} className="w-full">
            Back to sign in
          </Button>
        </div>
      </AuthShell>
    );
  }

  return (
    <AuthShell onSignIn={onBack}>
      <div className="auth-panel rounded-2xl border border-border/80 bg-surface/90 p-5 shadow-2xl backdrop-blur-xl sm:p-7 lg:rounded-none lg:border-0 lg:bg-transparent lg:p-0 lg:shadow-none lg:backdrop-blur-none">
        <div className="flex flex-col gap-2">
          <p className="text-xs font-medium uppercase tracking-[0.14em] text-muted">
            Private workspace
          </p>
          <h1 className="text-3xl font-medium tracking-[-0.035em] sm:text-4xl">
            Create your account
          </h1>
          <p className="text-sm leading-6 text-muted">
            Use an email you control. A valid PIG invite is required before the server creates
            workspace access.
          </p>
          <p className="text-xs leading-5 text-muted">
            This flow does not enable open registration on the shared identity provider.
          </p>
        </div>

        <form onSubmit={submit} className="mt-6 flex flex-col gap-4">
          <label className="block" htmlFor="register-invite-code">
            <span className="mb-1 block text-sm font-medium">Invite code</span>
            <Input
              id="register-invite-code"
              name="inviteCode"
              required
              value={form.inviteCode}
              onChange={set('inviteCode')}
              placeholder="Ask whoever invited you"
              autoCapitalize="off"
              autoCorrect="off"
              spellCheck={false}
            />
          </label>

          <label className="block" htmlFor="register-name">
            <span className="mb-1 block text-sm font-medium">Your name</span>
            <Input
              id="register-name"
              name="name"
              required
              value={form.name}
              onChange={set('name')}
              autoComplete="name"
            />
          </label>

          <label className="block" htmlFor="register-email">
            <span className="mb-1 block text-sm font-medium">Email</span>
            <Input
              id="register-email"
              name="email"
              type="email"
              required
              value={form.email}
              onChange={set('email')}
              placeholder="you@anywhere.com"
              autoComplete="email"
              autoCapitalize="off"
              autoCorrect="off"
              spellCheck={false}
            />
          </label>

          <label className="block" htmlFor="register-password">
            <span className="mb-1 block text-sm font-medium">Password</span>
            <Input
              id="register-password"
              name="password"
              type="password"
              required
              minLength={8}
              value={form.password}
              onChange={set('password')}
              // `new-password` is what prompts a password manager to offer a
              // generated one rather than autofilling an existing login.
              autoComplete="new-password"
            />
            <span className="mt-1 block text-xs text-muted">At least 8 characters.</span>
          </label>

          <label className="block" htmlFor="register-title">
            <span className="mb-1 block text-sm font-medium">
              Title <span className="font-normal text-muted">(optional)</span>
            </span>
            <Input
              id="register-title"
              name="title"
              value={form.title}
              onChange={set('title')}
              placeholder="Head of Growth"
            />
          </label>

          <fieldset>
            <legend className="mb-2 text-sm font-medium">Which team are you on?</legend>
            <div className="flex flex-col gap-2">
              {TEAMS.map((value) => (
                <label
                  key={value}
                  className={[
                    'flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition-colors',
                    team === value
                      ? 'border-primary bg-accent-subtle'
                      : 'border-border hover:bg-surface-2',
                  ].join(' ')}
                >
                  <input
                    type="radio"
                    name="team"
                    checked={team === value}
                    onChange={() => setTeam(value)}
                    className="mt-0.5 h-4 w-4 accent-[hsl(var(--accent))]"
                  />
                  <span className="min-w-0">
                    <span className="block text-sm font-medium">{TEAM_LABELS[value]}</span>
                    <span className="block text-xs text-muted">{TEAM_DESCRIPTIONS[value]}</span>
                  </span>
                </label>
              ))}
            </div>
          </fieldset>

          {error ? (
            <p className="text-sm text-danger" role="alert">
              {error}
            </p>
          ) : null}

          <Button type="submit" variant="primary" className="w-full" disabled={busy}>
            {busy ? 'Creating your account…' : 'Create account'}
          </Button>

          <button
            type="button"
            onClick={onBack}
            className="tap flex w-full items-center justify-center gap-1.5 text-sm font-medium text-muted"
          >
            <ArrowLeft className="h-3.5 w-3.5" aria-hidden />I already have an account
          </button>
        </form>
      </div>
    </AuthShell>
  );
}
