/**
 * Profile creation.
 *
 * Shown when someone is authenticated but is not yet a member — the state that
 * exists precisely because PIG shares its identity provider with other
 * applications. Without this screen that state is a dead end, which is a
 * miserable thing to hand someone who has just clicked a sign-in link.
 */
import { useState } from 'react';
import { TEAMS, TEAM_DESCRIPTIONS, TEAM_LABELS, type Team } from '@pig/core';
import { ApiError, post, type PublicConfig } from '@/lib/api';
import { Button, Input } from '@/components/ui';
import { AuthShell } from '@/components/AuthShell';
import { usePageTitle } from '@/lib/title';

export function CreateProfile({
  config,
  onCreated,
}: {
  config: PublicConfig;
  onCreated: () => void;
}) {
  usePageTitle('Join workspace');
  const [name, setName] = useState('');
  const [title, setTitle] = useState('');
  const [team, setTeam] = useState<Team>('demand');
  const [inviteCode, setInviteCode] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  async function submit(event: React.FormEvent) {
    event.preventDefault();
    setBusy(true);
    setError(null);
    try {
      await post('/api/signup', {
        name,
        team,
        title: title || undefined,
        inviteCode: inviteCode || undefined,
      });
      onCreated();
    } catch (err) {
      // The server distinguishes "no code", "wrong code", "expired" and
      // "issued to someone else". All four are actionable, so all four are
      // shown rather than flattened into "access denied".
      setError(err instanceof ApiError ? err.message : 'Could not create your profile.');
    } finally {
      setBusy(false);
    }
  }

  return (
    <AuthShell>
      <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">
            Set up your profile
          </h1>
          <p className="text-sm leading-6 text-muted">
            You're already authenticated. This creates a PIG profile only after workspace access is
            verified.
          </p>
        </div>

        <form onSubmit={submit} className="mt-6 flex flex-col gap-4">
          <label className="block" htmlFor="profile-name">
            <span className="mb-1 block text-sm font-medium">Your name</span>
            <Input
              id="profile-name"
              name="name"
              required
              value={name}
              onChange={(e) => setName(e.target.value)}
              autoComplete="name"
              placeholder="Alex Ferguson"
            />
          </label>

          <label className="block" htmlFor="profile-job-title">
            <span className="mb-1 block text-sm font-medium">
              Title <span className="font-normal text-muted">(optional)</span>
            </span>
            <Input
              id="profile-job-title"
              name="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              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"
                    value={value}
                    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>
            <p className="mt-2 text-xs text-muted">You can be added to more teams later.</p>
          </fieldset>

          {config.inviteRequired ? (
            <label className="block" htmlFor="profile-invite-code">
              <span className="mb-1 block text-sm font-medium">Invite code</span>
              <Input
                id="profile-invite-code"
                name="inviteCode"
                value={inviteCode}
                onChange={(e) => setInviteCode(e.target.value)}
                placeholder="Ask an administrator"
                autoCapitalize="off"
                autoCorrect="off"
                spellCheck={false}
              />
              <span className="mt-1 block text-xs text-muted">
                Not needed if your address is configured as an administrator.
              </span>
            </label>
          ) : null}

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

          <Button type="submit" variant="primary" className="w-full" disabled={busy}>
            {busy ? 'Creating…' : 'Join the workspace'}
          </Button>
        </form>
      </div>
    </AuthShell>
  );
}
