import { useRouter } from "next/router";
import { Elements, useStripe } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import { env } from "~/env.mjs";
import PaymentStatus from "~/components/payment_status";
import { api } from "~/utils/api";
import PaymentStatusEnum from "~/schemas/public/PaymentStatusEnum";
import { Button, buttonVariants } from "~/components/ui/button";
import { useTranslation } from "~/providers/I18nProvider";
import Link from "next/link";
import { cn } from "~/lib/utils";
import { ArrowLeft } from "lucide-react";
import type { GetServerSideProps } from "next";
import { useEffect, useState } from "react";
import { ProgressRedirect } from "~/components/progress_redirect";

type AcquistoProcessingProps = {
  client_secret: string;
};

export const getServerSideProps = (async (context) => {
  if (
    !context.query.payment_intent_client_secret ||
    typeof context.query.payment_intent_client_secret !== "string"
  ) {
    return {
      redirect: {
        statusCode: 500,
        destination: "/500",
        permanent: false,
      },
    };
  }

  return {
    props: {
      client_secret: context.query.payment_intent_client_secret,
    },
  };
}) satisfies GetServerSideProps<AcquistoProcessingProps>;

export default function AcquistoProcessing({
  client_secret,
}: AcquistoProcessingProps) {
  const { t } = useTranslation();

  const stripePromise = loadStripe(env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY);

  return (
    <div className="mx-auto my-5 w-full max-w-lg space-y-8">
      <h3 className="my-8 text-center text-xl font-bold tracking-wide text-neutral-700 uppercase dark:text-white">
        {t.acquisto_elaborazione.titolo}
      </h3>

      <div>
        <Elements
          options={{
            appearance: {
              theme: "stripe",
            },
            clientSecret: client_secret,
          }}
          stripe={stripePromise}
        >
          <CompletePage secret={client_secret} />
        </Elements>
      </div>
    </div>
  );
}
const CompletePage = ({ secret }: { secret: string }) => {
  const stripe = useStripe();
  const utils = api.useUtils();
  const router = useRouter();
  const { t } = useTranslation();
  const [status, setStatus] = useState<
    "success" | "processing" | "failed" | "internal_error" | "not_found"
  >("processing");

  useEffect(() => {
    const fetchPaymentIntent = async () => {
      if (!stripe) {
        return;
      }

      try {
        const { paymentIntent } = await stripe.retrievePaymentIntent(secret);
        if (!paymentIntent) {
          setStatus("internal_error");
          return;
        }
        const payment = await utils.pagamenti.getPaymentFromIntent.fetch({
          pIntentId: paymentIntent.id,
        });

        if (!payment) {
          setStatus("not_found");
          return;
        }

        if (paymentIntent.status === "succeeded") {
          if (payment.paymentstatus !== PaymentStatusEnum.success) {
            setStatus("internal_error");
          }
          setStatus("success");
        } else if (paymentIntent.status === "processing") {
          if (payment.paymentstatus !== PaymentStatusEnum.processing) {
            setStatus("internal_error");
          }
          setStatus("processing");
        } else {
          setStatus("failed");
        }
      } catch (error) {
        console.error("Error retrieving payment intent:", error);
      }
    };
    void fetchPaymentIntent();
  }, [stripe, secret]);

  if (!status) {
    return null;
  }

  return (
    <div className="space-y-4 p-4">
      {status === "success" && (
        <>
          <PaymentStatus
            title={t.acquisto_elaborazione.success_title}
            status="success"
            message={t.acquisto_elaborazione.success_desc}
          />

          <ProgressRedirect href="/area-riservata/dashboard" />
        </>
      )}
      {status === "processing" && (
        <>
          <PaymentStatus
            title={t.acquisto_elaborazione.processing_title}
            status="processing"
            message={t.acquisto_elaborazione.processing_desc}
          />
          <Link
            href="/area-riservata/dashboard"
            className={cn("w-full", buttonVariants({ variant: "info" }))}
          >
            {t.acquisto_elaborazione.to_dashboard}
          </Link>
        </>
      )}
      {status === "failed" && (
        <>
          <PaymentStatus
            title={t.acquisto_elaborazione.failed_title}
            status="error"
            message={t.acquisto_elaborazione.failed_desc}
          />
          <Link
            href="/area-riservata/chat"
            className={cn("w-full", buttonVariants({ variant: "default" }))}
          >
            {t.acquisto_elaborazione.to_chat}
          </Link>
        </>
      )}
      {status === "internal_error" && (
        <>
          <PaymentStatus
            title={t.acquisto_elaborazione.internal_error_title}
            status="error"
            message={t.acquisto_elaborazione.internal_error_desc}
          />
          <Link
            href="/area-riservata/chat"
            className={cn("w-full", buttonVariants({ variant: "default" }))}
          >
            {t.acquisto_elaborazione.to_chat}
          </Link>
        </>
      )}
      {status === "not_found" && (
        <>
          <PaymentStatus
            title={t.acquisto_elaborazione.not_found_title}
            status="error"
            message={t.acquisto_elaborazione.not_found_desc}
          />
          <Button
            onClick={() => router.back()}
            className="w-full"
            variant="secondary"
          >
            <ArrowLeft />
            {t.indietro}
          </Button>
          <Link
            href="/area-riservata/chat"
            className={cn("w-full", buttonVariants({ variant: "default" }))}
          >
            {t.acquisto_elaborazione.to_chat}
          </Link>
        </>
      )}
    </div>
  );
};
