'use client';

import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useSearchParams } from 'next/navigation';
import { registrationSchema, type RegistrationFormData } from '@/lib/validations/registration';
import { CheckCircle, Loader2, ChevronRight, ChevronLeft, User, Zap, Target } from 'lucide-react';

import StepPersonal from './stepPersonal';
import StepTrack    from './StepTrack';
import StepGoals    from './StepGoals';
import SuccessScreen from './SuccessScreen';

const STEPS = [
  { id: 1, label: 'Personal', icon: User },
  { id: 2, label: 'Track',    icon: Zap },
  { id: 3, label: 'Goals',    icon: Target },
];

export default function RegistrationForm() {
  const searchParams = useSearchParams();
  const refCode = searchParams.get('ref') ?? '';

  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted]       = useState(false);
  const [serverError, setServerError]   = useState('');
  const [submittedName, setSubmittedName] = useState('');

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<RegistrationFormData>({
    resolver: zodResolver(registrationSchema),
    mode: 'onChange',
    defaultValues: {
      educationLevel: 'undergraduate',
      institution: 'N/A',
      referralCode: refCode,
    },
  });

  // Pre-fill referral code if ?ref= param changes
  useEffect(() => {
    if (refCode) {
      setValue('referralCode', refCode);
    }
  }, [refCode, setValue]);

  const stepFields: Record<number, (keyof RegistrationFormData)[]> = {
    1: ['fullName', 'email', 'phone', 'gender', 'ageRange'],
    2: ['stack'],
    3: ['motivation', 'heardFrom'],
  };

  const nextStep = async () => {
    const valid = await trigger(stepFields[currentStep]);
    if (valid) setCurrentStep((s) => Math.min(s + 1, 3));
  };

  const prevStep = () => setCurrentStep((s) => Math.max(s - 1, 1));

  const onSubmit = async (data: RegistrationFormData) => {
    setIsSubmitting(true);
    setServerError('');

    try {
      const res = await fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...data, _hp: '' }),
      });

      const result = await res.json();

      if (res.status === 429) {
        setServerError(result.error || 'Too many submissions. Please try again later.');
        return;
      }

      if (!res.ok) {
        setServerError(result.error || 'Something went wrong. Please try again.');
        return;
      }

      setSubmittedName(data.fullName.split(' ')[0]);
      setSubmitted(true);
    } catch {
      setServerError('Network error. Please check your connection and try again.');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (submitted) {
    return <SuccessScreen name={submittedName} />;
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
      {/* Honeypot */}
      <input
        type="text"
        {...register('_hp' as keyof RegistrationFormData)}
        aria-hidden="true"
        tabIndex={-1}
        autoComplete="off"
        style={{
          position: 'absolute', width: '1px', height: '1px',
          padding: 0, margin: '-1px', overflow: 'hidden',
          clip: 'rect(0,0,0,0)', whiteSpace: 'nowrap', borderWidth: 0,
        }}
      />

      {/* Step progress */}
      <div className="flex items-center justify-center mb-8">
        <div className="flex items-center justify-between w-full max-w-md">
          {STEPS.map((step, idx) => {
            const Icon     = step.icon;
            const isActive = step.id === currentStep;
            const isDone   = step.id < currentStep;
            return (
              <div key={step.id} className="flex items-center">
                <div className="flex flex-col items-center">
                  <div
                    className={`w-9 h-9 rounded-full flex items-center justify-center transition-all duration-300 ${
                      isDone
                        ? 'bg-orange-500 text-white'
                        : isActive
                        ? 'bg-gray-900 text-white ring-4 ring-gray-900/10'
                        : 'bg-gray-100 text-gray-400'
                    }`}
                  >
                    {isDone ? <CheckCircle className="w-4 h-4" /> : <Icon className="w-3.5 h-3.5" />}
                  </div>
                  <span
                    className={`text-[10px] mt-1 font-semibold tracking-wide uppercase text-center ${
                      isActive ? 'text-gray-900' : isDone ? 'text-orange-500' : 'text-gray-400'
                    }`}
                  >
                    {step.label}
                  </span>
                </div>
                {idx < STEPS.length - 1 && (
                  <div
                    className={`w-10 sm:w-16 h-px mx-2 sm:mx-3 mb-4 transition-all duration-300 ${
                      step.id < currentStep ? 'bg-orange-400' : 'bg-gray-200'
                    }`}
                  />
                )}
              </div>
            );
          })}
        </div>
      </div>

      {currentStep === 1 && (
        <StepPersonal register={register} errors={errors} setValue={setValue} watch={watch} />
      )}
      {currentStep === 2 && (
        <StepTrack errors={errors} setValue={setValue} watch={watch} />
      )}
      {currentStep === 3 && (
        <StepGoals
          register={register}
          errors={errors}
          setValue={setValue}
          watch={watch}
          serverError={serverError}
        />
      )}

      {/* Navigation */}
      <div className="flex gap-3 pt-1">
        {currentStep > 1 && (
          <button
            type="button"
            onClick={prevStep}
            className="flex items-center gap-2 px-5 py-3 rounded-xl border-2 border-gray-200 text-gray-700 text-sm font-medium hover:bg-gray-50 transition-colors"
          >
            <ChevronLeft className="w-4 h-4" />
            Back
          </button>
        )}
        {currentStep < 3 ? (
          <button
            type="button"
            onClick={nextStep}
            className="flex-1 flex items-center justify-center gap-2 bg-gray-900 text-white px-6 py-3 rounded-xl text-sm font-semibold hover:bg-gray-800 transition-colors"
          >
            Continue
            <ChevronRight className="w-4 h-4" />
          </button>
        ) : (
          <button
            type="submit"
            disabled={isSubmitting}
            className="flex-1 flex items-center justify-center gap-2 bg-orange-500 hover:bg-orange-600 disabled:bg-orange-300 text-white px-4 py-3 rounded-xl text-sm font-semibold transition-colors"
          >
            {isSubmitting ? (
              <>
                <Loader2 className="w-4 h-4 animate-spin" />
                Submitting…
              </>
            ) : (
              <>
                Submit Application
                <ChevronRight className="w-4 h-4" />
              </>
            )}
          </button>
        )}
      </div>
    </form>
  );
}