'use client';

import { useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  ArrowRight,
  Mail,
  Shield,
  Sparkles,
  User,
  Users,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { GoogleSignInButton } from '@/components/auth/GoogleSignInButton';
import {
  RegisterFieldGrid,
  RegisterFieldGroup,
  RegisterFormError,
  RegisterFormFooter,
  RegisterFormPanel,
  RegisterFormSection,
  RegisterFormShell,
  RegisterGoogleBanner,
  RegisterInfoCallout,
  RegisterStepActions,
  RegisterStepIndicator,
  RegisterSummaryCard,
  RegisterTermsSection,
} from '@/components/auth/RegisterFormUi';
import { useAuth } from '@/contexts/AuthContext';
import { useLanguage } from '@/contexts/LanguageContext';
import { api } from '@/lib/api';
import { cn } from '@/lib/utils';
import { isGoogleSignInConfigured } from '@/lib/googleAuth';
import { t as translate } from '@/lib/registerLang';

type Step = 'account' | 'otp';

const STEPS = [
  { key: 'account', label: 'Account', labelTl: 'Account', num: 1 },
  { key: 'otp', label: 'Verify', labelTl: 'Beripika', num: 2 },
] as const;

const STEP_META: Record<
  Step,
  { title: string; titleTl: string; subtitle: string; subtitleTl: string; icon: typeof Users }
> = {
  account: {
    title: 'Create your account',
    titleTl: 'Gumawa ng account',
    subtitle: 'Continue with Google to autofill, or enter your details manually',
    subtitleTl: 'Gamitin ang Google para auto-fill, o i-type ang detalye mo',
    icon: User,
  },
  otp: {
    title: 'Verify your email',
    titleTl: 'I-verify ang email mo',
    subtitle: "We'll send a verification code to your email address",
    subtitleTl: 'Papadalhan ka namin ng verification code sa email mo',
    icon: Mail,
  },
};

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export default function RegisterPage() {
  const { register } = useAuth();
  const { lang } = useLanguage();
  const router = useRouter();
  const [step, setStep] = useState<Step>('account');
  const [form, setForm] = useState({ firstName: '', lastName: '', email: '', password: '' });
  const [confirmPassword, setConfirmPassword] = useState('');
  const [googleIdToken, setGoogleIdToken] = useState<string | null>(null);
  const [googleConnectedEmail, setGoogleConnectedEmail] = useState<string | null>(null);
  const [googleLoading, setGoogleLoading] = useState(false);
  const [otp, setOtp] = useState('');
  const [otpSent, setOtpSent] = useState(false);
  const [emailError, setEmailError] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [confirmPasswordError, setConfirmPasswordError] = useState('');
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [termsError, setTermsError] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [resending, setResending] = useState(false);

  const t = (en: string, tl: string) => translate(lang, en, tl);
  const meta = STEP_META[step];
  const Icon = meta.icon;

  const summaryBits = useMemo(() => {
    const bits: string[] = [];
    if (form.firstName.trim()) {
      bits.push(`${form.firstName.trim()} ${form.lastName.trim()}`.trim());
    }
    if (form.email.trim() || googleConnectedEmail) {
      bits.push(form.email.trim() || googleConnectedEmail || '');
    }
    return bits.filter(Boolean);
  }, [form.email, form.firstName, form.lastName, googleConnectedEmail]);

  const goBack = () => {
    setError('');
    if (step === 'otp') {
      setOtp('');
      setOtpSent(false);
      setStep('account');
    }
  };

  const validateEmail = () => {
    const email = form.email.trim();
    if (!email) {
      setEmailError(t('Enter your email address', 'Ilagay ang email address mo'));
      return null;
    }
    if (!EMAIL_RE.test(email)) {
      setEmailError(t('Enter a valid email address', 'Maglagay ng valid na email address'));
      return null;
    }
    setEmailError('');
    return email;
  };

  const handleGooglePrefill = async (idToken: string) => {
    setGoogleLoading(true);
    setError('');
    try {
      const res = await api<{
        data: {
          email: string;
          firstName: string;
          lastName: string;
          avatarUrl?: string | null;
        };
      }>('/auth/google/profile', {
        method: 'POST',
        body: JSON.stringify({ idToken }),
      });

      setGoogleIdToken(idToken);
      setGoogleConnectedEmail(res.data.email);
      setForm((prev) => ({
        ...prev,
        firstName: res.data.firstName || prev.firstName,
        lastName: res.data.lastName || prev.lastName,
        email: res.data.email || prev.email,
        password: '',
      }));
      setConfirmPassword('');
      setPasswordError('');
      setConfirmPasswordError('');
      setEmailError('');
    } catch (err: unknown) {
      setError(
        err instanceof Error
          ? err.message
          : t('Could not load Google profile', 'Hindi ma-load ang Google profile')
      );
    } finally {
      setGoogleLoading(false);
    }
  };

  const clearGooglePrefill = () => {
    setGoogleIdToken(null);
    setGoogleConnectedEmail(null);
    setForm((prev) => ({ ...prev, password: '' }));
    setConfirmPassword('');
  };

  const handleAccountNext = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setPasswordError('');
    setConfirmPasswordError('');
    setTermsError('');
    setEmailError('');

    if (!form.firstName.trim() || !form.lastName.trim()) {
      setError(t('First and last name are required', 'Kailangan ang pangalan at apelyido'));
      return;
    }

    if (!googleIdToken) {
      const email = validateEmail();
      if (!email) return;

      if (form.password.length < 8) {
        setPasswordError(
          t(
            'Password must be at least 8 characters',
            'Ang password ay dapat hindi bababa sa 8 character'
          )
        );
        return;
      }
      if (form.password !== confirmPassword) {
        setConfirmPasswordError(t('Passwords do not match', 'Hindi magkatugma ang mga password'));
        return;
      }
    }

    if (!acceptedTerms) {
      setTermsError(
        t(
          'Please accept the Terms & Conditions to continue.',
          'Tanggapin muna ang Terms & Conditions para makapagpatuloy.'
        )
      );
      return;
    }

    if (googleIdToken) {
      setLoading(true);
      setError('');
      try {
        await register({
          firstName: form.firstName.trim(),
          lastName: form.lastName.trim(),
          email: form.email.trim() || undefined,
          role: 'CUSTOMER',
          googleIdToken,
        });
        router.push('/customer/dashboard');
      } catch (err: unknown) {
        setError(
          err instanceof Error
            ? err.message
            : t('Registration failed', 'Hindi natapos ang registration')
        );
      } finally {
        setLoading(false);
      }
      return;
    }

    setOtp('');
    setOtpSent(false);
    setStep('otp');
  };

  const handleSendOTP = async (e?: React.FormEvent) => {
    e?.preventDefault();
    const email = validateEmail();
    if (!email) return;
    setLoading(true);
    setError('');
    try {
      await api('/auth/customer/send-otp', {
        method: 'POST',
        body: JSON.stringify({ email }),
      });
      setOtpSent(true);
      setOtp('');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('Failed to send OTP', 'Hindi naipadala ang OTP'));
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyAndRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!acceptedTerms) {
      setError(
        t(
          'Please accept the Terms & Conditions to create your account.',
          'Tanggapin muna ang Terms & Conditions para magawa ang account mo.'
        )
      );
      setStep('account');
      return;
    }
    const email = validateEmail();
    if (!email) return;
    setLoading(true);
    setError('');
    try {
      await register({
        firstName: form.firstName.trim(),
        lastName: form.lastName.trim(),
        email,
        role: 'CUSTOMER',
        otpCode: otp,
        password: form.password,
      });
      router.push('/customer/dashboard');
    } catch (err: unknown) {
      setError(
        err instanceof Error ? err.message : t('Registration failed', 'Hindi natapos ang registration')
      );
    } finally {
      setLoading(false);
    }
  };

  const handleResendOTP = async () => {
    const email = validateEmail();
    if (!email) return;
    setResending(true);
    setError('');
    try {
      await api('/auth/customer/resend-otp', {
        method: 'POST',
        body: JSON.stringify({ email }),
      });
    } catch (err: unknown) {
      setError(
        err instanceof Error ? err.message : t('Failed to resend OTP', 'Hindi naipadala ulit ang OTP')
      );
    } finally {
      setResending(false);
    }
  };

  const heroSubtitle =
    step === 'otp' && otpSent
      ? t(`Code sent to ${form.email.trim()}`, `Naipadala ang code sa ${form.email.trim()}`)
      : t(meta.subtitle, meta.subtitleTl);

  return (
    <RegisterFormShell
      roleLabel={t('Customer registration', 'Customer registration')}
      title={t(meta.title, meta.titleTl)}
      subtitle={heroSubtitle}
      backLabel={t('Back to role selection', 'Bumalik sa pagpili ng role')}
      lang={lang}
      stepIndicator={
        <RegisterStepIndicator steps={[...STEPS]} current={step} lang={lang} />
      }
    >
      {step === 'account' && (
        <form onSubmit={handleAccountNext} className="mx-auto max-w-2xl">
          <RegisterFormPanel>
            {!googleIdToken && isGoogleSignInConfigured() && (
              <RegisterFormSection
                icon={Sparkles}
                eyebrow={t('Optional', 'Opsyonal')}
                title={t('Quick start', 'Mabilisang umpisa')}
                description={t(
                  'Autofill your name and email from Google — or skip and type them in.',
                  'Auto-fill ang pangalan at email mula sa Google — o i-type nang manual.'
                )}
              >
                <GoogleSignInButton
                  mode="continue"
                  onCredential={handleGooglePrefill}
                  onError={setError}
                  disabled={loading || googleLoading}
                  dividerLabel={t('or fill in manually', 'o i-type nang manual')}
                />
                {googleLoading && (
                  <p className="text-center text-sm text-muted">
                    {t('Loading Google profile…', 'Kinukuha ang Google profile…')}
                  </p>
                )}
              </RegisterFormSection>
            )}

            {googleIdToken && googleConnectedEmail && (
              <RegisterGoogleBanner
                email={googleConnectedEmail}
                onClear={clearGooglePrefill}
                clearLabel={t('Use manual instead', 'Manual na lang')}
                connectedLabel={t('Connected with Google', 'Nakakonekta sa Google')}
                hint={t(
                  'Details below were filled from Google — edit anything if needed.',
                  'Nakuha ang detalye mula sa Google — puwedeng baguhin.'
                )}
              />
            )}

            <RegisterFormSection
              icon={User}
              eyebrow={t('Step 1', 'Hakbang 1')}
              title={t('Your name', 'Pangalan mo')}
              description={t(
                'Use the name customers will recognize when you message or hire.',
                'Gamitin ang pangalang makikilala ng workers kapag nag-message o nag-hire ka.'
              )}
            >
              <RegisterFieldGrid>
                <Input
                  label={t('First Name', 'Pangalan')}
                  value={form.firstName}
                  onChange={(e) => setForm({ ...form, firstName: e.target.value })}
                  required
                  className="rounded-none"
                />
                <Input
                  label={t('Last Name', 'Apelyido')}
                  value={form.lastName}
                  onChange={(e) => setForm({ ...form, lastName: e.target.value })}
                  required
                  className="rounded-none"
                />
              </RegisterFieldGrid>
            </RegisterFormSection>

            <RegisterFormSection
              icon={Mail}
              eyebrow={t('Step 2', 'Hakbang 2')}
              title={t('Sign-in details', 'Detalye sa pag-sign in')}
              description={
                googleIdToken
                  ? t(
                      'Your Google email will be used to sign in. No password needed.',
                      'Gagamitin ang Google email mo para mag-sign in. Walang password na kailangan.'
                    )
                  : t(
                      'Email and password are required to create your account.',
                      'Kailangan ang email at password para magawa ang account mo.'
                    )
              }
            >
              <RegisterFieldGroup>
                <Input
                  label={t('Email', 'Email address')}
                  type="email"
                  value={form.email}
                  onChange={(e) => {
                    setForm({ ...form, email: e.target.value });
                    if (emailError) setEmailError('');
                  }}
                  error={emailError}
                  disabled={Boolean(googleIdToken)}
                  required={!googleIdToken}
                  className={cn('rounded-none', googleIdToken && 'bg-slate-50')}
                />
                {googleIdToken && (
                  <p className="text-xs text-muted">
                    {t('Email comes from your Google account', 'Mula sa Google account mo ang email')}
                  </p>
                )}
              </RegisterFieldGroup>
              {!googleIdToken && (
                <RegisterFieldGrid>
                  <Input
                    label={t('Password', 'Password')}
                    type="password"
                    value={form.password}
                    onChange={(e) => {
                      setForm({ ...form, password: e.target.value });
                      if (passwordError) setPasswordError('');
                    }}
                    error={passwordError}
                    required
                    className="rounded-none"
                  />
                  <Input
                    label={t('Confirm password', 'Ulitin ang password')}
                    type="password"
                    value={confirmPassword}
                    onChange={(e) => {
                      setConfirmPassword(e.target.value);
                      if (confirmPasswordError) setConfirmPasswordError('');
                    }}
                    error={confirmPasswordError}
                    required
                    className="rounded-none"
                  />
                </RegisterFieldGrid>
              )}
            </RegisterFormSection>

            <RegisterFormSection
              icon={Shield}
              eyebrow={t('Step 3', 'Hakbang 3')}
              title={t('Terms & Conditions', 'Terms & Conditions')}
              description={t(
                'Please review and accept before continuing.',
                'Basahin at tanggapin muna bago magpatuloy.'
              )}
            >
              <RegisterTermsSection
                id="customer-accept-terms"
                lang={lang}
                role="customer"
                accepted={acceptedTerms}
                onChange={(checked) => {
                  setAcceptedTerms(checked);
                  if (checked) setTermsError('');
                }}
                error={termsError}
              />
            </RegisterFormSection>

            {error ? <RegisterFormError message={error} /> : null}

            <RegisterStepActions lang={lang}>
              <Button
                type="submit"
                className="auth-submit w-full gap-2 rounded-none sm:min-w-[12rem]"
                disabled={googleLoading || loading}
              >
                {loading
                  ? t('Creating account...', 'Ginagawa ang account...')
                  : googleIdToken
                    ? t('Create account', 'Gawin ang account')
                    : t('Continue', 'Magpatuloy')}
                {!loading && <ArrowRight className="h-4 w-4" />}
              </Button>
            </RegisterStepActions>
          </RegisterFormPanel>

          <RegisterFormFooter>
            <p>
              {t('Already have an account?', 'May account ka na?')}{' '}
              <Link href="/login" className="auth-link">
                {t('Sign in', 'Mag-sign in')}
              </Link>
            </p>
            <p>
              {t('Not a customer?', 'Hindi customer?')}{' '}
              <Link href="/register" className="auth-link">
                {t('Choose a different role', 'Pumili ng ibang role')}
              </Link>
              {' · '}
              <Link href="/register/worker" className="auth-link">
                {t('Register as worker', 'Mag-register bilang worker')}
              </Link>
            </p>
          </RegisterFormFooter>
        </form>
      )}

      {step === 'otp' && (
        <div className="mx-auto max-w-lg space-y-4">
          {summaryBits.length > 0 && (
            <RegisterSummaryCard
              eyebrow={t('Almost done', 'Malapit na')}
              title={summaryBits.join(' · ')}
              description={t(
                'Verify your email to create your customer account.',
                'I-verify ang email mo para magawa ang customer account.'
              )}
            />
          )}

          <RegisterFormPanel>
            <RegisterInfoCallout icon={Shield}>
              {otpSent
                ? t(
                    'Enter the code we sent to your email to complete registration.',
                    'Ilagay ang code na ipinadala namin sa email mo para makumpleto ang registration.'
                  )
                : t(
                    "We'll email you a 6-digit code to confirm your address before creating your account.",
                    'Papadalhan ka namin ng 6-digit code sa email para i-confirm ang address mo bago gawin ang account.'
                  )}
            </RegisterInfoCallout>

            <form
              onSubmit={otpSent ? handleVerifyAndRegister : handleSendOTP}
              className="divide-y divide-[#ebe6db]"
            >
              <RegisterFormSection title={t('Email verification', 'Email verification')}>
                <Input
                  label={t('Email', 'Email address')}
                  type="email"
                  value={form.email}
                  readOnly
                  className="rounded-none bg-slate-50"
                />
                {otpSent && (
                  <p className="text-xs text-muted">
                    {t(
                      'Need a different email? Go back and update it on the previous step.',
                      'Ibang email? Bumalik at i-update sa previous step.'
                    )}
                  </p>
                )}
                {otpSent && (
                  <Input
                    label={t('Verification code', 'Code ng beripikasyon')}
                    value={otp}
                    onChange={(e) => setOtp(e.target.value.replace(/\D/g, '').slice(0, 6))}
                    placeholder="123456"
                    inputMode="numeric"
                    autoComplete="one-time-code"
                    maxLength={6}
                    className="rounded-none text-center text-lg font-semibold tracking-[0.3em] md:text-xl"
                    required
                  />
                )}
              </RegisterFormSection>

              {error ? <RegisterFormError message={error} /> : null}

              <RegisterStepActions onBack={goBack} lang={lang}>
                {!otpSent ? (
                  <Button
                    type="submit"
                    className="auth-submit w-full gap-2 rounded-none"
                    disabled={loading || !EMAIL_RE.test(form.email.trim())}
                  >
                    {loading
                      ? t('Sending code...', 'Ipinapadala...')
                      : t('Send verification code', 'Ipadala ang verification code')}
                  </Button>
                ) : (
                  <>
                    <Button
                      type="submit"
                      className="auth-submit w-full rounded-none"
                      disabled={loading || otp.length < 6}
                    >
                      {loading
                        ? t('Creating account...', 'Ginagawa ang account...')
                        : t('Verify & Create Account', 'I-verify at gawin ang account')}
                    </Button>
                    <Button
                      type="button"
                      variant="outline"
                      className="w-full rounded-none border-[#d6d0c4]"
                      disabled={resending}
                      onClick={handleResendOTP}
                    >
                      {resending
                        ? t('Sending...', 'Ipinapadala...')
                        : t('Resend code', 'Ipadala ulit ang code')}
                    </Button>
                  </>
                )}
              </RegisterStepActions>
            </form>
          </RegisterFormPanel>
        </div>
      )}
    </RegisterFormShell>
  );
}
