/**
 * ============================================
 * REGISTER PAGE
 * ============================================
 * Equivalent to: account/register.html.twig in Shopware
 * 
 * Fetches salutations and countries from Shopware
 * to populate the form dynamically.
 */

'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/lib/auth-context';
import {
  getSalutations,
  getCountries,
  getStorefrontUrl,
  Salutation,
  Country,
} from '@/lib/shopware-api';
import Captcha, { type CaptchaHandle } from '@/components/ui/Captcha';
import { runCaptchaGate } from '@/lib/captcha-client';

export default function RegisterPage() {
  const { register, isLoggedIn } = useAuth();
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectTo = searchParams.get('redirect') || '/account';

  const [salutations, setSalutations] = useState<Salutation[]>([]);
  const [countries, setCountries] = useState<Country[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');
  const captchaRef = useRef<CaptchaHandle>(null);

  // Private vs commercial (business) account. The selector is only shown when
  // Shopware's "Show selection between company and customer account" setting is
  // enabled (core.loginRegistration.showAccountTypeSelection); otherwise the
  // account defaults to private — mirroring the default storefront.
  const [accountType, setAccountType] = useState<'private' | 'business' | ''>('');
  const [showAccountType, setShowAccountType] = useState(true);

  // Form state
  const [form, setForm] = useState({
    salutationId: '',
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    passwordConfirm: '',
    company: '',
    department: '',
    vatId: '',
    street: '',
    zipcode: '',
    city: '',
    countryId: '',
  });

  // If already logged in, redirect
  useEffect(() => {
    if (isLoggedIn) {
      router.push(redirectTo);
    }
  }, [isLoggedIn, redirectTo, router]);

  // Load salutations and countries on mount
  useEffect(() => {
    async function loadFormData() {
      try {
        const [salutationData, countryData] = await Promise.all([
          getSalutations(),
          getCountries(),
        ]);
        setSalutations(salutationData.elements || []);
        setCountries(countryData.elements || []);

        // Set defaults
        const defaultSalutation = salutationData.elements?.find(
          (s: Salutation) => s.salutationKey === 'mr'
        );
        if (defaultSalutation) {
          setForm((prev) => ({ ...prev, salutationId: defaultSalutation.id }));
        }
      } catch (err) {
        console.error('Failed to load form data:', err);
      }
    }
    loadFormData();
  }, []);

  // Respect the "Show selection between company and customer account" setting.
  useEffect(() => {
    let cancelled = false;
    fetch('/api/registration-config')
      .then((r) => r.json())
      .then((cfg) => {
        if (cancelled) return;
        const show = cfg?.showAccountTypeSelection !== false;
        setShowAccountType(show);
        // When the selector is hidden, the account is private by default.
        if (!show) setAccountType('private');
      })
      .catch(() => {
        // On failure keep the selector visible so B2B stays available.
      });
    return () => {
      cancelled = true;
    };
  }, []);

  const updateForm = (field: string, value: string) => {
    setForm((prev) => ({ ...prev, [field]: value }));
  };

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

    // Validate passwords match
    if (form.password !== form.passwordConfirm) {
      setError('Passwords do not match.');
      return;
    }

    if (form.password.length < 8) {
      setError('Password must be at least 8 characters long.');
      return;
    }

    if (showAccountType && accountType === '') {
      setError('Please select an account type.');
      return;
    }

    const isBusiness = accountType === 'business';

    if (isBusiness && !form.company.trim()) {
      setError('Company name is required for a commercial account.');
      return;
    }

    setIsSubmitting(true);

    try {
      const captchaPayload = (await captchaRef.current?.getPayload()) ?? {};
      await runCaptchaGate(captchaPayload);
      await register({
        salutationId: form.salutationId,
        firstName: form.firstName,
        lastName: form.lastName,
        email: form.email,
        password: form.password,
        storefrontUrl: getStorefrontUrl(),
        accountType: isBusiness ? 'business' : 'private',
        vatIds: isBusiness && form.vatId.trim() ? [form.vatId.trim()] : undefined,
        billingAddress: {
          street: form.street,
          zipcode: form.zipcode,
          city: form.city,
          countryId: form.countryId,
          ...(isBusiness && {
            company: form.company.trim(),
            department: form.department.trim() || undefined,
          }),
        },
      });
      router.push(redirectTo);
    } catch (err: any) {
      setError(err.message || 'Registration failed. Please try again.');
      captchaRef.current?.reset();
    } finally {
      setIsSubmitting(false);
    }
  };

  if (isLoggedIn) return null;

  const inputClass =
    'w-full px-4 py-3 rounded-xl border border-surface-200 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 outline-none transition-all text-surface-900 placeholder-surface-400';
  const labelClass = 'block text-sm font-medium text-surface-700 mb-1.5';

  return (
    <div className="min-h-[80vh] flex items-center justify-center px-6 py-16">
      <div className="w-full max-w-lg">
        {/* Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-surface-900">Create Account</h1>
          <p className="text-surface-500 mt-2">
            Join us and start shopping
          </p>
        </div>

        {/* Error */}
        {error && (
          <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-5">
          {/* Personal Info */}
          <div className="space-y-4">
            <h2 className="text-lg font-semibold text-surface-800">Personal Information</h2>

            {/* Account type (only when Shopware's selection setting is enabled) */}
            {showAccountType && (
              <div>
                <label htmlFor="accountType" className={labelClass}>Account type*</label>
                <select
                  id="accountType"
                  value={accountType}
                  onChange={(e) => setAccountType(e.target.value as 'private' | 'business' | '')}
                  required
                  className={inputClass}
                >
                  <option value="">Select...</option>
                  <option value="private">Private</option>
                  <option value="business">Commercial</option>
                </select>
              </div>
            )}

            <div>
              <label htmlFor="salutation" className={labelClass}>Salutation</label>
              <select
                id="salutation"
                value={form.salutationId}
                onChange={(e) => updateForm('salutationId', e.target.value)}
                required
                className={inputClass}
              >
                <option value="">Select...</option>
                {salutations.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.translated?.displayName || s.displayName}
                  </option>
                ))}
              </select>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="firstName" className={labelClass}>First Name</label>
                <input
                  id="firstName"
                  type="text"
                  value={form.firstName}
                  onChange={(e) => updateForm('firstName', e.target.value)}
                  required
                  className={inputClass}
                  placeholder="John"
                />
              </div>
              <div>
                <label htmlFor="lastName" className={labelClass}>Last Name</label>
                <input
                  id="lastName"
                  type="text"
                  value={form.lastName}
                  onChange={(e) => updateForm('lastName', e.target.value)}
                  required
                  className={inputClass}
                  placeholder="Doe"
                />
              </div>
            </div>

            {/* Commercial-account fields */}
            {accountType === 'business' && (
              <>
                <div>
                  <label htmlFor="company" className={labelClass}>Company*</label>
                  <input
                    id="company"
                    type="text"
                    value={form.company}
                    onChange={(e) => updateForm('company', e.target.value)}
                    required
                    className={inputClass}
                    placeholder="Enter company..."
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label htmlFor="department" className={labelClass}>Department</label>
                    <input
                      id="department"
                      type="text"
                      value={form.department}
                      onChange={(e) => updateForm('department', e.target.value)}
                      className={inputClass}
                      placeholder="(optional)"
                    />
                  </div>
                  <div>
                    <label htmlFor="vatId" className={labelClass}>VAT Reg.No.</label>
                    <input
                      id="vatId"
                      type="text"
                      value={form.vatId}
                      onChange={(e) => updateForm('vatId', e.target.value)}
                      className={inputClass}
                      placeholder="(optional)"
                    />
                  </div>
                </div>
              </>
            )}

            <div>
              <label htmlFor="regEmail" className={labelClass}>Email Address</label>
              <input
                id="regEmail"
                type="email"
                value={form.email}
                onChange={(e) => updateForm('email', e.target.value)}
                required
                autoComplete="email"
                className={inputClass}
                placeholder="your@email.com"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="regPassword" className={labelClass}>Password</label>
                <input
                  id="regPassword"
                  type="password"
                  value={form.password}
                  onChange={(e) => updateForm('password', e.target.value)}
                  required
                  minLength={8}
                  autoComplete="new-password"
                  className={inputClass}
                  placeholder="Min. 8 characters"
                />
              </div>
              <div>
                <label htmlFor="passwordConfirm" className={labelClass}>Confirm Password</label>
                <input
                  id="passwordConfirm"
                  type="password"
                  value={form.passwordConfirm}
                  onChange={(e) => updateForm('passwordConfirm', e.target.value)}
                  required
                  autoComplete="new-password"
                  className={inputClass}
                  placeholder="Repeat password"
                />
              </div>
            </div>
          </div>

          {/* Address */}
          <div className="space-y-4 pt-2">
            <h2 className="text-lg font-semibold text-surface-800">Billing Address</h2>

            <div>
              <label htmlFor="street" className={labelClass}>Street Address</label>
              <input
                id="street"
                type="text"
                value={form.street}
                onChange={(e) => updateForm('street', e.target.value)}
                required
                className={inputClass}
                placeholder="123 Main Street"
              />
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="zipcode" className={labelClass}>Postal Code</label>
                <input
                  id="zipcode"
                  type="text"
                  value={form.zipcode}
                  onChange={(e) => updateForm('zipcode', e.target.value)}
                  required
                  className={inputClass}
                  placeholder="12345"
                />
              </div>
              <div>
                <label htmlFor="city" className={labelClass}>City</label>
                <input
                  id="city"
                  type="text"
                  value={form.city}
                  onChange={(e) => updateForm('city', e.target.value)}
                  required
                  className={inputClass}
                  placeholder="Berlin"
                />
              </div>
            </div>

            <div>
              <label htmlFor="country" className={labelClass}>Country</label>
              <select
                id="country"
                value={form.countryId}
                onChange={(e) => updateForm('countryId', e.target.value)}
                required
                className={inputClass}
              >
                <option value="">Select country...</option>
                {countries.map((c) => (
                  <option key={c.id} value={c.id}>
                    {c.translated?.name || c.name}
                  </option>
                ))}
              </select>
            </div>
          </div>

          {/* Captcha — renders whatever is active in Shopware admin */}
          <Captcha ref={captchaRef} action="register" />

          <button
            type="submit"
            disabled={isSubmitting}
            className="w-full py-3.5 bg-brand-500 hover:bg-brand-600 disabled:bg-brand-300 text-white font-semibold rounded-xl transition-colors mt-2"
          >
            {isSubmitting ? (
              <span className="flex items-center justify-center gap-2">
                <svg className="w-5 h-5 animate-spin" viewBox="0 0 24 24" fill="none">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                </svg>
                Creating account...
              </span>
            ) : (
              'Create Account'
            )}
          </button>
        </form>

        <div className="mt-6 text-center">
          <p className="text-sm text-surface-500">
            Already have an account?{' '}
            <Link
              href={`/account/login${searchParams.get('redirect') ? `?redirect=${searchParams.get('redirect')}` : ''}`}
              className="text-brand-600 font-semibold hover:text-brand-700"
            >
              Sign in
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
