import React, { useState } from "react";
import { AppFormProvider, useAppForm } from "../../hooks/appHooks/useAppForm";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  defaultPurchaseValue,
  PurchaseSchema,
  getStepFields,
} from "./PurchaseSchema";
import PurchasePartyDetails from "./PurchasePartyDetails";
import PurchaseTransportDetails from "./PurchaseTransportDetails";
import PurchasePaymentDetails from "./PurchasePaymentDetails";

const ManagePurchase = () => {
  const [activeTab, setActiveTab] = useState(0);
  const [completedTabs, setCompletedTabs] = useState([]);

  const stepsConfig = [
    {
      name: "Contact Info",
      icon: "bx bx-user bx-md",
      subtitle: "Provide Contact Details",
      component: <PurchasePartyDetails />,
    },
    {
      name: "Organization",
      icon: "bx bx-buildings bx-md",
      subtitle: "Organization Details",
      component: <PurchaseTransportDetails/>,
    },
    {
      name: "Subscription",
      icon: "bx bx-star bx-md",
      subtitle: "Payment & Financials",
      component: <PurchasePaymentDetails/>,
    },
  ];

  const purchaseOrder = useAppForm({
    resolver: zodResolver(PurchaseSchema),
    defaultValues: defaultPurchaseValue,
    mode: "onChange",
  });

  const handleNext = async () => {
    const currentStepFields = getStepFields(activeTab);
    const valid = await purchaseOrder.trigger(currentStepFields);

    if (valid) {
      setCompletedTabs((prev) => [...new Set([...prev, activeTab])]);
      setActiveTab((prev) => Math.min(prev + 1, stepsConfig.length - 1));
    }
  };

  const handlePrev = () => {
    setActiveTab((prev) => Math.max(prev - 1, 0));
  };

  const onSubmit = (formData) => {
    console.log("PURCHASE DATA:", formData);
  };

  return (
    <div
      id="wizard-property-listing"
      className="bs-stepper horizontically mt-2 b-secondry px-1 py-1 shadow-none border-0"
    >
      {/* Header */}
      <div className="bs-stepper-header text-start px-0 py-1">
        {stepsConfig.map((step, index) => {
          const isActive = activeTab === index;
          const isCompleted = completedTabs.includes(index);

          return (
            <React.Fragment key={step.name}>
              <div
                className={`step ${isActive ? "active" : ""} ${
                  isCompleted ? "crossed" : ""
                }`}
              >
                <button type="button" className="step-trigger">
                  <span className="bs-stepper-circle">
                    {isCompleted ? (
                      <i className="bx bx-check"></i>
                    ) : (
                      <i className={step.icon}></i>
                    )}
                  </span>

                  <span className="bs-stepper-label">
                    <span className="bs-stepper-title">{step.name}</span>
                    <span className="bs-stepper-subtitle">
                      {step.subtitle}
                    </span>
                  </span>
                </button>
              </div>

              {index < stepsConfig.length - 1 && (
                <div className="line text-primary"></div>
              )}
            </React.Fragment>
          );
        })}
      </div>

      {/* Content */}
      <div className="bs-stepper-content py-2">
        <AppFormProvider {...purchaseOrder}>
          <form onSubmit={purchaseOrder.handleSubmit(onSubmit)}>
            {stepsConfig[activeTab].component}

            <div className="d-flex justify-content-between mt-4">
              <button
                type="button"
                className="btn btn-outline-secondary"
                onClick={handlePrev}
                disabled={activeTab === 0}
              >
                Previous
              </button>

              {activeTab < stepsConfig.length - 1 ? (
                <button
                  type="button"
                  className="btn btn-sm btn-primary"
                  onClick={handleNext}
                >
                  Next
                </button>
              ) : (
                <button type="submit" className="btn btn-sm btn-primary">
                  Submit
                </button>
              )}
            </div>
          </form>
        </AppFormProvider>
      </div>
    </div>
  );
};

export default ManagePurchase;
