/**
 * Signup form — direct API call, then email verification screen.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import React, { useState } from 'react';
import {
  signup,
{% if email_verification %}
  resendVerification,
{% endif %}
} from '../../lib/authApi';
{% if email_verification %}
import { EmailVerification } from './EmailVerification';
{% endif %}

export interface SignupFormProps {
  onSuccess?: () => void;
  onLoginClick?: () => void;
}

{% if email_verification %}
type SignupStep = 'form' | 'email_verification';
{% endif %}

export function SignupForm({ onSuccess, onLoginClick }: SignupFormProps): JSX.Element {
{% if email_verification %}
  const [step, setStep] = useState<SignupStep>('form');
{% endif %}
  const [formData, setFormData] = useState({
    {{ username_field }}: '',
    username: '',
    password: '',
    confirmPassword: '',
  });
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  const validatePassword = (password: string): string | null => {
    if (password.length < {{ password_min_length }}) return 'Password must be at least {{ password_min_length }} characters';
{% if password_require_uppercase %}
    if (!/[A-Z]/.test(password)) return 'Password must contain at least one uppercase letter';
{% endif %}
{% if password_require_lowercase %}
    if (!/[a-z]/.test(password)) return 'Password must contain at least one lowercase letter';
{% endif %}
{% if password_require_number %}
    if (!/[0-9]/.test(password)) return 'Password must contain at least one number';
{% endif %}
{% if password_require_special %}
    if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) return 'Password must contain at least one special character';
{% endif %}
    return null;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);

    if (formData.password !== formData.confirmPassword) {
      setError('Passwords do not match');
      return;
    }

    const passwordError = validatePassword(formData.password);
    if (passwordError) {
      setError(passwordError);
      return;
    }

    setLoading(true);

    try {
      await signup(formData.{{ username_field }}, formData.username, formData.password);
{% if email_verification %}
      setStep('email_verification');
{% else %}
      onSuccess?.();
{% endif %}
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Signup failed');
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setFormData((prev) => ({
      ...prev,
      [e.target.name]: e.target.value,
    }));
  };

  const getPasswordStrength = (
    password: string
  ): { strength: number; label: string; color: string } => {
    if (!password) return { strength: 0, label: '', color: '' };
    let s = 0;
    if (password.length >= {{ password_min_length }}) s++;
    if (/[A-Z]/.test(password)) s++;
    if (/[a-z]/.test(password)) s++;
    if (/[0-9]/.test(password)) s++;
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) s++;
    if (s <= 2) return { strength: 33, label: 'Weak', color: 'bg-red-500' };
    if (s <= 4) return { strength: 66, label: 'Medium', color: 'bg-yellow-500' };
    return { strength: 100, label: 'Strong', color: 'bg-green-500' };
  };

{% if email_verification %}
  if (step === 'email_verification') {
    return (
      <EmailVerification
        onResend={async () => {
          await resendVerification(formData.{{ username_field }});
        }}
        onBackToLogin={() => onLoginClick?.()}
      />
    );
  }
{% endif %}

  const passwordStrength = getPasswordStrength(formData.password);

  return (
    <div className="w-full max-w-md mx-auto">
      <div className="bg-white rounded-lg shadow-lg p-8">
        <h2 className="text-2xl font-bold text-nordic-800 mb-6 text-center">Create Account</h2>

        {error && (
          <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md">
            <p className="text-sm text-red-800">{error}</p>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="{{ username_field }}" className="block text-sm font-medium text-nordic-700 mb-1">
              {{ username_field_title }}
            </label>
            <input
              type="{{ input_type }}"
              id="{{ username_field }}"
              name="{{ username_field }}"
              value={formData.{{ username_field }}}
              onChange={handleChange}
              required
              disabled={loading}
              className="w-full px-3 py-2 border border-nordic-200 rounded-md focus:outline-none focus:ring-2 focus:ring-nordic-500 disabled:bg-nordic-50 disabled:cursor-not-allowed"
              placeholder="Enter your {{ username_field }}"
            />
          </div>

          <div>
            <label htmlFor="username" className="block text-sm font-medium text-nordic-700 mb-1">
              Username
            </label>
            <input
              type="text"
              id="username"
              name="username"
              value={formData.username}
              onChange={handleChange}
              required
              disabled={loading}
              className="w-full px-3 py-2 border border-nordic-200 rounded-md focus:outline-none focus:ring-2 focus:ring-nordic-500 disabled:bg-nordic-50 disabled:cursor-not-allowed"
              placeholder="Choose a username"
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium text-nordic-700 mb-1">
              Password
            </label>
            <input
              type="password"
              id="password"
              name="password"
              value={formData.password}
              onChange={handleChange}
              required
              disabled={loading}
              className="w-full px-3 py-2 border border-nordic-200 rounded-md focus:outline-none focus:ring-2 focus:ring-nordic-500 disabled:bg-nordic-50 disabled:cursor-not-allowed"
              placeholder="Choose a strong password"
            />
            {formData.password && (
              <div className="mt-2">
                <div className="flex items-center gap-2">
                  <div className="flex-1 h-2 bg-nordic-100 rounded-full overflow-hidden">
                    <div
                      className={`h-full transition-all ${passwordStrength.color}`}
                      style={{ '{{' }} width: `${passwordStrength.strength}%` {{ '}}' }}
                    />
                  </div>
                  <span className="text-xs text-nordic-600">{passwordStrength.label}</span>
                </div>
              </div>
            )}
          </div>

          <div>
            <label htmlFor="confirmPassword" className="block text-sm font-medium text-nordic-700 mb-1">
              Confirm Password
            </label>
            <input
              type="password"
              id="confirmPassword"
              name="confirmPassword"
              value={formData.confirmPassword}
              onChange={handleChange}
              required
              disabled={loading}
              className="w-full px-3 py-2 border border-nordic-200 rounded-md focus:outline-none focus:ring-2 focus:ring-nordic-500 disabled:bg-nordic-50 disabled:cursor-not-allowed"
              placeholder="Confirm your password"
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full bg-nordic-600 text-white py-2 px-4 rounded-md hover:bg-nordic-700 focus:outline-none focus:ring-2 focus:ring-nordic-500 focus:ring-offset-2 disabled:bg-nordic-300 disabled:cursor-not-allowed transition-colors"
          >
            {loading ? 'Creating account...' : 'Create Account'}
          </button>
        </form>

        {onLoginClick && (
          <div className="mt-6 text-center">
            <p className="text-sm text-nordic-600">
              Already have an account?{' '}
              <button
                type="button"
                onClick={onLoginClick}
                className="text-nordic-600 hover:text-nordic-800 font-medium underline"
              >
                Sign in
              </button>
            </p>
          </div>
        )}
      </div>
    </div>
  );
}
