import React, { useEffect, useMemo, useCallback, 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";
import { error } from "pdf-lib";

const ManagePurchase = ({ onClose, purchaseId }) => {
  const { data } = usePurchase(purchaseId);

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

  const stepsConfig = useMemo(
    () => [
      {
        name: "Vendor & Project Details",
        icon: "bx bx-user bx-md",
        subtitle: "Vendor information and project association",
        component: <PurchasePartyDetails purchase={data} />,
      },
      {
        name: "Invoice & Logistics",
        icon: "bx bx-receipt bx-md",
        subtitle: "Invoice, e-Way bill, and logistics information",
        component: <PurchaseTransportDetails />,
      },
      {
        name: "Invoice & Tax Amount",
        icon: "bx bx-credit-card bx-md",
        subtitle: "Payment terms, tax breakdown, and due dates",
        component: <PurchasePaymentDetails purchaseId={purchaseId} />,
      },
    ],
    [data, purchaseId]
  );

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

  const { reset, formState } = purchaseOrder;

  useEffect(() => {
    if (!purchaseId || !data) return;

    reset({
      ...data,
      projectId: data?.project?.id,
      organizationId: data?.organization?.id,
      supplierId: data?.supplier?.id,
      invoiceAttachmentTypeId: null,
      attachments:
        data?.attachments?.map((doc) => ({
          fileName: doc.fileName,
          base64Data: null,
          contentType: doc.contentType,
          documentId: doc.documentId ?? null,
          invoiceAttachmentTypeId: doc.invoiceAttachmentType?.id ?? null,
          fileSize: 0,
          description: "",
          preSignedUrl: doc.preSignedUrl,
          isActive: doc.isActive ?? true,
        })) || [],
    });

    setCompletedTabs([0, 1, 2]);
  }, [purchaseId, data, reset]);

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

    if (!valid) return;

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

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

  const generatePatchOps = useCallback(
    (formData) => {
      const { dirtyFields } = formState;

      return Object.keys(dirtyFields)
        .filter((key) => key !== "invoiceAttachmentTypeId")
        .map((key) => ({
          operationType: 0,
          path: `/${key}`,
          op: "replace",
          value: formData[key],
        }));
    },
    [formState]
  );

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

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

  const onSubmit = useCallback(
    (formData) => {
      if (purchaseId) {
        const payload = generatePatchOps(formData);
        updatePurchase({ purchaseId, payload });
      } else {
        CreateInvoice(formData);
      }
    },
    [purchaseId, generatePatchOps, updatePurchase, CreateInvoice]
  );
 
  return (
    <div className="bs-stepper horizontically mt-2 b-secondry shadow-none border-0">
      {/* --- Steps 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 text-truncate ${isActive ? "active" : ""} ${
                  isCompleted ? "crossed" : ""
                }`}
              >
                <button
                  type="button"
                  className={`step-trigger`}
                  onClick={() => purchaseId && setActiveTab(index)}
                >
                  <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>

      {/* --- Form Content --- */}
      <div className="bs-stepper-content py-2 px-3">
        <AppFormProvider {...purchaseOrder}>
          {activeTab !== 2 && (
            <div>
              {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>

                <button
                  type="button"
                  className="btn btn-sm btn-primary"
                  onClick={handleNext}
                >
                  Next
                </button>
              </div>
            </div>
          )}
          {activeTab === 2 && (
            <form onSubmit={purchaseOrder.handleSubmit(onSubmit)}>
              {stepsConfig[2].component}

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

                <button
                  type="submit"
                  className="btn btn-sm btn-primary"
                  disabled={isPending || isUpdating}
                >
                  {isPending || isUpdating ? "Please Wait" : "Submit"}
                </button>
              </div>
            </form>
          )}
        </AppFormProvider>
      </div>
    </div>
  );
};

export default ManagePurchase;
