"use client";

import { use, useEffect, useState } from "react";
import Link from "next/link";
import { PageBand, SiteShell } from "@/components/SiteShell";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:5000/api";

export default function DonationStatusPage({ params }: { params: Promise<{ orderId: string }> }) {
  const { orderId } = use(params);
  const [status, setStatus] = useState<"loading" | "paid" | "pending" | "error">("loading");
  const [receiptNo, setReceiptNo] = useState<string | null>(null);

  useEffect(() => {
    let attempts = 0;
    const maxAttempts = 15;
    
    const checkStatus = async () => {
      try {
        const res = await fetch(`${API}/donations/status/${orderId}`);
        if (!res.ok) throw new Error("Not found");
        
        const data = await res.json();
        
        if (data.status === "paid") {
          setStatus("paid");
          setReceiptNo(data.receiptNo);
          return;
        }

        attempts++;
        if (attempts < maxAttempts) {
          const delay = attempts <= 5 ? 2000 : attempts <= 10 ? 3000 : 5000;
          setTimeout(checkStatus, delay);
        } else {
          setStatus(data.status === "paid" ? "paid" : "pending");
          setReceiptNo(data.receiptNo);
        }
      } catch {
        attempts++;
        if (attempts < maxAttempts) {
          setTimeout(checkStatus, 3000);
        } else {
          setStatus("error");
        }
      }
    };

    checkStatus();
  }, [orderId]);

  return (
    <SiteShell>
      <PageBand className="flex min-h-[60vh] flex-col items-center justify-center text-center">
        {status === "loading" && (
          <div className="flex flex-col items-center gap-4">
            <div className="h-10 w-10 animate-spin rounded-full border-4 border-[var(--color-hairline)] border-t-[var(--color-primary)]" />
            <h2 className="text-2xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Verifying Payment...</h2>
            <p className="text-[var(--color-ink-mute)]">Please wait while we confirm your donation with the bank.</p>
          </div>
        )}

        {status === "paid" && (
          <div className="flex max-w-md flex-col items-center gap-5 rounded-[12px] border border-[var(--color-hairline)] bg-white p-8 shadow-[var(--shadow-l1)]">
            <div className="grid h-20 w-20 place-items-center rounded-full bg-[var(--color-primary)] text-4xl text-[var(--color-on-primary)] shadow-lg">
              ✓
            </div>
            <div>
              <h2 className="text-3xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Thank You!</h2>
              <p className="mt-2 text-[var(--color-primary-deep)]">Your donation has been successfully received.</p>
            </div>
            {receiptNo && (
              <div className="w-full rounded-[6px] border border-[var(--color-hairline)] bg-[var(--color-canvas-soft)] p-3 text-sm font-mono text-[var(--color-ink)]">
                Receipt No: {receiptNo}
              </div>
            )}
            <p className="text-sm text-[var(--color-ink-mute)]">
              A receipt has been sent to your email address.
            </p>
            <Link href="/" className="btn mt-2 w-full">
              Return to Home
            </Link>
          </div>
        )}

        {status === "pending" && (
          <div className="flex max-w-md flex-col items-center gap-5 rounded-[12px] border border-[var(--color-hairline)] bg-white p-8 shadow-[var(--shadow-l1)]">
            <div className="grid h-20 w-20 place-items-center rounded-full bg-[var(--color-canvas-night)] text-2xl text-[var(--color-on-dark)]">
              Pending
            </div>
            <div>
              <h2 className="text-3xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Payment Pending</h2>
              <p className="mt-2 text-[var(--color-ink-mute)]">We are still waiting for confirmation from the bank.</p>
            </div>
            <p className="text-sm text-[var(--color-ink-mute)]">
              If your money was deducted, it will be updated shortly. You will receive an email receipt once confirmed.
            </p>
            <Link href="/" className="btn-secondary mt-2 w-full">
              Return to Home
            </Link>
          </div>
        )}

        {status === "error" && (
          <div className="flex max-w-md flex-col items-center gap-5 rounded-[12px] border border-[var(--color-hairline)] bg-white p-8 shadow-[var(--shadow-l1)]">
            <div className="grid h-20 w-20 place-items-center rounded-full bg-[var(--color-canvas-night)] text-2xl text-[var(--color-on-dark)]">
              Failed
            </div>
            <div>
              <h2 className="text-3xl text-[var(--color-ink)]" style={{ fontWeight: 500 }}>Payment Failed</h2>
              <p className="mt-2 text-[var(--color-ink-mute)]">We couldn't verify your payment.</p>
            </div>
            <Link href="/donate" className="btn mt-2 w-full">
              Try Again
            </Link>
          </div>
        )}
      </PageBand>
    </SiteShell>
  );
}
