'use client';

import { useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import { useTranslations } from 'next-intl';
import { Link } from '@/i18n/navigation';
import { Mail, Lock, User, Phone } from 'lucide-react';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { useAuth } from '@/lib/hooks/useAuth';
import { useEnterAppWhenAuthenticated } from '@/lib/hooks/useEnterAppWhenAuthenticated';
import { AuthPageShell } from '@/components/ui/auth/AuthPageShell';
import { BrandLockup } from '@/components/ui/shared/BrandLockup';
import { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
import { Button } from '@/components/ui/shared/Button';
import { Input } from '@/components/ui/shared/Input';

type RegisterForm = {
  name: string;
  email: string;
  mobile: string;
  password: string;
  confirmPassword: string;
  organizationName: string;
  organizationEmail: string;
  organizationType: 'CLINIC' | 'LAB';
};

function normalizeIranMobile(input: string): string {
  let digits = input.replace(/\D/g, '');
  if (digits.startsWith('98') && digits.length === 12) digits = digits.slice(2);
  if (digits.startsWith('0') && digits.length === 11) digits = digits.slice(1);
  return digits;
}

export default function RegisterPage() {
  const t = useTranslations('auth');
  const tCommon = useTranslations('common');
  const tValidation = useTranslations('validation');
  const tErrors = useTranslations('errors');
  const { registerTrial, isLoading, isAuthReady } = useAuth();
  const [step, setStep] = useState(1);
  const [error, setError] = useState<string | null>(null);
  useEnterAppWhenAuthenticated();

  const registerSchema = useMemo(
    () =>
      z
        .object({
          name: z.string().min(2, tValidation('nameMinLength')),
          email: z.string().email(tValidation('emailInvalid')),
          mobile: z
            .string()
            .min(1, tValidation('mobileRequired'))
            .refine((value) => /^9\d{9}$/.test(normalizeIranMobile(value)), {
              message: tValidation('mobileInvalid'),
            }),
          password: z
            .string()
            .min(8, tValidation('passwordMinLength'))
            .regex(/[A-Z]/, tValidation('passwordUppercase'))
            .regex(/[0-9]/, tValidation('passwordNumber')),
          confirmPassword: z.string(),
          organizationName: z.string().min(2, tValidation('organizationNameMinLength')),
          organizationEmail: z.string().email(tValidation('organizationEmailInvalid')),
          organizationType: z.enum(['CLINIC', 'LAB'], {
            message: tValidation('organizationTypeRequired'),
          }),
        })
        .refine((data) => data.password === data.confirmPassword, {
          message: tValidation('passwordsDoNotMatch'),
          path: ['confirmPassword'],
        }),
    [tValidation],
  );

  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
    trigger,
    setValue,
  } = useForm<RegisterForm>({
    resolver: zodResolver(registerSchema),
    mode: 'onChange',
  });

  const organizationType = watch('organizationType');

  const handleNext = async () => {
    const fieldsToValidate =
      step === 1
        ? (['name', 'email', 'mobile', 'password', 'confirmPassword'] as const)
        : (['organizationName', 'organizationEmail', 'organizationType'] as const);

    const isValid = await trigger([...fieldsToValidate]);
    if (isValid) {
      setStep(step + 1);
    }
  };

  const onSubmit = async (data: RegisterForm) => {
    try {
      setError(null);
      await registerTrial(
        data.email,
        data.password,
        data.name,
        data.mobile,
        data.organizationName,
        data.organizationEmail,
        data.organizationType,
      );
    } catch (err: unknown) {
      setError(getUserFacingError(err, tErrors, t('registrationFailed')));
    }
  };

  const passwordToggleLabels = {
    show: t('showPassword'),
    hide: t('hidePassword'),
  };

  if (!isAuthReady) {
    return (
      <div className="min-h-[100dvh] app-web-bg flex items-center justify-center px-4">
        <p className="text-text-secondary">{tCommon('loading')}</p>
      </div>
    );
  }

  return (
    <AuthPageShell
      header={
        <>
          <Link href="/" className="flex justify-center">
            <BrandLockup className="text-2xl sm:text-3xl text-text-primary" />
          </Link>
          <h2 className="mt-4 sm:mt-6 text-center text-2xl sm:text-3xl font-semibold text-text-primary">
            {t('registerTitle')}
          </h2>
          <p className="mt-2 text-center text-sm text-text-secondary">
            {t('registerPrompt')}{' '}
            <Link href="/login" className="font-medium text-primary hover:opacity-90">
              {t('signInLink')}
            </Link>
          </p>
        </>
      }
    >
      <div className="surface-card py-6 sm:py-8 px-4 sm:px-10">
        <RegistrationProgressSteps step={step} />
        <div className="mb-5 sm:mb-6 p-3 sm:p-4 bg-primary-soft rounded-[var(--radius-md)] border border-primary/35">
          <h3 className="text-sm font-medium text-text-primary mb-2">{t('trialIncludes')}</h3>
          <ul className="text-sm text-text-secondary space-y-1">
            <li className="flex items-start gap-2">
              <span className="shrink-0">✓</span>
              <span>{t('trialTeamMembers')}</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="shrink-0">✓</span>
              <span>{t('trialFullAccess')}</span>
            </li>
            <li className="flex items-start gap-2">
              <span className="shrink-0">✓</span>
              <span>{t('trialNoCard')}</span>
            </li>
          </ul>
        </div>

        <form onSubmit={handleSubmit(onSubmit)} className="space-y-5 sm:space-y-6">
          {step === 1 && (
            <>
              <Input
                label={t('fullName')}
                {...register('name')}
                placeholder={t('namePlaceholder')}
                error={errors.name?.message}
                icon={<User className="h-5 w-5 icon-flat" />}
              />
              <Input
                label={t('email')}
                {...register('email')}
                type="email"
                placeholder={t('emailPlaceholder')}
                error={errors.email?.message}
                icon={<Mail className="h-5 w-5 icon-flat" />}
              />
              <Input
                label={t('mobile')}
                {...register('mobile')}
                type="tel"
                inputMode="tel"
                autoComplete="tel"
                placeholder={t('mobilePlaceholder')}
                error={errors.mobile?.message}
                icon={<Phone className="h-5 w-5 icon-flat" />}
              />
              <Input
                label={t('password')}
                {...register('password')}
                type="password"
                placeholder={t('passwordPlaceholder')}
                error={errors.password?.message}
                icon={<Lock className="h-5 w-5 icon-flat" />}
                passwordToggleLabels={passwordToggleLabels}
              />
              <Input
                label={t('confirmPassword')}
                {...register('confirmPassword')}
                type="password"
                placeholder={t('passwordPlaceholder')}
                error={errors.confirmPassword?.message}
                icon={<Lock className="h-5 w-5 icon-flat" />}
                passwordToggleLabels={passwordToggleLabels}
              />
              <Button type="button" variant="primary" onClick={handleNext} fullWidth>
                {tCommon('continue')}
              </Button>
            </>
          )}

          {step === 2 && (
            <>
              <OrganizationDetailsFields
                register={register as never}
                errors={errors as never}
                organizationType={organizationType}
                setValue={setValue as never}
              />
              {error && (
                <div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
                  <p className="text-sm text-red-400">{error}</p>
                </div>
              )}
              <div className="flex flex-col-reverse gap-3 sm:flex-row">
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setStep(1)}
                  className="sm:shrink-0"
                >
                  {tCommon('back')}
                </Button>
                <Button type="submit" variant="primary" isLoading={isLoading} fullWidth>
                  {t('startMyFreeTrial')}
                </Button>
              </div>
            </>
          )}
        </form>

        <p className="mt-5 sm:mt-6 text-xs text-center text-text-muted leading-relaxed">
          {t('termsIntro')}{' '}
          <Link href="/terms" className="text-primary hover:opacity-90">
            {t('termsOfService')}
          </Link>{' '}
          {tCommon('and')}{' '}
          <Link href="/privacy" className="text-primary hover:opacity-90">
            {t('privacyPolicy')}
          </Link>
        </p>
      </div>
    </AuthPageShell>
  );
}
