import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { loadStripe } from "@stripe/stripe-js";
import {
  Elements,
  useStripe,
  useElements,
  CardElement,
} from "@stripe/react-stripe-js";
import InvoiceMultiStep, { STEPS } from "Components/Invoice/InvoiceMultiStep";
import MkdSDK from "Utils/MkdSDK";
import { GlobalContext, showToast } from "Src/globalContext";
import SuccessModal from "Components/SuccessModal";

const stripePromise = loadStripe(
  "pk_test_51Ll5ukBgOlWo0lDUrBhA2W7EX2MwUH9AR5Y3KQoujf7PTQagZAJylWP1UOFbtH4UwxoufZbInwehQppWAq53kmNC00UIKSmebO"
);

const InvoiceLinkPage = () => {
  const params = useParams();
  const invoiceId = params.invoiceId;
  const token = params.token;
  const navigate = useNavigate();
  const [invoiceData, setInvoiceData] = useState(null);
  const [clientData, setClientData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [step2Info, setStep2Info] = useState({
    feedback_notes: "",
    signature: "",
    initial: "",
  });
  const [isModalOpen, setIsModalOpen] = useState(false);

  const stripe = useStripe();
  const elements = useElements();

  const fetchClientDetails = async (clientId) => {
    try {
      const sdk = new MkdSDK();
      const response = await sdk.callRawAPI(
        `/v3/api/custom/equality_record/client/${clientId}`,
        [],
        "GET"
      );

      if (!response.error) {
        setClientData(response?.model);
      } else {
        console.error("Error fetching client details:", response.message);
      }
    } catch (err) {
      console.error("Error fetching client details:", err);
    }
  };

  console.log(invoiceData);

  useEffect(() => {
    const fetchInvoice = async () => {
      try {
        const sdk = new MkdSDK();
        const response = await sdk.callRawAPI(
          `/v3/api/custom/equality_record/subscription/public/invoice/${invoiceId}/${token}`,
          [],
          "GET"
        );

        if (response.error) {
          setError("Invalid or expired link");
          showToast(globalDispatch, "Invalid or expired link", "error");
        } else {
          setInvoiceData(response);
          setStep2Info((prev) => ({
            ...prev,
            feedback_notes: response?.invoice?.feedback_notes,
            signature: response?.invoice?.signature,
            initial: response?.invoice?.initials,
          }));

          if (response?.invoice?.client_id) {
            await fetchClientDetails(response?.invoice?.client_id);
          }
        }
      } catch (err) {
        console.error("Error fetching invoice:", err);
        setError("Failed to load invoice");
        showToast(globalDispatch, "Failed to load invoice", "error");
      } finally {
        setLoading(false);
      }
    };

    if (invoiceId && token) {
      fetchInvoice();
    } else {
      setError("Invalid invoice link");
      setLoading(false);
    }
  }, [invoiceId, token, isModalOpen]);

  const updateClientDetails = async (clientId, clientData) => {
    try {
      const sdk = new MkdSDK();
      const response = await sdk.callRawAPI(
        `/v3/api/custom/equality_record/client/${clientId}`,
        clientData,
        "PUT"
      );

      if (!response.error) {
        showToast(globalDispatch, "Client details updated successfully");
        return true;
      } else {
        showToast(globalDispatch, "Failed to update client details", "error");
        return false;
      }
    } catch (err) {
      showToast(globalDispatch, "Failed to update client details", "error");
      return false;
    }
  };

  const handleMultiStepComplete = async (data) => {
    try {
      const sdk = new MkdSDK();

      if (data.step === STEPS.CLIENT_DETAILS) {
        if (data.clientDetails && invoiceData?.invoice?.client_id) {
          const clientUpdateSuccess = await updateClientDetails(
            invoiceData.invoice.client_id,
            data.clientDetails
          );
          if (!clientUpdateSuccess) {
            return;
          }
        }
        return;
      }

      if (data.type === "payment") {
        console.log("data.payload", data.payload);

        try {
          const response = await sdk.callRawAPI(
            `/v3/api/custom/equality_record/subscription/public/payment`,
            data.payload,
            "POST"
          );

          if (response.error) {
            showToast(
              globalDispatch,
              "Payment failed: " + response.message,
              "error"
            );
            return;
          }

          const { client_secret, payment_id } = response;

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

          const { error, paymentIntent } =
            await data.card.stripe.confirmCardPayment(client_secret, {
              payment_method: {
                card: cardElement,
                billing_details: {
                  email: data.payload.email,
                  name: `${data.payload.firstName} ${data.payload.lastName}`,
                  phone: data.payload.phone,
                },
              },
            });

          if (error) {
            showToast(
              globalDispatch,
              "Payment confirmation failed: " + error.message,
              4000,
              "error"
            );
            return;
          }

          const confirmResponse = await sdk.callRawAPI(
            `/v3/api/custom/equality_record/subscription/public/payment/confirm`,
            { paymentId: payment_id },
            "POST"
          );

          if (confirmResponse?.error) {
            showToast(
              globalDispatch,
              "Payment confirmation failed: " + confirmResponse.message,
              4000,
              "error"
            );
            return;
          }

          showToast(globalDispatch, "Payment successful", 4000, "success");
          setIsModalOpen(true);
        } catch (err) {
          console.error("Payment processing error:", err);
          showToast(
            globalDispatch,
            "Payment failed. Please try again.",
            4000,
            "error"
          );
          return;
        }
      } else {
        if (data.signature) {
          await sdk.callRawAPI(
            `/v3/api/custom/equality_record/subscription/public/invoice/${invoiceId}/${token}`,
            {
              signature: data.signature,
              initial: data.initial,
              feedback: data.feedback,
            },
            "PUT"
          );
        }
      }
    } catch (err) {
      console.error("Error processing request:", err);
      showToast(
        globalDispatch,
        "An error occurred. Please try again.",
        4000,
        "error"
      );
    }
  };

  if (loading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="h-16 w-16 animate-spin rounded-full border-4 border-primary border-t-transparent"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex h-screen flex-col items-center justify-center">
        <h1 className="mb-4 text-2xl font-bold text-danger">{error}</h1>
        <p className="text-bodydark">
          Please contact support if you believe this is an error.
        </p>
      </div>
    );
  }

  return (
    <div className="container mx-auto p-4">
      <Elements stripe={stripePromise}>
        <InvoiceMultiStep
          step2Info={step2Info}
          setStep2Info={setStep2Info}
          invoiceData={invoiceData}
          onSubmit={handleMultiStepComplete}
          termsContent={invoiceData?.invoice?.terms_and_conditions || ""}
          serviceAgreementContent={
            invoiceData?.invoice?.terms_and_conditions || ""
          }
          token={token}
          clientData={clientData}
        />
      </Elements>
      <SuccessModal
        isOpen={isModalOpen}
        onClose={() => {
          setIsModalOpen(false);
        }}
        message="Your payment was successful!"
      />
    </div>
  );
};

export default InvoiceLinkPage;
