import React, { useContext, useEffect, useState } from "react";
import Swal from "sweetalert2";
import { usePurchaseSubscription } from "../../utils/hooks/usePurchaseSubscription";
import { AuthContext } from "../../contexts/auth";
import { AuthContextType } from "../..";
import { Router, useRouter } from "next/router";
import { useCheckSubscriptionStatus } from "../../utils/hooks/useCheckSubscriptionStatus";
import { AxiosResponse } from "axios";
import Link from "next/link";

interface SubscriptionResponse {
  has_active_subscription: boolean;
  expiry_date: string | null;
}

const SubscriptionPackages = () => {
  const { isAuthenticated } = useContext(AuthContext) as AuthContextType;
  const router = useRouter();
  const [isSubscriptionProcessStarted, setIsSubscriptionProcessStarted] =
    useState(false);
  const [isSubscribed, setIsSubscribed] = useState(false);

  const subscriptionContent = [
    {
      id: 1,
      packageType: "Jobrator Plus",
      price: "299",
      discountedPrice: "199",
      features: [
        "Unlimited Access to 1000s of jobs",
        "Apply upto 50 job posts per month",
        "Upto 5 separate customized resumes",
        "Know which company viewed your profile",
        "Get notified about new top jobs",
      ],
    },
    // {
    //   id: 2,
    //   packageType: "Standard",
    //   price: "200",
    //   features: [
    //     "Unlimited Access to 1000s of jobs",
    //     "Apply upto 50 job posts per month",
    //     "Upto 5 separate customized resumes",
    //     "Know which company viewed your profile",
    //     "Get notified about new top jobs",
    //   ],
    // },
    // {
    //   id: 3,
    //   packageType: "Extended",
    //   price: "300",
    //   features: [
    //     "Unlimited Access to 1000s of jobs",
    //     "Apply upto 50 job posts per month",
    //     "Upto 5 separate customized resumes",
    //     "Know which company viewed your profile",
    //     "Get notified about new top jobs",
    //   ],
    // },
  ];

  const { status, plan, redirect } = router.query;

  useEffect(() => {
    if (status === "success") {
      (async () => {
        const resp = await Swal.fire({
          icon: "success",
          title: "Subscription successful!",
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "Ok!",
        });

        if (resp.isConfirmed) {
          // const newUrl = window.location.pathname;
          // router.replace(newUrl, undefined, { shallow: true });

          const storedRedirect =
            redirect || sessionStorage.getItem("postPaymentRedirect");

          const target = storedRedirect
            ? decodeURIComponent(storedRedirect as string)
            : "/dashboard";
          router.push(target);
        }
      })();
    }
  }, [status, plan, router]);

  useEffect(() => {
    if (isAuthenticated) {
      checkSubscriptionStatus();
    }
  }, [isAuthenticated]);

  const checkSubscriptionStatus = async () => {
    const response = await useCheckSubscriptionStatus();
    const { data } = response as AxiosResponse<SubscriptionResponse>;
    const hasActiveSubscription = data.has_active_subscription;
    if (hasActiveSubscription) {
      setIsSubscribed(true);
    }
  };

  const handleSubscription = async (packageId: number) => {
    const res = await Swal.fire({
      icon: "warning",
      title: "Are you sure?",
      showCancelButton: true,
      confirmButtonColor: "#3085d6",
      cancelButtonColor: "#d33",
      confirmButtonText: "Yes, Sure!",
      cancelButtonText: "Cancel",
    });

    if (!isAuthenticated && res.isConfirmed) {
      router.push("/login");
      return;
    }

    if (isAuthenticated && res.isConfirmed) {
      try {
        // Store redirect in session storage
        if (redirect) {
          sessionStorage.setItem("postPaymentRedirect", redirect as string);
        }

        setIsSubscriptionProcessStarted(true);
        const response = await usePurchaseSubscription(packageId);
        console.log("response>>>", response);
        const { data } = response as any;

        // Redirect user to Paystack
        // It internally verify payment status and then persists to DB
        if (data.payment.authorization_url) {
          window.location.href = data.payment.authorization_url;
        }

        console.log(status);
      } catch (e) {
        Swal.fire({
          icon: "error",
          title: "Oops...",
          text: "Something went wrong!",
        });
      } finally {
        setIsSubscriptionProcessStarted(false);
      }
    }
  };

  return (
    <div className="pt-4">
      <div className="auto-container">
        {/* <div className="sec-title text-center">
          <h2 className="">Subscription Packages</h2>
          <div className="text">
            Subscribe and get access to all the features of Jobrator
          </div>
        </div> */}
        <div className="subscription-content wow fadeInUp">
          <div className="row sec-title justify-content-center">
            {subscriptionContent.map((item) => (
              <div
                className="subscription-table col-lg-4 col-md-6 col-sm-12"
                key={item.id}
              >
                <div className="plan-1 border rounded-3 lh-base p-0">
                  <div
                    style={{ backgroundColor: "#055875", minHeight: "170px" }}
                    className="rounded-3 text-white d-flex align-items-around justify-content-center flex-column"
                  >
                    <h3
                      className="text-center fs-1 fw-bold p-2"
                      title="Plan Name"
                    >
                      {item.packageType}
                    </h3>
                    <h2
                      className="text-center fs-5 pt-1 text-white"
                      title="Price"
                    >
                      <div
                        className="pb-2"
                        style={{
                          textDecoration: "line-through",
                        }}
                      >
                        NGN {item.price}
                      </div>
                      <span>NGN {item.discountedPrice}</span>
                      <span className="fs-5">/month</span>
                    </h2>
                  </div>
                  <div className="px-2 py-3" title="Features">
                    {item.features.map((feature, index) => (
                      <p className="py-2" key={index}>
                        <span className="px-2">
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            x="0px"
                            y="0px"
                            width="24"
                            height="24"
                            viewBox="0 0 48 48"
                          >
                            <path
                              fill="#c8e6c9"
                              d="M44,24c0,11.045-8.955,20-20,20S4,35.045,4,24S12.955,4,24,4S44,12.955,44,24z"
                            ></path>
                            <path
                              fill="#4caf50"
                              d="M34.586,14.586l-13.57,13.586l-5.602-5.586l-2.828,2.828l8.434,8.414l16.395-16.414L34.586,14.586z"
                            ></path>
                          </svg>
                        </span>
                        {feature}
                      </p>
                    ))}
                    <div className="mb-1 pt-2 text-center">
                      <Link href="subscription-details-page">View detalis</Link>
                    </div>
                    <div className="align-items-center d-flex justify-content-center pt-4">
                      {isAuthenticated ? (
                        isSubscribed ? (
                          <button
                            className="theme-btn btn-style-three mb-4"
                            disabled
                          >
                            Already Subscribed!
                          </button>
                        ) : isSubscriptionProcessStarted ? (
                          <button
                            className="theme-btn btn-style-three mb-4"
                            disabled
                          >
                            Please wait...
                          </button>
                        ) : (
                          <button
                            onClick={() => handleSubscription(item.id)}
                            className="theme-btn btn-style-one mb-4"
                          >
                            Subscribe Now
                          </button>
                        )
                      ) : (
                        <button
                          onClick={() => handleSubscription(item.id)}
                          className="theme-btn btn-style-one mb-4"
                        >
                          Subscribe Now
                        </button>
                      )}
                      {/* <a
                        href="#"
                        className="theme-btn btn-style-one mb-4"
                        style={{ width: "50%" }}
                        data-bs-toggle="modal"
                        data-bs-target="#subscriptionSuccessModal"
                        change this when the payment api is ready
                      >
                        Subscribe Now
                      </a> */}
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default SubscriptionPackages;
