/**
 * WP Register Page
 *
 * Simplified registration form for WordPress plugin users.
 * B2B-only: TWWIM is pure B2B SaaS, every account is a Business.
 * No plan selection, no captcha.
 *
 * (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)
 */

import { useState } from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { PasswordInput } from '@/features/auth/components/PasswordInput';
import { AuthLayout } from '@/features/auth/components/AuthLayout';
import { AlertCircle } from 'lucide-react';
import { apiClient } from '@/infrastructure/http/ApiClient';
import { useTranslation } from '@/i18n/TranslationProvider';
import { CountrySelect } from '@archer/ui/components';
import { CompanyType } from '@archer/domain';

const wpRegisterSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8).max(100),
  firstName: z.string().min(1).max(100),
  lastName: z.string().min(1).max(100),
  /** ISO-3166-1 alpha-2 — drives billing currency via CurrencyResolver on the backend. */
  country: z.string().length(2, 'Select a country'),
  companyName: z.string().min(1, 'Company name is required').max(200),
  vatId: z.string().max(50).optional(),
  agreeToTerms: z.literal(true, {
    errorMap: () => ({ message: 'terms-required' }),
  }),
});

type WpRegisterFormData = z.infer<typeof wpRegisterSchema>;

/**
 * Best-effort ISO-2 country from the browser locale (e.g. 'de-DE' → 'DE').
 * Returns '' when the locale lacks a region — the CountrySelect just starts
 * empty and the user picks manually.
 */
function guessBrowserCountry(): string {
  if (typeof navigator === 'undefined') return '';
  const loc = navigator.language || '';
  const m = loc.match(/-([A-Z]{2})$/i);
  return m ? m[1].toUpperCase() : '';
}

export function WpRegisterPage({ onBack }: { onBack: () => void }) {
  const { t, locale } = useTranslation();
  const [apiError, setApiError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const {
    register,
    handleSubmit,
    control,
    formState: { errors, isSubmitting },
  } = useForm<WpRegisterFormData>({
    resolver: zodResolver(wpRegisterSchema),
    // Default to the browser's locale region when detectable — matches the
    // landing-web wizard's geo-default behaviour. Server is still authoritative.
    defaultValues: { country: guessBrowserCountry() },
  });

  const termsUrl = `https://www.twwim.ai/${locale}/terms-of-service`;
  const privacyUrl = `https://www.twwim.ai/${locale}/privacy-policy`;

  const onSubmit = async (data: WpRegisterFormData) => {
    setApiError(null);
    try {
      await apiClient.post('/auth/register', {
        email: data.email,
        password: data.password,
        firstName: data.firstName,
        lastName: data.lastName,
        country: data.country,
        companyName: data.companyName,
        companyType: CompanyType.BUSINESS,
        vatId: data.vatId || undefined,
        agreeToTerms: data.agreeToTerms,
        legalAcceptance: { agb: true as const, datenschutz: true as const, avv: true as const },
      });

      // Registration successful — show success message
      setSuccess(true);
    } catch (err: any) {
      const msg = err?.response?.data?.message || err?.message || 'Registration failed';
      setApiError(msg);
    }
  };

  if (success) {
    return (
      <AuthLayout>
        <div className="text-center space-y-4">
          <div className="mx-auto w-12 h-12 rounded-full bg-green-100 flex items-center justify-center">
            <AlertCircle className="h-6 w-6 text-green-600" />
          </div>
          <h2 className="text-xl font-semibold text-foreground">Account Created</h2>
          <p className="text-sm text-muted-foreground">
            Please check your email to verify your account, then sign in.
          </p>
          <Button onClick={onBack} className="w-full">
            Back to Sign In
          </Button>
        </div>
      </AuthLayout>
    );
  }

  return (
    <AuthLayout>
      <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
        <div className="text-center mb-6">
          <h2 className="text-xl font-semibold text-foreground">Create Business Account</h2>
          <p className="text-sm text-muted-foreground mt-1">
            TWWIM AI is a B2B SaaS — accounts are for businesses only.
          </p>
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <Label htmlFor="firstName">First Name</Label>
            <Input id="firstName" {...register('firstName')} />
            {errors.firstName && <p className="text-xs text-destructive mt-1">{errors.firstName.message}</p>}
          </div>
          <div>
            <Label htmlFor="lastName">Last Name</Label>
            <Input id="lastName" {...register('lastName')} />
            {errors.lastName && <p className="text-xs text-destructive mt-1">{errors.lastName.message}</p>}
          </div>
        </div>

        <div>
          <Label htmlFor="email">Email</Label>
          <Input id="email" type="email" {...register('email')} />
          {errors.email && <p className="text-xs text-destructive mt-1">{errors.email.message}</p>}
        </div>

        <div>
          <Label htmlFor="password">Password</Label>
          <PasswordInput id="password" {...register('password')} />
          {errors.password && <p className="text-xs text-destructive mt-1">{errors.password.message}</p>}
        </div>

        <div>
          <Label htmlFor="country">Country</Label>
          <Controller
            control={control}
            name="country"
            render={({ field }) => (
              <CountrySelect
                id="country"
                name="country"
                value={field.value ?? ''}
                onChange={field.onChange}
                placeholder="Search country…"
              />
            )}
          />
          {errors.country && <p className="text-xs text-destructive mt-1">{errors.country.message}</p>}
          <p className="mt-1 text-xs text-muted-foreground">Determines your billing currency.</p>
        </div>

        <div>
          <Label htmlFor="companyName">Company Name</Label>
          <Input id="companyName" {...register('companyName')} />
          {errors.companyName && (
            <p className="text-xs text-destructive mt-1">{errors.companyName.message}</p>
          )}
        </div>
        <div>
          <Label htmlFor="vatId">VAT ID (optional)</Label>
          <Input id="vatId" {...register('vatId')} placeholder="DE123456789" />
        </div>

        <div>
          <label className="flex items-start gap-2 text-sm cursor-pointer">
            <input
              type="checkbox"
              {...register('agreeToTerms')}
              className="mt-0.5 h-4 w-4 rounded border border-gray-400 bg-white accent-primary focus:ring-2 focus:ring-primary"
            />
            <span className="text-muted-foreground">
              {t('auth.register.terms.prefix')}
              <a
                href={termsUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary underline hover:no-underline"
              >
                {t('auth.register.terms.termsLink')}
              </a>
              {t('auth.register.terms.and')}
              <a
                href={privacyUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-primary underline hover:no-underline"
              >
                {t('auth.register.terms.privacyLink')}
              </a>
              .
            </span>
          </label>
          {errors.agreeToTerms && (
            <p className="text-xs text-destructive mt-1">{t('auth.register.terms.required')}</p>
          )}
        </div>

        {apiError && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{apiError}</AlertDescription>
          </Alert>
        )}

        <Button type="submit" className="w-full" disabled={isSubmitting}>
          {isSubmitting ? 'Creating account...' : 'Create Account'}
        </Button>

        <button
          type="button"
          onClick={onBack}
          className="w-full text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          Already have an account? Sign in
        </button>
      </form>
    </AuthLayout>
  );
}
