import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { Button } from '../components/ui/button';
import { Card } from '../components/ui/card';
import { toast } from 'sonner';
import PublicNavbar from '../components/PublicNavbar';
import PublicFooter from '../components/PublicFooter';
import { ArrowRight, ArrowLeft } from 'lucide-react';
import RegistrationStepIndicator from '../components/registration/RegistrationStepIndicator';
import RegistrationStep1 from '../components/registration/RegistrationStep1';
import RegistrationStep2 from '../components/registration/RegistrationStep2';
import RegistrationStep3 from '../components/registration/RegistrationStep3';
import RegistrationStep4 from '../components/registration/RegistrationStep4';

const Register = () => {
  const navigate = useNavigate();
  const { register } = useAuth();
  const [loading, setLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState({
    // Step 1: Personal & Partner Information
    first_name: '',
    last_name: '',
    phone: '',
    date_of_birth: '',
    address: '',
    city: '',
    state: '',
    zipcode: '',
    lead_sources: [],
    partner_first_name: '',
    partner_last_name: '',
    partner_is_member: false,
    partner_plan_to_become_member: false,

    // Step 2: Newsletter, Volunteer & Scholarship
    referred_by_member_name: '',
    newsletter_publish_name: false,
    newsletter_publish_photo: false,
    newsletter_publish_birthday: false,
    newsletter_publish_none: false,
    volunteer_interests: [],
    scholarship_requested: false,
    scholarship_reason: '',

    // Step 3: Directory Settings
    show_in_directory: false,
    directory_email: '',
    directory_bio: '',
    directory_address: '',
    directory_phone: '',
    directory_dob: '',
    directory_partner_name: '',

    // Step 4: Account Credentials
    email: '',
    password: '',
    confirmPassword: ''
  });

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const validateStep1 = () => {
    const required = ['first_name', 'last_name', 'phone', 'date_of_birth',
      'address', 'city', 'state', 'zipcode'];
    for (const field of required) {
      if (!formData[field]?.trim()) {
        toast.error('Please fill in all required fields');
        return false;
      }
    }
    if (formData.lead_sources.length === 0) {
      toast.error('Please select at least one option for how you heard about us');
      return false;
    }
    return true;
  };

  const validateStep2 = () => {
    const { newsletter_publish_name, newsletter_publish_photo,
      newsletter_publish_birthday, newsletter_publish_none } = formData;

    if (!newsletter_publish_name && !newsletter_publish_photo &&
      !newsletter_publish_birthday && !newsletter_publish_none) {
      toast.error('Please select at least one newsletter publication preference');
      return false;
    }

    if (formData.scholarship_requested && !formData.scholarship_reason?.trim()) {
      toast.error('Please explain your scholarship request');
      return false;
    }

    return true;
  };

  const validateStep3 = () => {
    return true; // No required fields
  };

  const validateStep4 = () => {
    if (!formData.email || !formData.password || !formData.confirmPassword) {
      toast.error('Please fill in all account fields');
      return false;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(formData.email)) {
      toast.error('Please enter a valid email address');
      return false;
    }

    if (formData.password.length < 6) {
      toast.error('Password must be at least 6 characters');
      return false;
    }

    if (formData.password !== formData.confirmPassword) {
      toast.error('Passwords do not match');
      return false;
    }

    return true;
  };

  const handleNext = () => {
    let isValid = false;

    switch (currentStep) {
      case 1: isValid = validateStep1(); break;
      case 2: isValid = validateStep2(); break;
      case 3: isValid = validateStep3(); break;
      default: isValid = false;
    }

    if (isValid) {
      setCurrentStep(prev => Math.min(prev + 1, 4));
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const handleBack = () => {
    setCurrentStep(prev => Math.max(prev - 1, 1));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    // Final validation
    if (!validateStep4()) return;

    setLoading(true);

    try {
      // Remove confirmPassword (client-side only)
      const { confirmPassword, ...dataToSubmit } = formData;

      // Convert date fields to ISO format
      const submitData = {
        ...dataToSubmit,
        date_of_birth: new Date(dataToSubmit.date_of_birth).toISOString(),
        directory_dob: dataToSubmit.directory_dob
          ? new Date(dataToSubmit.directory_dob).toISOString()
          : null
      };

      await register(submitData);
      toast.success('Please check your email for a confirmation email.');
      navigate('/login');
    } catch (error) {
      toast.error(error.response?.data?.detail || 'Registration failed. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-white">
      <PublicNavbar />

      <div className="max-w-4xl mx-auto px-6 py-12">
        <div className="mb-8">
          <Link to="/" className="inline-flex items-center text-[#664fa3] hover:text-[#ff9e77] transition-colors">
            <ArrowLeft className="h-4 w-4 mr-2" />
            Back to Home
          </Link>
        </div>

        <Card className="p-8 md:p-12 bg-white rounded-2xl border border-[#ddd8eb] shadow-lg">
          <div className="mb-8">
            <h1 className="text-4xl md:text-5xl font-semibold text-[#422268] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
              Join Our Community
            </h1>
            <p className="text-lg text-[#664fa3]" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Fill out the form below to start your membership journey.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-8" data-testid="register-form">
            <RegistrationStepIndicator currentStep={currentStep} />

            {currentStep === 1 && (
              <RegistrationStep1
                formData={formData}
                setFormData={setFormData}
                handleInputChange={handleInputChange}
              />
            )}

            {currentStep === 2 && (
              <RegistrationStep2
                formData={formData}
                setFormData={setFormData}
                handleInputChange={handleInputChange}
              />
            )}

            {currentStep === 3 && (
              <RegistrationStep3
                formData={formData}
                setFormData={setFormData}
                handleInputChange={handleInputChange}
              />
            )}

            {currentStep === 4 && (
              <RegistrationStep4
                formData={formData}
                handleInputChange={handleInputChange}
              />
            )}

            {/* Navigation Buttons */}
            <div className="flex justify-between items-center pt-6">
              {currentStep > 1 ? (
                <Button
                  type="button"
                  onClick={handleBack}
                  variant="outline"
                  className="rounded-full px-6 py-6 text-lg border-2 border-[#ddd8eb] hover:border-[#664fa3] text-[#422268]"
                >
                  <ArrowLeft className="mr-2 h-5 w-5" />
                  Back
                </Button>
              ) : (
                <div></div>
              )}

              {currentStep < 4 ? (
                <Button
                  type="button"
                  onClick={handleNext}
                  className="bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full px-6 py-6 text-lg font-medium shadow-lg hover:scale-105 transition-transform"
                >
                  Next
                  <ArrowRight className="ml-2 h-5 w-5" />
                </Button>
              ) : (
                <Button
                  type="submit"
                  disabled={loading}
                  className="bg-[#DDD8EB] text-[#422268] hover:bg-white rounded-full px-6 py-6 text-lg font-medium shadow-lg hover:scale-105 transition-transform disabled:opacity-50 disabled:cursor-not-allowed"
                  data-testid="submit-register-button"
                >
                  {loading ? 'Creating Account...' : 'Create Account'}
                  <ArrowRight className="ml-2 h-5 w-5" />
                </Button>
              )}
            </div>

            <p className="text-center text-[#664fa3] mt-4" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Already have an account?{' '}
              <Link to="/login" className="text-[#ff9e77] hover:underline font-medium">
                Login here
              </Link>
            </p>
          </form>
        </Card>
      </div>

      <PublicFooter />
    </div>
  );
};

export default Register;
