'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff, Mail, Lock, User, Building2, Check, AlertCircle } from 'lucide-react';
import { useAuth } from '@client/contexts/AuthContext';
import { useLanguage } from '@client/contexts/LanguageContext';
import { usePublicBranding } from '@client/hooks/usePublicBranding';

interface FormErrors {
  restaurantName?: string;
  ownerName?: string;
  email?: string;
  password?: string;
  general?: string;
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null;
  return (
    <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
      <AlertCircle size={12} />
      {message}
    </p>
  );
}

function PasswordStrength({ password, t }: { password: string; t: (key: string, fb?: string) => string }) {
  if (!password) return null;
  const checks = [
    { label: t('auth.pwCheck8chars', '8+ characters'), pass: password.length >= 8 },
    { label: t('auth.pwCheckUppercase', 'Uppercase letter'), pass: /[A-Z]/.test(password) },
    { label: t('auth.pwCheckNumber', 'Number'), pass: /\d/.test(password) },
  ];
  const score = checks.filter(c => c.pass).length;
  const strengthLabel = score === 0 ? '' : score === 1 ? t('auth.pwWeak', 'Weak') : score === 2 ? t('auth.pwFair', 'Fair') : t('auth.pwStrong', 'Strong');
  const strengthColor = score === 1 ? 'hsl(0, 84%, 44%)' : score === 2 ? 'hsl(38, 92%, 40%)' : 'hsl(142, 72%, 29%)';
  return (
    <div className="mt-2">
      <div className="flex gap-1 mb-1">
        {[1, 2, 3].map(i => (
          <div key={i} className="flex-1 h-1 rounded-full transition-all" style={{ backgroundColor: i <= score ? strengthColor : 'hsl(var(--border))' }} />
        ))}
      </div>
      {strengthLabel && <p className="text-xs font-medium" style={{ color: strengthColor }}>{strengthLabel} {t('auth.password', 'password')}</p>}
    </div>
  );
}

function DefaultLogoMark({ size = 28 }: { size?: number }) {
  return (
    <div
      className="rounded-xl flex items-center justify-center shrink-0"
      style={{ width: size, height: size, background: 'linear-gradient(135deg, hsl(22,89%,48%), hsl(22,89%,35%))' }}
    >
      <svg width={size * 0.45} height={size * 0.45} viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"/>
        <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
        <line x1="12" y1="19" x2="12" y2="22"/>
      </svg>
    </div>
  );
}

export default function RegisterPage() {
  const router = useRouter();
  const { signUp } = useAuth();
  const { t } = useLanguage();
  const [showPassword, setShowPassword] = useState(false);
  const [selectedPlan, setSelectedPlan] = useState('growth');
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({ restaurantName: '', ownerName: '', email: '', password: '' });
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});
  const { logoUrl, siteTitle: siteName } = usePublicBranding();

  interface Plan {
    id: string;
    name: string;
    price: string;
    period: string;
    features: string[];
    color: string;
    popular?: boolean;
  }

  const plans: Plan[] = [
    { id: 'starter', name: t('billing.starter', 'Starter'), price: '$49', period: '/mo', features: [t('billing.feature1Branch', '1 branch'), t('billing.feature500Queries', '500 AI queries/mo'), t('billing.featureChatAgent', 'Chat agent'), t('billing.featureBasicAnalytics', 'Basic analytics')], color: 'hsl(var(--info))' },
    { id: 'growth', name: t('billing.growth', 'Growth'), price: '$129', period: '/mo', features: [t('billing.feature3Branches', '3 branches'), t('billing.feature2000Queries', '2,000 AI queries/mo'), t('billing.featureVoiceChat', 'Voice + Chat agents'), t('billing.featureAdvancedAnalytics', 'Advanced analytics'), t('billing.featurePrioritySupport', 'Priority support')], color: 'hsl(var(--primary))', popular: true },
    { id: 'enterprise', name: t('billing.enterprise', 'Enterprise'), price: '$299', period: '/mo', features: [t('billing.featureUnlimitedBranches', 'Unlimited branches'), t('billing.featureUnlimitedQueries', 'Unlimited AI queries'), t('billing.featureAllChannels', 'All channels'), t('billing.featureCustomIntegrations', 'Custom integrations'), t('billing.featureDedicatedSupport', 'Dedicated support')], color: 'hsl(var(--accent))' },
  ];

  const validators: Record<string, (val: string) => string | undefined> = {
    restaurantName: (v) => !v.trim() ? t('auth.restaurantNameRequired', 'Restaurant name is required') : v.trim().length < 2 ? t('auth.minTwoChars', 'Must be at least 2 characters') : undefined,
    ownerName: (v) => !v.trim() ? t('auth.ownerNameRequired', 'Owner name is required') : v.trim().length < 2 ? t('auth.minTwoChars', 'Must be at least 2 characters') : undefined,
    email: (v) => !v.trim() ? t('auth.emailRequired', 'Email address is required') : !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? t('auth.emailInvalid', 'Please enter a valid email address') : undefined,
    password: (v) => !v ? t('auth.passwordRequired', 'Password is required') : v.length < 8 ? t('auth.passwordMin8', 'Password must be at least 8 characters') : undefined,
  };

  const handleChange = (field: string, value: string) => {
    setForm(prev => ({ ...prev, [field]: value }));
    if (touched[field]) setErrors(prev => ({ ...prev, [field]: validators[field]?.(value) }));
  };

  const handleBlur = (field: string) => {
    setTouched(prev => ({ ...prev, [field]: true }));
    setErrors(prev => ({ ...prev, [field]: validators[field]?.(form[field as keyof typeof form]) }));
  };

  const validate = (): boolean => {
    const newErrors: FormErrors = {};
    const newTouched: Record<string, boolean> = {};
    Object.keys(validators).forEach(field => {
      newTouched[field] = true;
      const err = validators[field]?.(form[field as keyof typeof form]);
      if (err) newErrors[field as keyof FormErrors] = err;
    });
    setErrors(newErrors);
    setTouched(newTouched);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validate()) return;
    setLoading(true);
    setErrors({});
    try {
      const result = await signUp(form.email, form.password, {
        ownerName: form.ownerName,
        restaurantName: form.restaurantName,
        plan: selectedPlan,
      });
      // Hand the names off to /onboarding so Step 1 doesn't ask for them again.
      try {
        sessionStorage.setItem('pendingOnboarding', JSON.stringify({
          restaurantName: form.restaurantName,
          ownerName: form.ownerName,
        }));
      } catch { /* sessionStorage may be unavailable; onboarding falls back to /api/auth/me */ }

      // OTP gate: account is only created after email is verified.
      if ((result as { requiresOtp?: boolean })?.requiresOtp) {
        router.push(`/verify-email?email=${encodeURIComponent(form.email)}`);
        return;
      }
      router.push('/onboarding');
      router.refresh();
    } catch (err: any) {
      setErrors({ general: err?.message || t('auth.registrationFailed', 'Registration failed. Please try again.') });
    } finally {
      setLoading(false);
    }
  };

  const inputStyle = (field: string) => ({
    borderColor: touched[field] && errors[field as keyof FormErrors] ? 'hsl(0, 84%, 44%)' : undefined,
    boxShadow: touched[field] && errors[field as keyof FormErrors] ? '0 0 0 2px hsl(0, 84%, 44%, 0.15)' : undefined,
  });

  return (
    <div className="min-h-screen flex items-start justify-center py-10 px-4" style={{ backgroundColor: 'hsl(var(--background))' }}>
      <div className="w-full max-w-2xl">
        <div className="mb-8">
          <Link href="/" className="inline-flex items-center gap-2.5 group" aria-label={t("common.goToHomepage", "Go to homepage")}>
            {logoUrl
              ? <img src={logoUrl} alt={siteName} className="rounded-xl object-contain shrink-0" style={{ width: 28, height: 28 }} />
              : <DefaultLogoMark size={28} />
            }
            <span className="font-bold text-lg" style={{ color: 'hsl(var(--foreground))' }}>{siteName}</span>
          </Link>
        </div>

        <div className="mb-8">
          <h2 className="text-2xl font-bold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('auth.createAccount', 'Create your account')}</h2>
          <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('auth.trialNoCard', 'Start your 14-day free trial — no credit card required')}</p>
        </div>

        {errors.general && (
          <div className="flex items-center gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
            <AlertCircle size={15} />
            {errors.general}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-6" noValidate>
          {/* Account details */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('auth.accountDetails', 'Account Details')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.restaurantName', 'Restaurant Name')}</label>
                <div className="relative">
                  <Building2 size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.restaurantName && errors.restaurantName ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    className="input-base pl-9"
                    placeholder={t('auth.restaurantNamePlaceholder', 'The Rustic Fork')}
                    value={form.restaurantName}
                    onChange={e => handleChange('restaurantName', e.target.value)}
                    onBlur={() => handleBlur('restaurantName')}
                    style={inputStyle('restaurantName')}
                  />
                </div>
                <FieldError message={touched.restaurantName ? errors.restaurantName : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.ownerName', 'Owner / Manager Name')}</label>
                <div className="relative">
                  <User size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.ownerName && errors.ownerName ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    className="input-base pl-9"
                    placeholder={t('auth.ownerNamePlaceholder', 'Marco Khalid')}
                    value={form.ownerName}
                    onChange={e => handleChange('ownerName', e.target.value)}
                    onBlur={() => handleBlur('ownerName')}
                    style={inputStyle('ownerName')}
                  />
                </div>
                <FieldError message={touched.ownerName ? errors.ownerName : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.emailAddress', 'Email Address')}</label>
                <div className="relative">
                  <Mail size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.email && errors.email ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    type="email"
                    className="input-base pl-9"
                    placeholder={t('auth.emailPlaceholder', 'you@restaurant.com')}
                    value={form.email}
                    onChange={e => handleChange('email', e.target.value)}
                    onBlur={() => handleBlur('email')}
                    style={inputStyle('email')}
                  />
                </div>
                <FieldError message={touched.email ? errors.email : undefined} />
              </div>
              <div>
                <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('auth.password', 'Password')}</label>
                <div className="relative">
                  <Lock size={15} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: touched.password && errors.password ? 'hsl(0, 84%, 44%)' : 'hsl(var(--muted-foreground))' }} />
                  <input
                    type={showPassword ? 'text' : 'password'}
                    className="input-base pl-9 pr-10"
                    placeholder={t('auth.passwordMinPlaceholder', 'Min 8 characters')}
                    value={form.password}
                    onChange={e => handleChange('password', e.target.value)}
                    onBlur={() => handleBlur('password')}
                    style={inputStyle('password')}
                  />
                  <button type="button" className="absolute right-3 top-1/2 -translate-y-1/2" onClick={() => setShowPassword(!showPassword)} style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {showPassword ? <EyeOff size={15} /> : <Eye size={15} />}
                  </button>
                </div>
                <FieldError message={touched.password ? errors.password : undefined} />
                <PasswordStrength password={form.password} t={t} />
              </div>
            </div>
          </div>

          {/* Plan selection */}
          <div className="card p-5">
            <h3 className="font-semibold mb-4" style={{ color: 'hsl(var(--foreground))' }}>{t('billing.choosePlan', 'Choose a Plan')}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              {plans.map(plan => (
                <button
                  key={plan.id}
                  type="button"
                  onClick={() => setSelectedPlan(plan.id)}
                  className="relative text-left p-4 rounded-xl border-2 transition-all"
                  style={{
                    borderColor: selectedPlan === plan.id ? plan.color : 'hsl(var(--border))',
                    backgroundColor: selectedPlan === plan.id ? plan.color + '08' : 'hsl(var(--surface))',
                  }}
                >
                  {plan.popular && (
                    <span className="absolute -top-2.5 left-1/2 -translate-x-1/2 text-xs font-bold px-2.5 py-0.5 rounded-full text-white" style={{ backgroundColor: plan.color }}>{t('billing.popular', 'Popular')}</span>
                  )}
                  <div className="flex items-center justify-between mb-2">
                    <span className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{plan.name}</span>
                    {selectedPlan === plan.id && (
                      <span className="w-5 h-5 rounded-full flex items-center justify-center" style={{ backgroundColor: plan.color }}>
                        <Check size={12} className="text-white" />
                      </span>
                    )}
                  </div>
                  <div className="mb-3">
                    <span className="text-xl font-bold" style={{ color: plan.color }}>{plan.price}</span>
                    <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{plan.period}</span>
                  </div>
                  <ul className="space-y-1">
                    {plan.features.map(f => (
                      <li key={f} className="flex items-center gap-1.5 text-xs" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                        <Check size={11} style={{ color: plan.color, flexShrink: 0 }} /> {f}
                      </li>
                    ))}
                  </ul>
                </button>
              ))}
            </div>
          </div>

          <button type="submit" disabled={loading} className="btn-primary w-full justify-center py-3">
            {loading ? (
              <span className="flex items-center gap-2">
                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                {t('auth.creatingAccount', 'Creating account...')}
              </span>
            ) : t('auth.startFreeTrial', 'Start Free Trial')}
          </button>

          <p className="text-center text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('auth.byCreating', 'By creating an account you agree to our')}{' '}
            <span className="underline cursor-pointer" style={{ color: 'hsl(var(--primary))' }}>{t('auth.termsOfService', 'Terms of Service')}</span>
            {' '}{t('common.and', 'and')}{' '}
            <span className="underline cursor-pointer" style={{ color: 'hsl(var(--primary))' }}>{t('auth.privacyPolicy', 'Privacy Policy')}</span>
          </p>

          <p className="text-center text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('auth.alreadyHaveAccount', 'Already have an account?')}{' '}
            <Link href="/login" className="font-semibold" style={{ color: 'hsl(var(--primary))' }}>{t('auth.signIn', 'Sign in')}</Link>
          </p>
        </form>
      </div>
    </div>
  );
}
