import { useState, type FormEvent } from 'react';
import { PasswordStrengthBar } from './PasswordStrengthBar.js';
import type { RegisterFormProps } from './types.js';

/**
 * Registration form with name, email, password, confirm password,
 * password strength indicator, and optional terms checkbox.
 * Styled via CSS custom properties (inherits --bl-* from host app).
 */
export function RegisterForm({
  onSubmit,
  isLoading = false,
  error,
  termsUrl,
  privacyUrl,
  onSwitchToLogin,
  className,
}: RegisterFormProps) {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [termsAccepted, setTermsAccepted] = useState(!termsUrl);

  const passwordMismatch = confirm.length > 0 && password !== confirm;
  const canSubmit =
    name.trim().length > 0 &&
    email.length > 0 &&
    password.length >= 8 &&
    !passwordMismatch &&
    termsAccepted &&
    !isLoading;

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (!canSubmit) return;
    onSubmit({ name: name.trim(), email, password });
  }

  const inputStyle = {
    padding: '10px 12px',
    border: '1px solid var(--bl-border, #ccc)',
    borderRadius: 'var(--bl-radius, 6px)',
    fontSize: '14px',
    width: '100%',
    boxSizing: 'border-box' as const,
  };

  return (
    <div className={className} data-testid="bl-register-form">
      <form
        onSubmit={handleSubmit}
        style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}
      >
        <label style={{ fontSize: '13px', fontWeight: 500, color: 'var(--bl-text, #333)' }}>
          Name
          <input
            type="text"
            placeholder="Your name"
            value={name}
            onChange={e => setName(e.target.value)}
            required
            disabled={isLoading}
            data-testid="bl-register-name"
            style={{ ...inputStyle, marginTop: '4px', display: 'block' }}
          />
        </label>

        <label style={{ fontSize: '13px', fontWeight: 500, color: 'var(--bl-text, #333)' }}>
          Email
          <input
            type="email"
            placeholder="you@example.com"
            value={email}
            onChange={e => setEmail(e.target.value)}
            required
            disabled={isLoading}
            data-testid="bl-register-email"
            style={{ ...inputStyle, marginTop: '4px', display: 'block' }}
          />
        </label>

        <label style={{ fontSize: '13px', fontWeight: 500, color: 'var(--bl-text, #333)' }}>
          Password
          <input
            type="password"
            placeholder="Min 8 characters"
            value={password}
            onChange={e => setPassword(e.target.value)}
            required
            minLength={8}
            disabled={isLoading}
            data-testid="bl-register-password"
            style={{ ...inputStyle, marginTop: '4px', display: 'block' }}
          />
        </label>

        <PasswordStrengthBar password={password} />

        <label style={{ fontSize: '13px', fontWeight: 500, color: 'var(--bl-text, #333)' }}>
          Confirm password
          <input
            type="password"
            placeholder="Re-enter password"
            value={confirm}
            onChange={e => setConfirm(e.target.value)}
            required
            disabled={isLoading}
            data-testid="bl-register-confirm"
            style={{
              ...inputStyle,
              marginTop: '4px',
              display: 'block',
              borderColor: passwordMismatch ? 'var(--bl-error, #dc3545)' : undefined,
            }}
          />
        </label>

        {passwordMismatch && (
          <div
            data-testid="bl-register-mismatch"
            style={{ color: 'var(--bl-error, #dc3545)', fontSize: '12px' }}
          >
            Passwords do not match
          </div>
        )}

        {termsUrl && (
          <label
            style={{
              display: 'flex',
              alignItems: 'flex-start',
              gap: '8px',
              fontSize: '13px',
              color: 'var(--bl-text, #333)',
            }}
          >
            <input
              type="checkbox"
              checked={termsAccepted}
              onChange={e => setTermsAccepted(e.target.checked)}
              disabled={isLoading}
              data-testid="bl-register-terms"
              style={{ marginTop: '2px' }}
            />
            <span>
              I agree to the{' '}
              <a
                href={termsUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{ color: 'var(--bl-link, #0066ff)' }}
              >
                Terms of Service
              </a>
              {privacyUrl && (
                <>
                  {' '}
                  and{' '}
                  <a
                    href={privacyUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: 'var(--bl-link, #0066ff)' }}
                  >
                    Privacy Policy
                  </a>
                </>
              )}
            </span>
          </label>
        )}

        {error && (
          <div
            data-testid="bl-register-error"
            style={{ color: 'var(--bl-error, #dc3545)', fontSize: '13px' }}
          >
            {error}
          </div>
        )}

        <button
          type="submit"
          disabled={!canSubmit}
          data-testid="bl-register-submit"
          style={{
            padding: '10px 16px',
            border: 'none',
            borderRadius: 'var(--bl-radius, 6px)',
            background: 'var(--bl-primary, #0066ff)',
            color: 'var(--bl-accent-foreground, #fff)',
            cursor: !canSubmit ? 'not-allowed' : 'pointer',
            fontSize: '14px',
            fontWeight: 600,
            opacity: !canSubmit ? 0.6 : 1,
          }}
        >
          {isLoading ? 'Creating account...' : 'Create account'}
        </button>

        {onSwitchToLogin && (
          <div style={{ textAlign: 'center', fontSize: '13px', color: 'var(--bl-muted, #999)' }}>
            Already have an account?{' '}
            <button
              type="button"
              onClick={onSwitchToLogin}
              data-testid="bl-register-switch-login"
              style={{
                border: 'none',
                background: 'transparent',
                color: 'var(--bl-link, #0066ff)',
                cursor: 'pointer',
                textDecoration: 'underline',
                fontSize: '13px',
                padding: 0,
              }}
            >
              Sign in
            </button>
          </div>
        )}
      </form>
    </div>
  );
}
