// src/pages/Payment.jsx (FINAL - supports /payment/:status + query params, no backend verify)
import React, { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams } from "react-router"; // ✅ FIX
import { useToast } from "../components/ToastProvider";
import Logo from "../assets/logo.png";
import { LuCheckCheck, LuChevronLeft, LuX, LuRefreshCcw } from "react-icons/lu";

const decodeMaybe = (v) => {
  try {
    return v ? decodeURIComponent(v) : "";
  } catch {
    return v || "";
  }
};

function Payment() {
  const navigate = useNavigate();
  const { status: statusParam } = useParams(); // ✅ reads /payment/failed or /payment/success
  const { success, error: toastError, info } = useToast();

  const [loading, setLoading] = useState(true);
  const [finalStatus, setFinalStatus] = useState("pending"); // pending | success | failed
  const [finalMessage, setFinalMessage] = useState("");

  const parsed = useMemo(() => {
    const url = new URL(window.location.href);

    const invoice_id = url.searchParams.get("invoice_id") || "";
    const result = (url.searchParams.get("result") || "").toLowerCase();
    const message = decodeMaybe(url.searchParams.get("message") || "");

    // sometimes gateway params can appear on frontend
    const Authority = url.searchParams.get("Authority") || "";
    const Status = (url.searchParams.get("Status") || "").toLowerCase();

    return { invoice_id, result, message, Authority, Status };
  }, []);

  const cleanUrlParams = () => {
    try {
      const u = new URL(window.location.href);
      ["invoice_id", "result", "message", "Authority", "Status"].forEach((k) => u.searchParams.delete(k));
      window.history.replaceState({}, "", u.toString());
    } catch {}
  };

  const computeFromUrl = ({ result, Status, statusParam }) => {
    const sp = (statusParam || "").toLowerCase();

    // 1) route param has priority: /payment/success or /payment/failed
    if (sp === "success" || sp === "ok" || sp === "paid") return "success";
    if (sp === "failed" || sp === "fail" || sp === "error" || sp === "cancel" || sp === "canceled" || sp === "cancelled") return "failed";

    // 2) query result
    if (result === "success" || result === "ok") return "success";
    if (result === "failed" || result === "fail" || result === "error") return "failed";

    // 3) zarinpal Status=OK
    if (Status === "ok") return "success";
    if (Status && Status !== "ok") return "failed";

    return "failed";
  };

  useEffect(() => {
    const run = async () => {
      info("در حال دریافت نتیجه پرداخت...", { title: "پرداخت" });

      const computed = computeFromUrl({ result: parsed.result, Status: parsed.Status, statusParam });

      const msg =
        parsed.message ||
        (computed === "success"
          ? "پرداخت با موفقیت ثبت شد ✅"
          : "پرداخت لغو یا ناموفق بود ❌");

      setFinalStatus(computed);
      setFinalMessage(msg);
      setLoading(false);

      if (computed === "success") success(msg, { title: "پرداخت" });
      else toastError(msg, { title: "پرداخت" });

      cleanUrlParams();
    };

    run();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [statusParam]);

  const isSuccess = finalStatus === "success";

  return (
    <div className="dark:text-white min-h-screen w-full flex items-center justify-center p-4">
      <div className="w-full max-w-xl rounded-3xl border border-black/10 dark:border-white/10 bg-white dark:bg-[#16325b] shadow overflow-hidden">
        <div className="p-6 border-b border-black/10 dark:border-white/10 flex items-center gap-4">
          <img src={Logo} alt="netnest" className="h-12 w-12 rounded-xl object-contain" />
          <div className="min-w-0">
            <div className="text-lg font-extrabold">نتیجه پرداخت</div>
            <div className="text-xs text-black/60 dark:text-white/70 truncate">
              {parsed.invoice_id ? `شناسه فاکتور: ${parsed.invoice_id}` : "شناسه فاکتور نامشخص"}
            </div>
          </div>
        </div>

        <div className="p-6">
          <div
            className={`p-4 rounded-2xl border shadow flex items-start gap-3 ${
              isSuccess ? "border-emerald-500/30 bg-emerald-500/10" : "border-red-500/30 bg-red-500/10"
            }`}
          >
            <div className="pt-0.5">
              {isSuccess ? <LuCheckCheck className="w-6 h-6" /> : <LuX className="w-6 h-6" />}
            </div>

            <div className="min-w-0">
              <div className="font-bold text-base">
                {loading ? "در حال بررسی..." : isSuccess ? "پرداخت موفق ✅" : "پرداخت ناموفق ❌"}
              </div>

              <div className="text-sm mt-1 text-black/70 dark:text-white/80 break-words">
                {finalMessage || (loading ? "لطفاً چند لحظه صبر کنید." : "")}
              </div>

              {!loading && (
                <div className="text-xs mt-2 opacity-70">
                  وضعیت توسط سرور ثبت شده و این صفحه فقط نتیجه را نمایش می‌دهد.
                </div>
              )}
            </div>
          </div>

          <div className="mt-5 grid sm:grid-cols-2 gap-3">
            <button
              type="button"
              onClick={() => navigate("/receipt")}
              className="px-4 py-3 rounded-2xl shadow bg-[#43BEFF] hover:bg-[#34b6ff] text-white text-sm font-semibold transition"
            >
              رفتن به پرداخت‌ها / فاکتورها
            </button>

            <button
              type="button"
              onClick={() => navigate("/home")}
              className="px-4 py-3 rounded-2xl shadow bg-white dark:bg-[#001F3F] border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 text-sm font-semibold transition"
            >
              بازگشت به داشبورد
            </button>

            <button
              type="button"
              onClick={() => window.location.reload()}
              className="sm:col-span-2 px-4 py-3 rounded-2xl shadow bg-white dark:bg-[#001F3F] border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10 text-sm inline-flex items-center justify-center gap-2 transition"
            >
              <LuRefreshCcw className="w-4 h-4" />
              تلاش مجدد (فقط رفرش صفحه)
            </button>

            <button
              type="button"
              onClick={() => navigate(-1)}
              className="sm:col-span-2 px-4 py-2 rounded-2xl text-sm text-black/60 dark:text-white/70 inline-flex items-center justify-center gap-2 hover:underline"
            >
              <LuChevronLeft className="w-4 h-4" />
              برگشت
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Payment;
