'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 { useAuth } from '@/lib/hooks/useAuth';
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';
import { TopBarControls } from '@/components/ui/shared/TopBarControls';

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 { registerTrial, isLoading } = useAuth();
  const [step, setStep] = useState(1);
  const [error, setError] = useState<string | null>(null);

  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) {
      const message = err instanceof Error ? err.message : t('registrationFailed');
      setError(message || t('registrationFailed'));
    }
  };

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

  return (
    <div className="relative min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
      <div className="absolute top-4 right-4">
        <TopBarControls />
      </div>

      <div className="sm:mx-auto sm:w-full sm:max-w-md">
        <Link href="/" className="flex justify-center">
          <span className="text-3xl font-semibold text-text-primary">{tCommon('appName')}</span>
        </Link>
        <h2 className="mt-6 text-center 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>

      <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="surface-card py-8 px-4 sm:px-10">
          <RegistrationProgressSteps step={step} />
          <div className="mb-6 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-center">
                <span className="mr-2">✓</span> {t('trialTeamMembers')}
              </li>
              <li className="flex items-center">
                <span className="mr-2">✓</span> {t('trialFullAccess')}
              </li>
              <li className="flex items-center">
                <span className="mr-2">✓</span> {t('trialNoCard')}
              </li>
            </ul>
          </div>

          <form onSubmit={handleSubmit(onSubmit)} className="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-600">{error}</p>
                  </div>
                )}
                <div className="flex gap-3">
                  <Button type="button" variant="outline" onClick={() => setStep(1)}>
                    {tCommon('back')}
                  </Button>
                  <Button type="submit" variant="primary" isLoading={isLoading} fullWidth>
                    {t('startMyFreeTrial')}
                  </Button>
                </div>
              </>
            )}
          </form>

          <p className="mt-6 text-xs text-center text-text-muted">
            {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>
      </div>
    </div>
  );
}
