import React, { useEffect, 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";
import {
  useCreatePurchaseInvoice,
  usePurchase,
  useUpdatePurchaseInvoice,
} from "../../hooks/usePurchase";
const ManagePurchase = ({ onClose, purchaseId }) => {
  const { data } = usePurchase(purchaseId);
  const [activeTab, setActiveTab] = useState(0);
  const [completedTabs, setCompletedTabs] = useState([]);

  const stepsConfig = [
    {
      name: "Party Details",
      icon: "bx bx-user bx-md",
      subtitle: "Supplier & project information",
      component: <PurchasePartyDetails purchase={data} />,
    },
    {
      name: "Invoice & Transport",
      icon: "bx bx-receipt bx-md",
      subtitle: "Invoice, eWay bill & transport info",
      component: <PurchaseTransportDetails />,
    },
    {
      name: "Payment Details",
      icon: "bx bx-credit-card bx-md",
      subtitle: "Amount, tax & due date",
      component: <PurchasePaymentDetails />,
    },
  ];

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

  const {
    reset,
    formState: { errors },
  } = purchaseOrder;

  useEffect(() => {
    if (purchaseId && data) {
      reset({
        ...data,
        title: data.title,
        projectId: data.project.id,
        organizationId: data.organization.id,
        supplierId: data.supplier.id,
      });
      setCompletedTabs([0, 1, 2]);
    }
  }, [purchaseId, data, reset]);

  const handleNext = async (e) => {
    e.preventDefault();
    e.stopPropagation();

    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 = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setActiveTab((prev) => Math.max(prev - 1, 0));
  };

  const { mutate: CreateInvoice, isPending } = useCreatePurchaseInvoice(() => {
    reset();
    onClose();
  });

  const { mutate: updatePurchase, isPending: isUpdating } =
    useUpdatePurchaseInvoice(() => {
      reset();
      onClose();
    });

  const onSubmit = (formData) => {
    if (activeTab !== 2) {
      console.warn("Submit blocked - not on last step");
      return;
    }

    const dirtyFields = purchaseOrder.formState.dirtyFields;

    if (purchaseId) {
      const changedData = Object.keys(dirtyFields).reduce((acc, key) => {
        if (dirtyFields[key]) {
          acc.push({
            operationType: 0,
            path: `/${key}`,
            op: "replace",
            from: null,
            value: formData[key],
          });
        }
        return acc;
      }, []);

      updatePurchase({
        purchaseId,
        payload: changedData,
      });
    } else {
      CreateInvoice(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
            onKeyDown={(e) => {
              if (e.key === "Enter" && activeTab !== 2) {
                e.preventDefault();
              }
            }}
            onSubmit={(e) => {
              e.preventDefault();

              if (activeTab !== 2) {
                console.warn("BLOCKED SUBMIT on step:", activeTab);
                return;
              }

              purchaseOrder.handleSubmit(onSubmit)(e);
            }}
          >
            {stepsConfig[activeTab].component}

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

              <div>
                {activeTab < stepsConfig.length - 1 ? (
                  <button
                    type="button"
                    className="btn btn-sm btn-primary"
                    onClick={handleNext}
                    disabled={isPending || isUpdating}
                  >
                    Next <i className="bx bx-sm bx-right-arrow"></i>
                  </button>
                ) : (
                  <button
                    type="submit"
                    className="btn btn-sm btn-primary"
                    disabled={isPending || isUpdating}
                  >
                    {isPending || isUpdating ? "Please Wait" : "Submit"}
                  </button>
                )}
              </div>
            </div>
          </form>
        </AppFormProvider>
      </div>
    </div>
  );
};

export default ManagePurchase;
