"use client";

import React, { useState, FormEvent, useEffect } from "react";
import { StripeCardElement } from "@stripe/stripe-js";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import { useRouter, useSearchParams } from "next/navigation";
import { useDispatch } from "react-redux";
import { paymentListing } from "../api/api";
import paymentSuccess from "../assets/payment_success.gif";
import Image from "next/image";

export const PaymentForm: React.FC = () => {
  const stripe = useStripe();
  const elements = useElements();
  const router = useRouter();
  const searchParams = useSearchParams();
  const dispatch = useDispatch<any>();

  const walletAmount = Number(searchParams.get("walletAmount")) || 0;
  const currency = searchParams.get("currency") || "usd";

  const [paymentStatus, setPaymentStatus] = useState<string>("");
  const [showSuccessDialog, setShowSuccessDialog] = useState<boolean>(false);
  const [showErrorDialog, setShowErrorDialog] = useState<boolean>(false);
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);

  useEffect(() => {
    const routesToPrefetch = ["/profile/wallet/transaction/"];

    routesToPrefetch.forEach((route) => {
      router.prefetch(route);
    });
  }, [router]);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    if (!stripe || !elements) return;
    setIsSubmitting(true);

    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: "card",
      card: elements.getElement(CardElement) as StripeCardElement,
    });

    if (error) {
      setPaymentStatus("Payment failed");
      setShowErrorDialog(true);
      // console.error("Payment Error:", error);
    } else if (paymentMethod) {
      dispatch(
        paymentListing({
          amount: walletAmount,
          payment_method_id: paymentMethod.id,
          currency: currency,
        })
      )
        .unwrap()
        .then(async (response: any) => {
          const clientSecret = response?.data?.payment_intent_client_secret;
          const requiresAction = response?.data?.requires_action;

          if (requiresAction && clientSecret) {
            const result = await stripe.confirmCardPayment(clientSecret);

            if (result.error) {
              setPaymentStatus("Payment failed: " + result.error.message);
              setShowErrorDialog(true);
            } else if (result.paymentIntent.status === "succeeded") {
              setPaymentStatus("Payment completed successfully.");
              setShowSuccessDialog(true);
            }
          } else {
            setPaymentStatus(response?.data?.message || "Payment successful");
            setShowSuccessDialog(true);
          }
        })
        .catch((err: any) => {
          // console.error("Payment API Error:", err.message);
          setPaymentStatus("Payment failed: " + err.message);
          setShowErrorDialog(true);
        });
    }

    setIsSubmitting(false);
  };

  const handleClose = () => {
    setShowSuccessDialog(false);
    router.push("/profile/wallet/transaction/");
  };

  const handleErrorClose = () => {
    setShowErrorDialog(false);
  };

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-lg mt-11 mb-11">
      <h2 className="text-2xl font-semibold mb-4 text-black text-center">
        Complete Your Payment
      </h2>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label
            htmlFor="amount"
            className="block text-gray-700 text-sm font-medium mb-1 "
          >
            Amount
          </label>
          <input
            id="amount"
            type="number"
            placeholder="Amount in dollars"
            value={walletAmount || ""}
            disabled
            className="w-full p-2 border border-gray-300 rounded-md shadow-sm"
          />
        </div>
        <div className="mb-4">
          <CardElement
            options={{ hidePostalCode: true }}
            className="border border-gray-300 p-3 rounded-md shadow-sm"
          />
        </div>
        <button
          type="submit"
          disabled={!stripe || isSubmitting}
          className="animation-custom-button w-full"
        >
          <span className="relative z-10 text-lg">
            {isSubmitting ? "Processing..." : "Pay"}
          </span>
        </button>
      </form>

      {/* Success Dialog */}
      {showSuccessDialog && (
        <div className="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 z-50 p-3">
          <div className="bg-white flex items-center flex-col justify-center rounded-lg shadow-lg pb-4 p-3">
            <Image
              unoptimized
              src={paymentSuccess}
              alt="Success GIF"
              className="mx-auto"
              width={200}
              height={170}
            />
            <h3 className="text-2xl items-center font-semibold text-green-600">
              {paymentStatus}
            </h3>
            <p className="mt-2 text-sm text-gray-600">
              Amount: ${walletAmount}
            </p>
            <button
              onClick={handleClose}
              className="animation-custom-button w-1/2 mt-2"
            >
              <span className="relative z-10 text-lg">Close</span>
            </button>
          </div>
        </div>
      )}

      {/* Error Dialog */}
      {showErrorDialog && (
        <div className="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 z-50 p-3">
          <div className="bg-white p-6 flex items-center flex-col justify-center rounded-lg shadow-lg h-1/2 w-1/3">
            <h3 className="text-2xl font-semibold text-red-600">
              {paymentStatus}
            </h3>
            <p className="mt-4 text-gray-600">
              There was an issue processing your payment. Please try again.
            </p>
            <button
              onClick={handleErrorClose}
              className="mt-4 w-full bg-navy text-white py-2 px-4 rounded-md"
            >
              Close
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
