import { showToast } from "Context/Global";
import React, { useEffect, useState } from "react";
import { useParams, useLocation, Link } from "react-router-dom";
import { GlobalContext } from "Src/globalContext";

import MkdSDK from "Utils/MkdSDK";

const InvoiceSuccessPage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const { invoiceId } = useParams();
  const location = useLocation();
  const [invoiceData, setInvoiceData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const paymentMethod = location.state?.paymentMethod || "card";
  const token = location.state?.token;

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

        if (response.error) {
          setError("Failed to load invoice details");
          showToast(globalDispatch, "Failed to load invoice details", "error");
        } else {
          setInvoiceData(response.data);
        }
      } catch (err) {
        setError("An error occurred while loading invoice details");
        showToast(globalDispatch, "Failed to load invoice details", "error");
      } finally {
        setLoading(false);
      }
    };

    if (token) {
      fetchInvoice();
    } else {
      setError("Invalid or missing access token");
      showToast(globalDispatch, "Invalid or missing access token", "error");
      setLoading(false);
    }
  }, [invoiceId, token]);

  const handleDownloadPDF = async (type) => {
    try {
      const sdk = new MkdSDK();
      const response = await sdk.callRestAPI(
        `/v3/api/custom/equality_record/subscription/public/invoice/${invoiceId}/${token}/pdf/${type}`,
        "GET"
      );

      if (response.error) {
        showToast(globalDispatch, "Failed to download PDF", "error");
        return;
      }

      const blob = new Blob([response.data], { type: "application/pdf" });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement("a");
      link.href = url;
      link.download = `${type.replace("_", "-")}.pdf`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (err) {
      showToast(globalDispatch, "Failed to download PDF", "error");
    }
  };

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

  if (error) {
    return (
      <div className="flex flex-col justify-center items-center h-screen">
        <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 p-4 mx-auto">
      <div className="p-8 mx-auto max-w-2xl rounded-lg border border-strokedark bg-boxdark">
        <div className="mb-8 text-center">
          <div className="flex justify-center mb-4">
            <div className="p-4 rounded-full bg-success/20">
              <svg
                className="w-12 h-12 text-success"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M5 13l4 4L19 7"
                ></path>
              </svg>
            </div>
          </div>
          <h1 className="mb-2 text-3xl font-bold text-white">
            {paymentMethod === "check"
              ? "Check Payment Instructions Received"
              : "Payment Successful"}
          </h1>
          <p className="text-lg text-bodydark">
            {paymentMethod === "check"
              ? "Please follow the mailing instructions to complete your payment"
              : "Your payment has been processed successfully"}
          </p>
        </div>

        {paymentMethod === "check" && (
          <div className="p-4 mb-8 rounded bg-meta-4">
            <h2 className="mb-4 text-xl font-semibold text-white">
              Mailing Instructions
            </h2>
            <div className="space-y-2">
              <p className="text-bodydark">Please mail your check to:</p>
              <div className="p-4 rounded bg-boxdark">
                <p className="text-white">{invoiceData.company_name}</p>
                <p className="text-white">{invoiceData.company_address}</p>
                <p className="text-white">
                  Invoice #: {invoiceData.invoice_number}
                </p>
                <p className="text-white">
                  Amount Due: $
                  {invoiceData.payment_type === "deposit"
                    ? (
                        (invoiceData.subtotal *
                          invoiceData.deposit_percentage) /
                        100
                      ).toFixed(2)
                    : invoiceData.subtotal}
                </p>
              </div>
            </div>
          </div>
        )}

        <div className="mb-8">
          <h2 className="mb-4 text-xl font-semibold text-white">
            Download Documents
          </h2>
          <div className="grid gap-4">
            <button
              onClick={() => handleDownloadPDF("service_agreement")}
              className="flex justify-between items-center p-4 rounded border border-stroke bg-meta-4 hover:bg-opacity-90"
            >
              <span className="text-white">Service Agreement</span>
              <svg
                className="w-5 h-5 text-bodydark"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                ></path>
              </svg>
            </button>
            <button
              onClick={() => handleDownloadPDF("terms_conditions")}
              className="flex justify-between items-center p-4 rounded border border-stroke bg-meta-4 hover:bg-opacity-90"
            >
              <span className="text-white">Terms & Conditions</span>
              <svg
                className="w-5 h-5 text-bodydark"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                ></path>
              </svg>
            </button>
            <button
              onClick={() => handleDownloadPDF("invoice")}
              className="flex justify-between items-center p-4 rounded border border-stroke bg-meta-4 hover:bg-opacity-90"
            >
              <span className="text-white">Invoice</span>
              <svg
                className="w-5 h-5 text-bodydark"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth="2"
                  d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                ></path>
              </svg>
            </button>
          </div>
        </div>

        <div className="text-center">
          <p className="mb-4 text-bodydark">
            {paymentMethod === "check"
              ? "Once we receive your check, we'll begin processing your order."
              : "We'll begin processing your order right away."}
          </p>
          <p className="text-bodydark">
            If you have any questions, please{" "}
            <Link to="/contact" className="text-primary hover:underline">
              contact our support team
            </Link>
            .
          </p>
        </div>
      </div>
    </div>
  );
};

export default InvoiceSuccessPage;
