import React, { useState } from "react";
import GlobalModel from "../../components/common/GlobalModel";
import Stepper from "./Stepper";
import SupplierInfoStep from "./SupplierInfoStep";
import BankStep from "./BankStep";
import AddressStep from "./AddressStep";

const AddProductModal = ({ isOpen, onClose }) => {
  const steps = [
    { key: "supplierInfo", label: "Supplier Info" },
    { key: "bank", label: "Bank" },
    { key: "address", label: "Address" },
  ];

  const [activeStepIndex, setActiveStepIndex] = useState(0);
  const activeStepKey = steps[activeStepIndex].key;

  if (!isOpen) return null;

  const handleNext = () => {
    if (activeStepIndex < steps.length - 1) setActiveStepIndex(activeStepIndex + 1);
    else handleSubmit();
  };

  const handleBack = () => {
    if (activeStepIndex > 0) setActiveStepIndex(activeStepIndex - 1);
  };

  const handleSubmit = () => {
    console.log("Form submitted");
    onClose();
  };

  return (
    <GlobalModel isOpen size="xl" closeModal={onClose}>
      <div className="p-4">
        <h5 className="mb-4">Add New Supplier</h5>

        <Stepper steps={steps} activeStep={activeStepIndex} />

        <form onSubmit={(e) => e.preventDefault()}>
          {activeStepKey === "supplierInfo" && <SupplierInfoStep />}
          {activeStepKey === "bank" && <BankStep />}
          {activeStepKey === "address" && <AddressStep />}

          <div className="d-flex justify-content-between mt-5 border-top pt-3">
            <button
              type="button"
              className="btn btn-label-secondary btn-sm"
              onClick={activeStepIndex > 0 ? handleBack : onClose}
            >
              {activeStepIndex > 0 ? "← Back" : "Cancel"}
            </button>

            <div>
              {activeStepIndex < steps.length - 1 ? (
                <button type="button" className="btn btn-primary btn-sm" onClick={handleNext}>
                  Next →
                </button>
              ) : (
                <button type="button" className="btn btn-primary btn-sm" onClick={handleSubmit}>
                  Submit
                </button>
              )}
            </div>
          </div>
        </form>
      </div>
    </GlobalModel>
  );
};

export default AddProductModal;
