"use client";

import {
  createManagementSubscriptionSession,
  getSubscriptions,
} from "@/app/(auth)/actions";
import { ModalStatus, Subscription, User } from "@/types";
import React from "react";
import { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { useRouter } from "next/navigation";
import Button from "@/components/Button";
import { useQRCode } from "next-qrcode";

interface ManageSubscriptionProps {
  user: User;
}

function AccountContent({ user }: ManageSubscriptionProps) {
  const router = useRouter();
  const { Canvas } = useQRCode();
  const portalWebsite = process.env
    .NEXT_PUBLIC_PORTAL_SIGN365_WEBSITE as string;
  const downloadApplicationLink = process.env
    .NEXT_PUBLIC_SIGN365_APPLICATION_LINK as string;
  const portalWebsiteTemplatesLink = process.env
    .NEXT_PUBLIC_SIGN365_WEBSITE_TEMPLATE_LINK as string;
  const portalWebsiteIntegrationsLink = process.env
    .NEXT_PUBLIC_SIGN365_WEBSITE_INTEGRATIONS_LINK as string;

  const [subscription, setSubscription] = useState<Subscription>();
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    (async () => {
      if (!user) {
        setLoading(false);
        return;
      }
      try {
        setLoading(true);
        const subscriptions = await getSubscriptions();
        if (subscriptions.length > 0) {
          setSubscription(subscriptions[0]);
        }
        setLoading(false);
      } catch (err) {
        setLoading(false);
      }
    })();
  }, [user]);
  const manageSubscription = async () => {
    try {
      const managementSession = await createManagementSubscriptionSession();
      router.push(managementSession.url);
    } catch (error) {
      if (error instanceof Error) {
        toast.error(error.message, {
          position: "bottom-left",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "colored",
        });
      }
    }
  };

  return loading ? (
    <div className="flex flex-col">
      <Button status={ModalStatus.Loading} text="Loading..." />
    </div>
  ) : (
    <div className="flex flex-col">
      {subscription ? (
        <div className="max-w-6xl mx-auto h-full w-full py-8 px-6 md:pt-12">
          <div className="flex flex-row justify-between w-full bg-gray-700 p-8 rounded">
            <div>
              <h3 className="font-architects-daughter text-xl text-pink-600 mb-2">
                Get Started
              </h3>
              <ol className="list-decimal ml-6">
                <li>
                  <p className="text-lg text-white">
                    <a href={downloadApplicationLink} className="text-pink-500">
                      Download the application
                    </a>{" "}
                    by scanning the QR code
                  </p>
                </li>
                <li>
                  <p className="text-lg text-white">
                    <a
                      href={portalWebsiteTemplatesLink}
                      className="text-pink-500"
                    >
                      Upload some PDF
                    </a>{" "}
                    Forms you want to fill
                  </p>
                </li>
                <li>
                  <p className="text-lg text-white">
                    Setup some{" "}
                    <a
                      href={portalWebsiteIntegrationsLink}
                      className="text-pink-500"
                    >
                      Integrations
                    </a>
                  </p>
                </li>
              </ol>
              <a href={portalWebsite}>
                <button className="btn text-base capitalize !rounded-md text-white bg-bg-gray-925 hover:bg-gray-900 w-full sm:w-auto mt-8">
                  Management Portal
                </button>
              </a>
            </div>
            <div>
              <Canvas
                text={"https://github.com/bunlong/next-qrcode"}
                options={{
                  errorCorrectionLevel: "M",
                  margin: 3,
                  scale: 4,
                  width: 200,
                  color: {
                    dark: "#000000",
                    light: "#ffffff",
                  },
                }}
              />
            </div>
          </div>
        </div>
      ) : (
        <></>
      )}
      <div className="max-w-6xl mx-auto mb-2 h-full w-full px-6">
        <div className="w-full bg-gray-700 p-8 rounded">
          <h3 className="font-architects-daughter text-xl text-pink-600 mb-2">
            Your Subscription
          </h3>
          {subscription ? (
            <>
              <h2 className="h2 text-3xl mb-3">
                {subscription?.product?.name}
              </h2>
              <p className="text-lg text-white mb-4">
                {subscription.product?.description}
              </p>
              <button
                onClick={manageSubscription}
                className="btn text-base capitalize !rounded-md text-white bg-bg-gray-925 hover:bg-gray-900 w-full sm:w-auto mt-8"
              >
                Manage Subscription
              </button>
            </>
          ) : (
            <>
              <p className="text-lg text-white mb-4">
                {"You haven’t upgraded your workflow yet"}
              </p>
              <button
                onClick={() => router.push("/pricing")}
                className="px-10 py-2 text-base capitalize !rounded-3xl text-white bg-gradient-to-r from-primary to-secondary hover:bg-gray-900 w-full sm:w-auto"
              >
                Upgrade
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

export default AccountContent;
