"use client";

import { useState, useEffect } from "react";
import { useRouter } from "@/i18n/navigation";
import { useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { usePaymentControllerCreateCheckoutV1 } from "@/api/user/individual-payment/individual-payment";
import { toast } from "react-hot-toast";

export default function Payment() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const t = useTranslations("individual.payment");
  const [agreedToTerms, setAgreedToTerms] = useState(false);

  const canceled = searchParams.get("canceled");

  // Create checkout mutation (NO screening creation)
  const createCheckoutMutation = usePaymentControllerCreateCheckoutV1({
    mutation: {
      onSuccess: (data: any) => {
        const checkoutUrl = data?.data?.checkout_url;
        if (checkoutUrl) {
          // Redirect to Stripe checkout
          window.location.href = checkoutUrl;
        } else {
          // Dev mode bypass
          const screeningUuid = data?.data?.screening_uuid;
          if (screeningUuid) {
            router.push(`/individual/screening/${screeningUuid}/questions`);
          }
        }
      },
      onError: (error) => {
        console.error("Failed to create checkout:", error);
        toast.error(t("checkoutError"));
      },
    },
  });

  // Show canceled payment message
  useEffect(() => {
    if (canceled === "true") {
      toast.error(t("paymentCanceled"));
    }
  }, [canceled, t]);

  const handleBack = () => {
    router.push("/individual/screening");
  };

  const handlePayment = () => {
    if (!agreedToTerms) return;

    // Create Stripe checkout session (screening will be created AFTER payment)
    createCheckoutMutation.mutate();
  };

  const isLoading = createCheckoutMutation.isPending;

  const includedFeatures = [
    t("feature1"),
    t("feature2"),
    t("feature3"),
    t("feature4"),
    t("feature5"),
  ];

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Back Button */}
        <button
          onClick={handleBack}
          className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-6 transition cursor-pointer"
          disabled={isLoading}
        >
          <svg
            className="w-4 h-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M15 19l-7-7 7-7"
            />
          </svg>
          {t("back")}
        </button>

        {/* Main Card */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
          {/* Title */}
          <div className="text-center mb-6">
            <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900 mb-2">
              {t("title")}
            </h1>
            <p className="text-gray-500">{t("subtitle")}</p>
          </div>

          {/* Price Section */}
          <div className="flex items-center justify-between mb-6">
            <div>
              <p className="text-sm text-gray-600 mb-1">{t("totalAmount")}</p>
              <p className="text-3xl font-semibold text-[#3B9EC9]">$5</p>
            </div>
            <span className="px-4 py-2 text-sm font-medium text-[#3B9EC9] bg-[#3B9EC9]/10 rounded-lg">
              {t("oneTime")}
            </span>
          </div>

          {/* Divider */}
          <div className="border-t border-gray-200 mb-6"></div>

          {/* What's Included Box */}
          <div className="bg-[#E8F5F5] rounded-xl p-6 mb-6">
            <h3 className="font-semibold text-gray-900 mb-4">{t("whatsIncluded")}</h3>
            <ul className="space-y-3">
              {includedFeatures.map((feature, index) => (
                <li key={index} className="flex items-center gap-3 text-gray-700">
                  <svg
                    className="w-5 h-5 text-[#3B9EC9] flex-shrink-0"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                  {feature}
                </li>
              ))}
            </ul>
          </div>

          {/* Terms Checkbox */}
          <div className="flex items-center gap-3 mb-6">
            <input
              type="checkbox"
              id="terms"
              checked={agreedToTerms}
              onChange={(e) => setAgreedToTerms(e.target.checked)}
              className="w-5 h-5 rounded border-gray-300 text-[#3B9EC9] focus:ring-[#3B9EC9] cursor-pointer"
              disabled={isLoading}
            />
            <label htmlFor="terms" className="text-sm text-gray-600 cursor-pointer">
              {t("agreeTerms")}{" "}
              <a href="/terms" target="_blank" rel="noopener noreferrer" className="font-semibold text-[#3B9EC9] underline hover:text-[#3B9EC9]/80">{t("termsOfService")}</a>{" "}
              {t("and")}{" "}
              <a href="/privacy-policy" target="_blank" rel="noopener noreferrer" className="font-semibold text-[#3B9EC9] underline hover:text-[#3B9EC9]/80">{t("privacyPolicy")}</a>
            </label>
          </div>

          {/* Pay Button */}
          <button
            onClick={handlePayment}
            disabled={!agreedToTerms || isLoading}
            className="w-full py-4 text-sm font-medium text-white bg-[#3B9EC9] rounded-xl hover:bg-[#3B9EC9]/90 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition flex items-center justify-center gap-2"
          >
            {isLoading ? (
              <>
                <div className="inline-block animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                <span>{t("processing")}</span>
              </>
            ) : (
              t("payBtn")
            )}
          </button>

          {/* Stripe Badge */}
          <div className="flex items-center justify-center gap-2 mt-6 text-sm text-gray-500">
            <svg
              className="w-4 h-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
              />
            </svg>
            <span>{t("securePayment")}</span>
            <span className="font-semibold text-[#635BFF]">stripe</span>
          </div>
        </div>

        {/* Footer Text */}
        <p className="text-center text-sm text-gray-500 mt-6">{t("stripeDisclaimer")}</p>
      </div>
    </main>
  );
}
