import React, { useState,useEffect } from "react";
import { ChevronLeft } from "lucide-react";
import { useDispatch, useSelector } from "react-redux";
import {
  updatePersonalDetails,
  updateEducationalDetails,
  updateFamilyDetails,
  updateLifestyleDetails,
  updatePartnerPreferences,
  submitForm,
} from "../redux/registrationFormSlice";
import PersonalDetailsForm from "./PersonalDetailsForm";
import EducationalDetailsForm from "./EducationalDetailsForm";
import FamilyDetailsForm from "./FamilyDetailsForm";
import LifestyleDetailsForm from "./LifestyleDetailsForm";
import PartnerPreferencesForm from "./PartnerPreferencesForm";
import PreviewScreen from "./PreviewScreen";
import { useLocation } from "react-router-dom";
const Stepper = ({ currentStep, onStepClick }) => {
  

  const steps = [
    { num: 1, label: "Personal" },
    { num: 2, label: "Educational" },
    { num: 3, label: "Family" },
    { num: 4, label: "Lifestyle" },
    { num: 5, label: "Partner" },
    { num: 6, label: "Preview" },
  ];

  return (
    <div className="flex items-center justify-between px-4 py-6">
      {steps.map((step, index) => (
        <React.Fragment key={step.num}>
          <div
            className="flex flex-col items-center cursor-pointer"
            onClick={() => onStepClick(step.num)}
          >
            <div
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold ${
                currentStep >= step.num
                  ? "bg-red-600 text-white"
                  : "bg-gray-300 text-gray-600"
              }`}
            >
              {step.num}
            </div>
          </div>
          {index < steps.length - 1 && (
            <div
              className={`flex-1 h-0.5 mx-1 ${
                currentStep > step.num ? "bg-red-600" : "bg-gray-300"
              }`}
            />
          )}
        </React.Fragment>
      ))}
    </div>
  );
};

const StepperForm = () => {
  const dispatch = useDispatch();
 const location = useLocation();

  const personalDetails = useSelector(
    (state) => state.registerform.personalDetails
  );
  const educationalDetails = useSelector(
    (state) => state.registerform.educationalDetails
  );
  const familyDetails = useSelector((state) => state.registerform.familyDetails);
  const lifestyleDetails = useSelector(
    (state) => state.registerform.lifestyleDetails
  );
  const partnerPreferences = useSelector(
    (state) => state.registerform.partnerPreferences
  );

  const initialStep = location.state?.step || 1;

  const [currentStep, setCurrentStep] = useState(initialStep);
  const [errors, setErrors] = useState({});



   useEffect(() => {
    // in case user comes again with a different step
    if (location.state?.step) {
      setCurrentStep(location.state.step);
      window.scrollTo(0, 0);
    }
  }, [location.state?.step]);




  const validateStep = (step) => {
    const newErrors = {};

    if (step === 1) {
      const required = [
        "name",
        "mobileNumber",
        "gender",
        "dob",
        "height",
        "weight",
        "maritalStatus",
        "religion",
        "caste",
        "email",
        "state",
        "city",
        "pincode",
      ];

      required.forEach((field) => {
        if (!personalDetails[field]) {
          newErrors[field] = "This field is required";
        }
      });

      if (
        personalDetails.email &&
        !/\S+@\S+\.\S+/.test(personalDetails.email)
      ) {
        newErrors.email = "Invalid email format";
      }
      if (
        personalDetails.mobileNumber &&
        personalDetails.mobileNumber.length !== 10
      ) {
        newErrors.mobileNumber = "Mobile number must be 10 digits";
      }
    } else if (step === 2) {
      const required = [
        "qualification",
        "fieldOfStudy",
        "occupation",
        "organization",
        "income",
        "workLocation",
      ];
      required.forEach((field) => {
        if (!educationalDetails[field]) {
          newErrors[field] = "This field is required";
        }
      });
    } else if (step === 3) {
      const required = [
        "fatherName",
        "fatherOccupation",
        "motherName",
        "motherOccupation",
        "siblings",
        "siblingsStatus",
       
      ];
      required.forEach((field) => {
        if (!familyDetails[field]) {
          newErrors[field] = "This field is required";
        }
      });
    } else if (step === 4) {
      const required = ["diet", "drinking", "smoking", "hobbies"];
      required.forEach((field) => {
        if (!lifestyleDetails[field]) {
          newErrors[field] = "This field is required";
        }
      });
    } else if (step === 5) {
      const required = [
        "ageRange",
        "religionCaste",
        "occupationPref",
        "lifestylePref",
        "qualificationPref",
        "occupationText",
        "incomePref",
        "locationPref",
      ];
      required.forEach((field) => {
        if (!partnerPreferences[field]) {
          newErrors[field] = "This field is required";
        }
      });
    }

    setErrors(newErrors);

    // Autofocus first invalid field
    if (Object.keys(newErrors).length > 0) {
      const firstKey = Object.keys(newErrors)[0];
      const el = document.querySelector(`[name="${firstKey}"]`);
      if (el) el.focus();
    }

    return Object.keys(newErrors).length === 0;
  };

  // API call simulation for each step submit
  const submitStepAPI = async (step) => {
    // Replace with actual API call
    return new Promise((resolve) => setTimeout(resolve, 500));
  };

  const handleStepSubmit = async () => {
    const isValid = validateStep(currentStep);
    if (!isValid) return;

    try {
      await submitStepAPI(currentStep);
      setCurrentStep((prev) => Math.min(prev + 1, 6));
      window.scrollTo(0, 0);
    } catch (e) {
      alert("Failed to submit step. Please try again.");
    }
  };

  const handleSkip = () => {
    setErrors({});
    setCurrentStep((prev) => Math.min(prev + 1, 6));
    window.scrollTo(0, 0);
  };

  const handleStepClick = (step) => {
    setCurrentStep(step);
    setErrors({});
    window.scrollTo(0, 0);
  };

  const handleEdit = (step) => {
    setCurrentStep(step);
    setErrors({});
    window.scrollTo(0, 0);
  };

  const handleFinalSubmit = async () => {
    for (let i = 1; i <= 5; i++) {
      const ok = validateStep(i);
      if (!ok) {
        setCurrentStep(i);
        return;
      }
    }

    try {
      // final combined API call - replace with your final API
      await new Promise((resolve) => setTimeout(resolve, 500));
      alert("Form submitted successfully!");
    } catch (e) {
      alert("Failed to submit form.");
    }
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 1:
        return (
          <PersonalDetailsForm
            onSubmitStep={handleStepSubmit}
            onSkipStep={handleSkip}
            errors={errors}
          />
        );
      case 2:
        return (
          <EducationalDetailsForm
            onSubmitStep={handleStepSubmit}
            onSkipStep={handleSkip}
            errors={errors}
          />
        );
      case 3:
        return (
          <FamilyDetailsForm
            onSubmitStep={handleStepSubmit}
            onSkipStep={handleSkip}
            errors={errors}
          />
        );
      case 4:
        return (
          <LifestyleDetailsForm
            onSubmitStep={handleStepSubmit}
            onSkipStep={handleSkip}
            errors={errors}
          />
        );
      case 5:
        return (
          <PartnerPreferencesForm
            onSubmitStep={handleStepSubmit}
            onSkipStep={handleSkip}
            errors={errors}
          />
        );
      case 6:
        return <PreviewScreen onEdit={handleEdit} onSubmit={handleFinalSubmit} />;
      default:
        return null;
    }
  };

  const getTitle = () => {
    const titles = {
      1: "Personal Details",
      2: "Educational & Professional Details",
      3: "Family Details",
      4: "Lifestyle & Habits",
      5: "Partner Preferences",
      6: "Details Preview",
    };
    return titles[currentStep] || "";
  };

  return (
    <div className="">
      <div className="max-w-[1400px] mx-auto bg-white  ">
        {/* Header */}
        <div className="my-4 rounded-[10px] py-4  bg-[#e3ffed]  w-full max-w-[1200px] mx-auto">

            <Stepper currentStep={currentStep} onStepClick={handleStepClick} />
          <div className="flex items-center p-4 justify-center">
            {currentStep > 1 && currentStep < 6 && (
              <button
                onClick={() => setCurrentStep((prev) => prev - 1)}
                className="mr-3"
              >
                <ChevronLeft size={24} />
              </button>
            )}
            <h1 className="text-[24px] font-semibold text-center uppercase bg-[#fff2f2] py-2 px-3 rounded-5">{getTitle()}</h1>
          </div>
        
        </div>

        {/* Content */}
        <div className="pb-6">{renderStepContent()}</div>
      </div>
    </div>
  );
};

export default StepperForm;
