"use client";

import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Link from "next/link";
import { apiFetch } from "@/lib/apiClient";
import { formatNaira } from "@/lib/utils";

type VerifyResult = {
  status: "SUCCESS" | "FAILED" | "PENDING";
  transaction?: {
    amount: number;
    gatewayReference: string;
    booking?: { package?: { name: string } };
  };
};

import { Suspense } from "react";

function PaymentCallbackInner() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const reference = searchParams.get("reference") ?? searchParams.get("trxref") ?? "";
  const [state, setState] = useState<"loading" | "success" | "failed" | "pending">("loading");
  const [result, setResult] = useState<VerifyResult | null>(null);
  const amount = result?.transaction?.amount ?? 0;
  const txRef = result?.transaction?.gatewayReference ?? reference;
  const packageName = result?.transaction?.booking?.package?.name;

  useEffect(() => {
    if (!reference) { router.replace("/dashboard"); return; }
    apiFetch<VerifyResult>("/payments/verify", {
        method: "POST",
        body: JSON.stringify({ reference }),
      })
      .then((data) => {
        setResult(data);
        setState(
          data.status === "SUCCESS" ? "success"
          : data.status === "FAILED" ? "failed"
          : "pending"
        );
      })
      .catch(() => setState("failed"));
  }, [reference, router]);

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-5"
      style={{ background: state === "success" ? "linear-gradient(145deg, #1C2472, #0D1145)" : "#F8F8F8" }}>

      {state === "loading" && (
        <div className="text-center space-y-4">
          <div className="w-16 h-16 mx-auto rounded-full border-4 border-white/20 border-t-[#B8952A] animate-spin" />
          <p className="text-white font-semibold">Verifying your payment...</p>
          <p className="text-white/50 text-sm">Please wait, do not close this page</p>
        </div>
      )}

      {state === "success" && result && (
        <div className="text-center space-y-6 max-w-sm w-full">
          {/* Success icon */}
          <div className="w-20 h-20 mx-auto rounded-full flex items-center justify-center"
            style={{ background: "rgba(184,149,42,0.15)", border: "2px solid #B8952A" }}>
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#B8952A" strokeWidth="2.5">
              <path d="M22 11.08V12a10 10 0 11-5.93-9.14"/>
              <polyline points="22 4 12 14.01 9 11.01"/>
            </svg>
          </div>
          <div>
            <h1 className="text-white font-black text-2xl mb-2" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              Payment Successful!
            </h1>
            <p className="text-white/60 text-sm">Your deposit has been added to your savings</p>
          </div>

          {/* Amount card */}
          <div className="rounded-2xl p-5 text-center" style={{ background: "rgba(255,255,255,0.06)", border: "1px solid rgba(255,255,255,0.08)" }}>
            <p className="text-white/40 text-xs uppercase tracking-wider mb-1">Amount Deposited</p>
            <p className="text-[#B8952A] font-black text-3xl" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              {formatNaira(amount)}
            </p>
            {packageName && (
              <p className="text-white/50 text-sm mt-1">toward {packageName}</p>
            )}
            <p className="text-white/30 text-[10px] mt-3 font-mono">{txRef}</p>
          </div>

          <div className="space-y-3 w-full">
            <Link href="/dashboard"
              className="block w-full py-4 rounded-full font-semibold text-[#1C2472] text-sm text-center"
              style={{ background: "#B8952A" }}>
              Go to Dashboard
            </Link>
            <Link href="/transactions"
              className="block w-full py-3 rounded-full font-semibold text-white/70 text-sm text-center border border-white/10 hover:border-white/30 transition-colors">
              View Transaction History
            </Link>
          </div>
        </div>
      )}

      {state === "failed" && (
        <div className="text-center space-y-6 max-w-sm w-full">
          <div className="w-20 h-20 mx-auto rounded-full flex items-center justify-center bg-red-50 border-2 border-red-200">
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#EF4444" strokeWidth="2.5">
              <circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>
            </svg>
          </div>
          <div>
            <h1 className="font-black text-2xl text-[#111111] mb-2" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              Payment Failed
            </h1>
            <p className="text-[#6B7280] text-sm">Your card was not charged. Please try again.</p>
            {txRef && (
              <p className="text-[#9CA3AF] text-[10px] mt-2 font-mono">{txRef}</p>
            )}
          </div>
          <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
            <p className="text-amber-700 text-xs text-center">
              If you were charged but see this screen, please contact support with your reference number above.
            </p>
          </div>
          <div className="space-y-3 w-full">
            <Link href="/deposit"
              className="block w-full py-4 rounded-full font-semibold text-white text-sm text-center"
              style={{ background: "#1C2472", boxShadow: "0 4px 16px rgba(28,36,114,0.3)" }}>
              Try Again
            </Link>
            <Link href="/dashboard"
              className="block w-full py-3 rounded-full font-semibold text-[#6B7280] text-sm text-center border border-gray-200 hover:bg-gray-50 transition-colors">
              Back to Dashboard
            </Link>
          </div>
        </div>
      )}

      {state === "pending" && (
        <div className="text-center space-y-6 max-w-sm w-full">
          <div className="w-20 h-20 mx-auto rounded-full flex items-center justify-center bg-amber-50 border-2 border-amber-200">
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#F59E0B" strokeWidth="2">
              <circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
            </svg>
          </div>
          <div>
            <h1 className="font-black text-2xl text-[#111111] mb-2" style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
              Payment Pending
            </h1>
            <p className="text-[#6B7280] text-sm">Your payment is being processed. Your balance will update automatically.</p>
          </div>
          <Link href="/dashboard"
            className="block w-full py-4 rounded-full font-semibold text-white text-sm text-center"
            style={{ background: "#1C2472", boxShadow: "0 4px 16px rgba(28,36,114,0.3)" }}>
            Back to Dashboard
          </Link>
        </div>
      )}
    </div>
  );
}

export default function PaymentCallbackPage() {
  return (
    <Suspense>
      <PaymentCallbackInner />
    </Suspense>
  );
}
