import {
  Eye,
  EyeOff,
  Mail,
  Lock,
  ArrowRight,
  BarChart2,
  Sparkles,
  TrendingUp,
  Globe,
  CheckCircle2,
  Star,
  LucideIcon,
} from 'lucide-react';
import { z } from 'zod';

import { useState, useEffect, FormEventHandler } from 'react';

import { Head, Link, useForm } from '@inertiajs/react';

import {
  PasswordStrengthIndicator,
  type PasswordRequirement,
} from '@/Components/auth/PasswordStrengthIndicator';
import { SocialAuthButtons } from '@/Components/auth/SocialAuthButtons';
import InputError from '@/Components/InputError';
import { LegalContentModal } from '@/Components/legal/LegalContentModal';
import { Checkbox } from '@/Components/ui/checkbox';
import { Input } from '@/Components/ui/input';
import { Label } from '@/Components/ui/label';
import { LoadingButton } from '@/Components/ui/loading-button';
import { CTA_LABELS } from '@/config/cta-labels';
import { useFormValidation } from '@/hooks/useFormValidation';
import AuthLayout from '@/Layouts/AuthLayout';
import { trackEvent, trackProductEvent } from '@/lib/analytics';
import {
  REGISTER_PAGE_VIEWED,
  REGISTRATION_COMPLETED,
  REGISTRATION_STARTED,
} from '@/lib/event-catalog';

const registerSchema = z.object({
  email: z.string().min(1, 'Email is required').email('Please enter a valid email address'),
  password: z.string().min(8, 'Password must be at least 8 characters'),
});

interface Feature {
  icon: LucideIcon;
  title: string;
  description: string;
}

interface RegisterTestimonial {
  name: string;
  role: string;
  company: string;
  quote: string;
  rating: number;
}

const STATIC_TESTIMONIALS: RegisterTestimonial[] = [
  {
    name: 'James C.',
    role: 'SEO Consultant',
    company: 'Freelance SEO',
    quote:
      'RankWiz found 14 pages bleeding traffic that I hadn\u2019t noticed in 6 months of manual GSC review. Recovered two product pages in under a week.',
    rating: 5,
  },
  {
    name: 'Sarah M.',
    role: 'Agency Owner',
    company: 'Bloom Digital',
    quote:
      'The ROI tracking sold me. I can show clients a before/after traffic graph tied to specific recommendations.',
    rating: 5,
  },
];

interface RegisterProps {
  error?: string;
  rememberDays?: number;
  features?: {
    socialAuth?: boolean;
  };
  metrics?: {
    sites_connected: number;
  };
  testimonials?: RegisterTestimonial[];
}

const passwordRequirements: PasswordRequirement[] = [
  { id: 'length', label: 'At least 8 characters', test: (p) => p.length >= 8 },
  { id: 'uppercase', label: 'One uppercase letter', test: (p) => /[A-Z]/.test(p) },
  { id: 'lowercase', label: 'One lowercase letter', test: (p) => /[a-z]/.test(p) },
  { id: 'number', label: 'One number', test: (p) => /\d/.test(p) },
];

const sellingPoints: Feature[] = [
  {
    icon: BarChart2,
    title: 'Traffic Insights from GSC',
    description:
      'See exactly which pages are winning and losing, backed by your real Google Search Console data.',
  },
  {
    icon: Sparkles,
    title: 'AI Drafts Included',
    description:
      'AI drafts included on every plan. Generate content fixes ranked by impact — no API key needed to start.',
  },
  {
    icon: TrendingUp,
    title: 'ROI Tracking on Every Fix',
    description:
      'Know the impact of each recommendation you apply, measured in clicks and ranking.',
  },
  {
    icon: Globe,
    title: 'WordPress-Native Integration',
    description: 'Two-way sync with your WordPress site for seamless content management.',
  },
];

export default function Register({
  error,
  rememberDays = 30,
  features,
  metrics,
  testimonials,
}: RegisterProps) {
  useEffect(() => {
    trackProductEvent(REGISTER_PAGE_VIEWED);
    trackEvent(REGISTRATION_STARTED);

    if (typeof window !== 'undefined') {
      const params = new URLSearchParams(window.location.search);

      // CRO-005: Pre-fill email captured on /free-audit intent form
      const prefillEmail = params.get('email') ?? localStorage.getItem('rankwiz_lead_email');
      if (prefillEmail) {
        setData('email', prefillEmail);
        localStorage.removeItem('rankwiz_lead_email');
      }

      // BILL-004: Preserve billing intent from marketing pricing page
      const billingPeriod = params.get('billing_period');
      const plan = params.get('plan');
      if (billingPeriod) localStorage.setItem('intended_billing_period', billingPeriod);
      if (plan) localStorage.setItem('intended_plan', plan);
    }
    // setData is stable across renders (Inertia useForm guarantee)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [showPassword, setShowPassword] = useState(false);
  const [legalModal, setLegalModal] = useState<'terms' | 'privacy' | null>(null);
  const {
    errors: clientErrors,
    validateField,
    validateAll,
    clearError,
  } = useFormValidation(registerSchema);

  // Helper for grammatically correct day/days
  const dayText = rememberDays === 1 ? 'day' : 'days';

  const { data, setData, post, processing, errors, reset } = useForm({
    name: '',
    email: '',
    password: '',
    remember: false,
  });

  const handleSubmit: FormEventHandler = (e) => {
    e.preventDefault();

    if (!validateAll(data)) return;

    post(route('register'), {
      onSuccess: () => {
        trackEvent(REGISTRATION_COMPLETED, { field_count: 3, cta_label: CTA_LABELS.REGISTER });

        // BILL-004: Redirect to pricing page with preserved billing intent
        if (typeof window !== 'undefined') {
          const billingPeriod = localStorage.getItem('intended_billing_period');
          const plan = localStorage.getItem('intended_plan');
          if (billingPeriod || plan) {
            const params = new URLSearchParams();
            if (billingPeriod) params.set('billing_period', billingPeriod);
            if (plan) params.set('plan', plan);
            localStorage.removeItem('intended_billing_period');
            localStorage.removeItem('intended_plan');
            window.location.href = `${route('billing.plans')}?${params.toString()}`;
          }
        }
      },
      onFinish: () => reset('password'),
    });
  };

  const displayTestimonials =
    testimonials && testimonials.length > 0 ? testimonials : STATIC_TESTIMONIALS;
  const featuredTestimonial = displayTestimonials[0];

  const leftContent = (
    <div className="max-w-lg space-y-8">
      <div className="space-y-4">
        <h1 className="text-4xl font-bold leading-tight">Your WordPress SEO command center.</h1>
        <p className="text-lg text-brand-surface-foreground/70 leading-relaxed">
          Connect Google Search Console, find what&apos;s broken, and fix it with AI — free to
          start, no credit card required.
        </p>
      </div>

      <div className="space-y-4">
        {sellingPoints.map((feature, index) => (
          <div
            key={feature.title}
            className="flex items-start gap-4 animate-fade-in"
            style={{ animationDelay: `${index * 0.1}s` }}
          >
            <div className="w-10 h-10 rounded-lg bg-brand-surface-foreground/10 flex items-center justify-center flex-shrink-0">
              <feature.icon className="h-5 w-5" />
            </div>
            <div>
              <h3 className="font-semibold mb-0.5">{feature.title}</h3>
              <p className="text-sm text-brand-surface-foreground/60">{feature.description}</p>
            </div>
          </div>
        ))}
      </div>

      {/* CRO-004: Social proof testimonial in left panel */}
      {featuredTestimonial && (
        <div className="rounded-xl border border-brand-surface-foreground/10 bg-brand-surface-foreground/5 p-5 space-y-3">
          <div className="flex gap-0.5" aria-label={`${featuredTestimonial.rating} out of 5 stars`}>
            {Array.from({ length: featuredTestimonial.rating }).map((_, i) => (
              <Star key={i} className="h-4 w-4 fill-current text-yellow-400" aria-hidden="true" />
            ))}
          </div>
          <blockquote className="text-sm leading-relaxed text-brand-surface-foreground/80 italic">
            &ldquo;{featuredTestimonial.quote}&rdquo;
          </blockquote>
          <div className="text-sm font-semibold">
            {featuredTestimonial.name}
            <span className="font-normal text-brand-surface-foreground/60">
              {' '}
              · {featuredTestimonial.role}
              {featuredTestimonial.company && `, ${featuredTestimonial.company}`}
            </span>
          </div>
        </div>
      )}

      {/* Social proof count */}
      {metrics && (
        <p className="text-sm text-brand-surface-foreground/60">
          Join{' '}
          <span className="font-semibold text-brand-surface-foreground">
            {Math.max(metrics.sites_connected, 50)}+
          </span>{' '}
          site owners tracking SEO with real GSC data
        </p>
      )}
    </div>
  );

  const leftFooter = (
    <div className="pt-6 border-t border-brand-surface-foreground/10">
      <div className="flex flex-wrap items-center gap-4 text-sm">
        <span className="flex items-center gap-1.5">
          <CheckCircle2 className="h-4 w-4" />
          Free to get started
        </span>
        <span className="flex items-center gap-1.5">
          <CheckCircle2 className="h-4 w-4" />
          No credit card required
        </span>
      </div>
    </div>
  );

  const footer = (
    <>
      By creating an account, you agree to our{' '}
      <button
        type="button"
        onClick={() => setLegalModal('terms')}
        className="text-primary hover:underline"
      >
        Terms of Service
      </button>{' '}
      and{' '}
      <button
        type="button"
        onClick={() => setLegalModal('privacy')}
        className="text-primary hover:underline"
      >
        Privacy Policy
      </button>
    </>
  );

  return (
    <AuthLayout leftContent={leftContent} leftFooter={leftFooter} footer={footer}>
      {/* SEO-001: Add meta tags and noindex directive to auth pages */}
      <Head title="Create account">
        <meta
          name="description"
          content="Create a free RankWiz account to connect your WordPress site with Google Search Console and start optimizing your SEO."
        />
        <meta name="robots" content="noindex, nofollow" />
      </Head>
      <div className="space-y-8">
        {/* Header */}
        <div className="text-center lg:text-left">
          <h2 className="text-2xl md:text-3xl font-bold text-foreground">Create your account</h2>
          <p className="mt-2 text-muted-foreground">
            Connect your WordPress site and find SEO wins — free.
          </p>
        </div>

        {/* Social Login - Only show if feature is enabled */}
        {features?.socialAuth && (
          <SocialAuthButtons processing={processing} separatorText="or register with email" />
        )}

        {error && (
          <div className="rounded-md border border-destructive/20 bg-destructive/5 px-3 py-2 text-sm text-destructive">
            {error}
          </div>
        )}

        {/* Registration Form */}
        <form onSubmit={handleSubmit} className="space-y-5">
          <div className="space-y-2">
            <Label htmlFor="email">Email address</Label>
            <div className="relative flex items-center">
              <Mail className="absolute left-3 h-4 w-4 text-muted-foreground" />
              <Input
                id="email"
                type="email"
                placeholder="you@example.com"
                value={data.email}
                onChange={(e) => {
                  setData('email', e.target.value);
                  if (clientErrors.email) clearError('email');
                }}
                onBlur={(e) => validateField('email', e.target.value)}
                className="pl-10"
                autoComplete="username"
                required
                aria-describedby={
                  clientErrors.email || errors.email ? 'register-email-error' : undefined
                }
                aria-invalid={!!(clientErrors.email || errors.email)}
              />
            </div>
            <InputError
              id="register-email-error"
              message={clientErrors.email || errors.email}
              className="text-xs"
            />
          </div>

          <div className="space-y-3">
            <Label htmlFor="password">Password</Label>
            <div className="relative flex items-center">
              <Lock className="absolute left-3 h-4 w-4 text-muted-foreground" />
              <Input
                id="password"
                type={showPassword ? 'text' : 'password'}
                placeholder="Create a strong password"
                value={data.password}
                onChange={(e) => {
                  setData('password', e.target.value);
                  if (clientErrors.password) clearError('password');
                }}
                onBlur={(e) => validateField('password', e.target.value)}
                className="pl-10 pr-10"
                autoComplete="new-password"
                required
                aria-describedby={
                  clientErrors.password || errors.password ? 'register-password-error' : undefined
                }
                aria-invalid={!!(clientErrors.password || errors.password)}
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute right-3 text-muted-foreground hover:text-foreground transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-sm"
                aria-label={showPassword ? 'Hide password' : 'Show password'}
                aria-pressed={showPassword}
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </button>
            </div>

            <PasswordStrengthIndicator
              password={data.password}
              passwordRequirements={passwordRequirements}
            />
            <InputError
              id="register-password-error"
              message={clientErrors.password || errors.password}
              className="text-xs"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="name" className="text-muted-foreground">
              First name <span className="font-normal text-xs">(optional)</span>
            </Label>
            <Input
              id="name"
              type="text"
              placeholder="We'll use it to personalise your experience"
              value={data.name}
              onChange={(e) => setData('name', e.target.value)}
              autoComplete="given-name"
              aria-describedby={errors.name ? 'register-name-error' : undefined}
              aria-invalid={!!errors.name}
            />
            <InputError id="register-name-error" message={errors.name} className="text-xs" />
          </div>

          <div className="flex items-center space-x-2">
            <Checkbox
              id="remember-register"
              checked={data.remember}
              onCheckedChange={(checked) => setData('remember', checked === true)}
            />
            <Label
              htmlFor="remember-register"
              className="text-sm font-normal text-muted-foreground cursor-pointer"
            >
              Keep me signed in for {rememberDays} {dayText}
            </Label>
          </div>

          <LoadingButton
            type="submit"
            className="w-full group"
            size="lg"
            loading={processing}
            loadingText="Creating account..."
          >
            {CTA_LABELS.REGISTER}
            <ArrowRight className="ml-2 h-4 w-4 transition-transform group-hover:translate-x-1" />
          </LoadingButton>
        </form>

        {/* Login Link */}
        <p className="text-center text-sm text-muted-foreground">
          Already have an account?{' '}
          <Link
            href={route('login')}
            className="font-medium text-primary hover:text-primary/80 transition-colors"
          >
            Sign in instead
          </Link>
        </p>
      </div>

      {/* Legal Content Modal */}
      <LegalContentModal type={legalModal} onClose={() => setLegalModal(null)} />
    </AuthLayout>
  );
}
