import React, { useState, useRef, useEffect, useContext } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import {
  CardElement,
  Elements,
  useStripe,
  useElements,
} from "@stripe/react-stripe-js";
import SignaturePad from "react-signature-pad-wrapper";
import MkdSDK from "Utils/MkdSDK";
import { showToast } from "Context/Global";
import {
  uploadFilesAPI,
  uploadS3FilesAPI,
} from "Src/services/workOrderService";
import { ClipLoader } from "react-spinners";
import { GlobalContext } from "Src/globalContext";

export const STEPS = {
  CLIENT_DETAILS: 1,
  REVIEW_SIGN: 2,
  PAYMENT: 3,
};

const schema = yup.object().shape({
  firstName: yup.string().required("First name is required"),
  lastName: yup.string().required("Last name is required"),
  email: yup.string().email("Invalid email").required("Email is required"),
  phone: yup.string().required("Phone number is required"),
  position: yup.string().required("Position is required"),
  program: yup.string().required("Program is required"),
  notes: yup.string(),
});

const InvoiceMultiStep = ({
  invoiceData,
  onSubmit,
  termsContent,
  serviceAgreementContent,
  token,
  clientData,
  step2Info,
  setStep2Info,
}) => {
  const { dispatch: globalDispatch } = useContext(GlobalContext);
  console.log("Step 2 Info:", step2Info);
  console.log("Invoice Data:", invoiceData);
  console.log("Client Data:", clientData);
  const [currentStep, setCurrentStep] = useState(STEPS.CLIENT_DETAILS);
  const [signature, setSignature] = useState(step2Info?.signature);
  console.log("Signature:", signature);
  const [initial, setInitial] = useState(
    step2Info?.initial || invoiceData?.invoice?.initials || ""
  );
  const [feedback, setFeedback] = useState(
    step2Info?.feedback_notes || invoiceData?.invoice?.feedback_notes || ""
  );
  const [paymentType, setPaymentType] = useState("deposit");
  const [paymentAmount, setPaymentAmount] = useState(0);
  const [selectedItems, setSelectedItems] = useState([]);
  const [paymentMethodId, setPaymentMethodId] = useState(null);
  const [paymentError, setPaymentError] = useState(null);
  const [paymentNotes, setPaymentNotes] = useState("");
  const signaturePadRef = useRef(null);
  const initialsPadRef = useRef(null);
  const stripe = useStripe();
  const elements = useElements();
  console.log(selectedItems);
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm({
    resolver: yupResolver(schema),
    defaultValues: {
      firstName: invoiceData?.invoice?.client_name?.split(" ")[0] || "",
      lastName: invoiceData?.invoice?.client_name?.split(" ")[1] || "",
      email: invoiceData?.invoice?.client_email || clientData?.email || "",
      programName: invoiceData?.invoice?.program || clientData?.program || "",
      phone: invoiceData?.invoice?.created_by_phone || clientData?.phone || "",
      position: clientData?.position || "",
      program: clientData?.program || "",
      notes: invoiceData?.invoice?.notes || "",
    },
  });

  // Update form values when clientData changes
  useEffect(() => {
    if (clientData) {
      setValue("email", clientData.email || "");
      setValue("phone", clientData.phone || "");
      setValue("position", clientData.position || "");
      setValue("program", clientData.program || "");
      const [firstName, ...lastNameParts] = (clientData.name || "").split(" ");
      setValue("firstName", firstName || "");
      setValue("lastName", lastNameParts.join(" ") || "");
    }
  }, [clientData, setValue]);

  // Update signature pad with existing signature if available
  useEffect(() => {
    if (signaturePadRef.current && invoiceData?.invoice?.signature) {
      const img = new Image();
      img.onload = () => {
        const canvas = signaturePadRef.current._canvas;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
      };
      img.src = `https://equalityrecords.s3.amazonaws.com/${invoiceData.invoice.signature}`;
    }
  }, [invoiceData?.invoice?.signature]);

  // Add function to handle item selection
  const handleItemSelection = (itemId, selected) => {
    if (selected) {
      setSelectedItems([...selectedItems, itemId]);
    } else {
      setSelectedItems(selectedItems.filter((id) => id !== itemId));
    }
  };

  // Update Payment Amount Display
  useEffect(() => {
    const totalPaymentAmount = selectedItems.reduce((sum, itemId) => {
      const item = invoiceData.items.find((item) => item.id === itemId);
      const successfulPayments = invoiceData.payments.filter(
        (p) => p.invoice_item_id === item.id && p.status === "succeeded"
      );
      const totalPaidAmount = successfulPayments.reduce(
        (sum, payment) => sum + parseFloat(payment.amount),
        0
      );
      const remainingAmount = parseFloat(item.total) - totalPaidAmount;
      const depositAmount =
        (parseFloat(item.total) *
          parseFloat(invoiceData.invoice.deposit_percentage)) /
        100;
      const amountToPay =
        paymentType === "deposit"
          ? Math.max(depositAmount - totalPaidAmount, 0)
          : remainingAmount;
      return sum + amountToPay;
    }, 0);
    setPaymentAmount(totalPaymentAmount);
  }, [selectedItems, paymentType, invoiceData]);

  const updateStepCompletion = async (step, data) => {
    try {
      const sdk = new MkdSDK();

      if (step === STEPS.REVIEW_SIGN) {
        // For step 2, we need to send specific fields
        const payload = {
          initials: data.initial,
          signature: data?.signature || step2Info?.signature,
          feedback_notes: data.feedback,
        };

        const response = await sdk.callRawAPI(
          `/v3/api/custom/equality_record/subscription/public/invoice/${invoiceData?.invoice?.id}/${token}`,
          payload,
          "PUT"
        );

        if (response.error) {
          throw new Error(
            response.message || "Failed to update signature details"
          );
        }
        setStep2Info((prev) => ({
          ...prev,
          feedback_notes: response.invoice.feedback_notes,
          signature: response.invoice.signature,
          initial: response.invoice.initials,
        }));
      } else {
      }
    } catch (error) {
      console.error("Failed to update step completion:", error);
      showToast(
        globalDispatch,
        error.message || "Failed to update",
        4000,
        "error"
      );
    }
  };

  const clearSignature = () => {
    if (signaturePadRef.current) {
      signaturePadRef.current.clear();
    }
  };

  const clearInitials = () => {
    if (initialsPadRef.current) {
      initialsPadRef.current.clear();
    }
  };

  const saveSignature = async () => {
    try {
      if (signaturePadRef.current && !signaturePadRef.current.isEmpty()) {
        const signatureDataUrl = signaturePadRef.current.toDataURL();

        // Convert data URL to blob
        const signatureBlob = await fetch(signatureDataUrl).then((r) =>
          r.blob()
        );

        // Create form data and upload
        const formData = new FormData();
        formData.append("files", signatureBlob, "signature.png");

        const uploadResult = await uploadS3FilesAPI(formData);

        if (!uploadResult.error) {
          // Parse the attachments field to extract the URL
          const attachments = JSON.parse(uploadResult.attachments);
          const signatureUrl = attachments[0];
          setSignature(signatureUrl);
          return signatureUrl; // Return the uploaded signature URL
        } else {
          throw new Error("Failed to upload signature");
        }
      }
      return null;
    } catch (error) {
      console.error("Error saving signature:", error);
      showToast(globalDispatch, "Failed to save signature", 4000, "error");
      return null;
    }
  };

  const validateSignatureStep = () => {
    if (!initial) {
      showToast(globalDispatch, "Please enter your initials", 4000, "error");
      return false;
    }

    if (signaturePadRef.current?.isEmpty()) {
      showToast(globalDispatch, "Please provide your signature", 4000, "error");
      return false;
    }

    return true;
  };

  const handleInitialsChange = (type, value) => {
    setInitial(value);
  };

  const handleCardPayment = async () => {
    if (!stripe || !elements) {
      setPaymentError("Stripe has not been initialized");
      return null;
    }

    const cardElement = elements.getElement(CardElement);
    if (!cardElement) {
      setPaymentError("Card element not found");
      return null;
    }

    try {
      const { error, paymentMethod } = await stripe.createPaymentMethod({
        type: "card",
        card: cardElement,
      });

      if (error) {
        setPaymentError(error.message);
        return null;
      }

      setPaymentMethodId(paymentMethod.id);
      setPaymentError(null);
      return paymentMethod.id;
    } catch (err) {
      setPaymentError("Failed to process card. Please try again.");
      return null;
    }
  };

  const renderStep = () => {
    switch (currentStep) {
      case STEPS.CLIENT_DETAILS:
        return (
          <div className="rounded-lg border border-strokedark bg-boxdark p-6">
            {/* Company Information */}
            <div className="mb-8 rounded border border-stroke bg-meta-4 p-6">
              <div className="flex items-center gap-6">
                <div className="h-20 w-20 overflow-hidden rounded-lg border border-stroke">
                  <img
                    src={
                      invoiceData?.invoice?.created_by_company_logo ||
                      "/placeholder-logo.png"
                    }
                    alt="Company Logo"
                    className="h-full w-full object-contain"
                  />
                </div>
                <div>
                  <h2 className="text-2xl font-bold text-white">
                    {invoiceData?.invoice?.created_by_company_name ||
                      "Company Name"}
                  </h2>
                  <p className="text-bodydark">
                    {invoiceData?.invoice?.created_by_first_name}{" "}
                    {invoiceData?.invoice?.created_by_last_name}
                  </p>
                </div>
              </div>
            </div>

            <h2 className="mb-6 text-2xl font-semibold text-white">
              Client Information
            </h2>

            {/* Client Details Form */}
            <form className="grid grid-cols-1 gap-6 md:grid-cols-2">
              <div>
                <label className="mb-2.5 block font-medium text-white">
                  First Name
                </label>
                <input
                  {...register("firstName")}
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Enter first name"
                />
                {errors.firstName && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.firstName.message}
                  </p>
                )}
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Last Name
                </label>
                <input
                  {...register("lastName")}
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Enter last name"
                />
                {errors.lastName && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.lastName.message}
                  </p>
                )}
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Email
                </label>
                <input
                  {...register("email")}
                  type="email"
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Enter email address"
                />
                {errors.email && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.email.message}
                  </p>
                )}
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Phone
                </label>
                <input
                  {...register("phone")}
                  type="tel"
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Enter phone number"
                />
                {errors.phone && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.phone.message}
                  </p>
                )}
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Position
                </label>
                <input
                  {...register("position")}
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Enter position"
                />
                {errors.position && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.position.message}
                  </p>
                )}
              </div>

              <div>
                <label className="mb-2.5 block font-medium text-white">
                  Program
                </label>
                <input
                  {...register("program")}
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Enter program"
                />
                {errors.program && (
                  <p className="mt-1 text-xs text-danger">
                    {errors.program.message}
                  </p>
                )}
              </div>

              {/* Invoice Items */}
              <div className="col-span-2 mt-8">
                <h3 className="mb-4 text-xl font-semibold text-white">
                  Invoice Items
                </h3>
                <div className="overflow-x-auto">
                  <table className="w-full table-auto">
                    <thead className="bg-meta-4">
                      <tr>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Description
                        </th>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Mix Date
                        </th>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Team Name
                        </th>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Division
                        </th>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Survey Due
                        </th>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Submission Due
                        </th>
                        <th className="px-4 py-3 text-left text-sm font-medium text-white">
                          Est. Completion
                        </th>
                        <th className="px-4 py-3 text-right text-sm font-medium text-white">
                          Amount
                        </th>
                      </tr>
                    </thead>
                    <tbody>
                      {invoiceData?.items?.map((item, index) => (
                        <tr key={index} className="border-b border-stroke/50">
                          <td className="px-4 py-3 text-white">
                            {item.description}
                          </td>
                          <td className="px-4 py-3 text-white">
                            {new Date(item.mix_date).toLocaleDateString()}
                          </td>
                          <td className="px-4 py-3 text-white">
                            {item.team_name}
                          </td>
                          <td className="px-4 py-3 text-white">
                            {item.division}
                          </td>
                          <td className="px-4 py-3 text-white">
                            {new Date(
                              item.music_survey_due
                            ).toLocaleDateString()}
                          </td>
                          <td className="px-4 py-3 text-white">
                            {new Date(
                              item.routine_submission_due
                            ).toLocaleDateString()}
                          </td>
                          <td className="px-4 py-3 text-white">
                            {new Date(
                              item.estimated_completion
                            ).toLocaleDateString()}
                          </td>
                          <td className="px-4 py-3 text-right text-white">
                            ${parseFloat(item.total).toFixed(2)}
                          </td>
                        </tr>
                      ))}
                    </tbody>
                    <tfoot className="bg-meta-4">
                      <tr>
                        <td
                          colSpan="7"
                          className="px-4 py-3 text-right font-medium text-white"
                        >
                          Subtotal:
                        </td>
                        <td className="px-4 py-3 text-right font-medium text-white">
                          $
                          {parseFloat(
                            invoiceData?.invoice?.subtotal || 0
                          ).toFixed(2)}
                        </td>
                      </tr>
                      <tr>
                        <td
                          colSpan="7"
                          className="px-4 py-3 text-right font-medium text-white"
                        >
                          Deposit Required (
                          {invoiceData?.invoice?.deposit_percentage}%):
                        </td>
                        <td className="px-4 py-3 text-right font-medium text-white">
                          $
                          {parseFloat(
                            invoiceData?.invoice?.deposit_amount || 0
                          ).toFixed(2)}
                        </td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </div>

              <div className="col-span-2">
                <label className="mb-2.5 block font-medium text-white">
                  Producer Notes
                </label>
                <textarea
                  readOnly
                  {...register("notes")}
                  className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                  placeholder="Producer Notes"
                  rows={4}
                />
              </div>
            </form>

            <div className="col-span-2 mt-6 flex justify-end">
              <button
                onClick={async () => {
                  const formData = watch();
                  // Update client details before moving to next step
                  console.log(formData);
                  if (invoiceData?.invoice?.client_id) {
                    const clientUpdateData = {
                      first_name: formData.firstName,
                      last_name: formData.lastName,
                      email: formData.email,
                      phone: formData.phone,
                      position: formData.position,
                      program: formData.program,
                    };
                    await onSubmit({
                      clientDetails: clientUpdateData,
                      step: STEPS.CLIENT_DETAILS,
                    });
                  }
                  await updateStepCompletion(STEPS.CLIENT_DETAILS, formData);
                  setCurrentStep(STEPS.REVIEW_SIGN);
                }}
                className="rounded-md bg-primary px-6 py-2 text-white hover:bg-opacity-90"
              >
                Next: Review & Sign
              </button>
            </div>
          </div>
        );

      case STEPS.REVIEW_SIGN:
        return (
          <div className="rounded-lg border border-strokedark bg-boxdark p-6">
            <h2 className="mb-6 text-2xl font-semibold text-white">
              Review & Sign Documents
            </h2>

            {/* Feedback Section */}
            <div className="mb-8">
              <h3 className="mb-4 text-lg font-medium text-white">
                Feedback & Notes
              </h3>
              <textarea
                value={feedback}
                onChange={(e) => setFeedback(e.target.value)}
                className="w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 text-white outline-none transition focus:border-primary active:border-primary"
                placeholder="Any feedback or notes about the invoice"
                rows={4}
              />
            </div>

            {/* Service Agreement */}
            <div className="mb-8">
              <h3 className="mb-4 text-lg font-medium text-white">
                Service Agreement
              </h3>
              <div className="mb-4 max-h-60 overflow-y-auto rounded bg-meta-4 p-4">
                <div className="prose prose-invert h-10">
                  {serviceAgreementContent || "NIL"}
                </div>
              </div>
              <div className="grid grid-cols-2 gap-6">
                <div>
                  <label className="mb-2 block text-white">Signature</label>
                  {signature ? (
                    <div className="relative h-[150px] rounded border border-stroke bg-white p-2">
                      <img
                        src={`${invoiceData?.invoice?.signature || signature}`}
                        alt="Signature"
                        className="h-[110px] w-full object-contain"
                      />
                      <button
                        onClick={() => {
                          setSignature(null);
                          if (signaturePadRef.current) {
                            signaturePadRef.current.clear();
                          }
                          // Ensure the signature pad is displayed
                          signaturePadRef.current._canvas.style.display =
                            "block";
                        }}
                        className="mt-2 cursor-pointer text-sm text-black hover:text-black"
                      >
                        Edit
                      </button>
                    </div>
                  ) : (
                    <div className="h-[150px] rounded border border-stroke bg-white p-2">
                      <SignaturePad
                        ref={signaturePadRef}
                        canvasProps={{
                          className: "w-full h-[110px]",
                        }}
                      />
                      <button
                        onClick={clearSignature}
                        className="mt-2 cursor-pointer text-sm text-black hover:text-black"
                      >
                        Clear
                      </button>
                    </div>
                  )}
                </div>
                <div>
                  <label className="mb-2 block text-white">Initial</label>
                  <input
                    type="text"
                    value={initial}
                    onChange={(e) => setInitial(e.target.value)}
                    className="h-[150px] w-full rounded border-[1.5px] border-stroke bg-transparent px-5 py-3 align-middle text-5xl font-bold text-white outline-none transition focus:border-primary active:border-primary"
                    placeholder="Enter your initials"
                    maxLength={10}
                  />
                </div>
              </div>
            </div>

            <div className="flex justify-between">
              <button
                onClick={() => setCurrentStep(STEPS.CLIENT_DETAILS)}
                className="rounded-md border border-stroke px-6 py-2 text-white hover:bg-meta-4"
              >
                Back
              </button>
              <button
                onClick={async () => {
                  try {
                    if (!validateSignatureStep()) {
                      return;
                    }

                    // Save signature first
                    const uploadedSignature = await saveSignature();

                    console.log("uploadedSignature", uploadedSignature);

                    // Update the step with all required fields
                    await updateStepCompletion(STEPS.REVIEW_SIGN, {
                      initial: initial,
                      signature: uploadedSignature,
                      feedback: feedback,
                    });

                    // Move to next step
                    setCurrentStep(STEPS.PAYMENT);
                  } catch (error) {
                    console.error("Error updating signature details:", error);
                    showToast(
                      globalDispatch,
                      "Failed to save signature details",
                      4000,
                      "error"
                    );
                  }
                }}
                className="rounded-md bg-primary px-6 py-2 text-white hover:bg-opacity-90"
              >
                Next: Payment
              </button>
            </div>
          </div>
        );

      case STEPS.PAYMENT:
        return (
          <div className="rounded-lg border border-strokedark bg-boxdark p-6">
            <h2 className="mb-6 text-2xl font-semibold text-white">Payment</h2>

            {/* Item Selection */}
            <div className="mb-6">
              <h3 className="mb-4 text-lg font-medium text-white">
                Select Items to Pay
              </h3>
              <div className="space-y-3">
                {invoiceData.items?.map((item) => {
                  const successfulPayments = invoiceData.payments.filter(
                    (p) =>
                      p.invoice_item_id === item.id && p.status === "succeeded"
                  );
                  const totalPaidAmount = successfulPayments.reduce(
                    (sum, payment) => sum + parseFloat(payment.amount),
                    0
                  );
                  const remainingAmount =
                    parseFloat(item.total) - totalPaidAmount;
                  const isFullyPaid = remainingAmount <= 0;
                  const depositAmount =
                    (parseFloat(item.total) *
                      parseFloat(invoiceData.invoice.deposit_percentage)) /
                    100;
                  const remainingForFull = remainingAmount;

                  return (
                    <div key={item.id} className="flex items-center">
                      <input
                        type="checkbox"
                        id={`item-${item.id}`}
                        checked={selectedItems.includes(item.id)}
                        onChange={(e) =>
                          handleItemSelection(item.id, e.target.checked)
                        }
                        className="mr-3 h-5 w-5 rounded border-gray-300"
                        disabled={isFullyPaid}
                      />
                      <label htmlFor={`item-${item.id}`} className="text-white">
                        {item.team_name} - ${remainingAmount.toFixed(2)}
                        {isFullyPaid && " (Paid)"}
                        <span className="text-sm text-gray-400">
                          {" "}
                          (Original: ${item.total})
                        </span>
                      </label>
                      {!isFullyPaid && (
                        <div className="ml-4">
                          <label className="inline-flex items-center">
                            <input
                              type="radio"
                              value="deposit"
                              checked={paymentType === "deposit"}
                              onChange={(e) => setPaymentType(e.target.value)}
                              className="mr-2"
                            />
                            <span className="text-white">
                              Deposit (${depositAmount.toFixed(2)})
                            </span>
                          </label>
                          <label className="ml-4 inline-flex items-center">
                            <input
                              type="radio"
                              value="full"
                              checked={paymentType === "full"}
                              onChange={(e) => setPaymentType(e.target.value)}
                              className="mr-2"
                            />
                            <span className="text-white">
                              Full (${remainingForFull.toFixed(2)})
                            </span>
                          </label>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>

            {/* Payment Method Selection */}
            <div className="mb-6">
              <h3 className="mb-4 text-lg font-medium text-white">
                Payment Method
              </h3>
              <div className="space-y-4">
                <div>
                  <label className="mb-2 block text-white">Card Payment</label>
                  <CardElement
                    options={{
                      style: {
                        base: {
                          fontSize: "16px",
                          color: "#ffffff",
                          "::placeholder": {
                            color: "#aab7c4",
                          },
                        },
                        invalid: {
                          color: "#dc3545",
                        },
                      },
                    }}
                  />
                  {paymentError && (
                    <p className="mt-2 text-sm text-danger">{paymentError}</p>
                  )}
                </div>
              </div>
            </div>

            {/* Payment Amount Display */}
            <div className="mb-6">
              <h3 className="mb-2 text-lg font-medium text-white">
                Payment Amount
              </h3>
              <p className="text-2xl font-bold text-white">
                ${paymentAmount.toFixed(2)}
              </p>
            </div>

            {/* Navigation Buttons */}
            <div className="flex justify-between">
              <button
                onClick={() => setCurrentStep(STEPS.REVIEW_SIGN)}
                className="rounded-md border border-stroke px-6 py-2 text-white hover:bg-meta-4"
              >
                Back
              </button>
              <button
                onClick={async () => {
                  if (selectedItems.length <= 0) {
                    showToast(
                      globalDispatch,
                      "Please select at least one item",
                      5000,
                      "error"
                    );
                    return;
                  } else {
                    // Handle card payment
                    const paymentMethodId = await handleCardPayment();
                    if (!paymentMethodId) {
                      return; // Stop if card processing failed
                    }

                    // Process each selected item individually
                    for (const itemId of selectedItems) {
                      const payload = {
                        invoiceItemId: itemId,
                        paymentMethodId: paymentMethodId,
                        paymentType: paymentType, // "deposit" or "full"
                      };

                      await onSubmit({
                        type: "payment",
                        payload,
                        signature,
                        initial,
                        paymentNotes,
                        feedback,
                        card: { stripe: stripe, elements: elements },
                      });
                    }
                  }
                }}
                className="rounded-md bg-primary px-6 py-2 text-white hover:bg-opacity-90"
              >
                Complete Payment
              </button>
            </div>
          </div>
        );
    }
  };

  // Add breadcrumbs steps
  const steps = [
    { number: STEPS.CLIENT_DETAILS, label: "Client Details" },
    { number: STEPS.REVIEW_SIGN, label: "Review & Sign" },
    { number: STEPS.PAYMENT, label: "Payment" },
  ];

  return (
    <div>
      {/* Breadcrumbs Navigation */}
      <div className="mb-8">
        <div className="flex items-center justify-center">
          {steps.map((step, index) => (
            <div key={step.number} className="flex items-center">
              <div
                className={`flex h-10 w-10 items-center justify-center rounded-full border-2 ${
                  currentStep >= step.number
                    ? "border-primary bg-primary text-white"
                    : "border-stroke bg-boxdark text-bodydark2"
                }`}
              >
                {step.number}
              </div>
              <div
                className={`mx-2 text-sm font-medium ${
                  currentStep >= step.number ? "text-white" : "text-bodydark2"
                }`}
              >
                {step.label}
              </div>
              {index < steps.length - 1 && (
                <div
                  className={`h-px w-20 ${
                    currentStep > step.number ? "bg-primary" : "bg-stroke"
                  }`}
                />
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Existing Content */}
      {renderStep()}
    </div>
  );
};

export default InvoiceMultiStep;
