"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import type { Lang } from "@/lib/config";
import {
  CheckCircle2,
  Calendar,
  Clock,
  Home,
  MapPin,
  Loader2,
} from "lucide-react";

interface PaymentSuccessContentProps {
  lang: Lang;
  bookingId?: string;
  sessionId?: string;
}

export default function PaymentSuccessContent({
  lang,
  bookingId,
  sessionId,
}: PaymentSuccessContentProps) {
  const isAr = lang === "ar";
  const [countdown, setCountdown] = useState(10);
  const [verifying, setVerifying] = useState(true);
  const [verificationError, setVerificationError] = useState<string | null>(
    null,
  );

  // Verify payment and update booking status
  useEffect(() => {
    const verifyPayment = async () => {
      if (!bookingId) {
        setVerifying(false);
        return;
      }

      try {
        const params = new URLSearchParams();
        if (sessionId) params.append("session_id", sessionId);

        const response = await fetch(
          `/api/bookings/${bookingId}/verify-payment?${params.toString()}`,
        );

        const data = await response.json();

        if (data.success) {
          if (data.verified) {
            console.log("Payment verified and booking updated");
          } else if (data.alreadyPaid) {
            console.log("Booking was already marked as paid");
          } else {
            // Payment not found yet - webhook might still be processing
            // Try again in 2 seconds, up to 3 times
            console.log("Payment not verified yet, will retry...");
          }
        } else {
          console.error("Payment verification failed:", data.error);
          setVerificationError(data.error);
        }
      } catch (error) {
        console.error("Error verifying payment:", error);
      } finally {
        setVerifying(false);
      }
    };

    verifyPayment();
  }, [bookingId, sessionId]);

  // Auto-redirect countdown (only starts after verification)
  useEffect(() => {
    if (verifying) return;

    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          window.location.href = `/${lang}/dashboard`;
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [lang, verifying]);

  const t = {
    title: isAr ? "تم الدفع بنجاح!" : "Payment Successful!",
    subtitle: isAr
      ? "شكراً لك! تم استلام دفعتك وتأكيد موعدك."
      : "Thank you! Your payment has been received and your appointment is confirmed.",
    confirmed: isAr ? "موعدك مؤكد" : "Your Appointment is Confirmed",
    confirmationNote: isAr
      ? "ستتلقى رسالة تأكيد عبر البريد الإلكتروني قريباً مع تفاصيل موعدك."
      : "You will receive a confirmation email shortly with your appointment details.",
    whatNext: isAr ? "ماذا بعد؟" : "What's Next?",
    step1: isAr
      ? "تحقق من بريدك الإلكتروني للحصول على تأكيد الموعد"
      : "Check your email for appointment confirmation",
    step2: isAr
      ? "سنرسل لك تذكيراً قبل موعدك بيوم واحد"
      : "We'll send you a reminder one day before your appointment",
    step3: isAr
      ? "يرجى الحضور قبل 10 دقائق من موعدك"
      : "Please arrive 10 minutes before your scheduled time",
    backToHome: isAr ? "العودة للوحة التحكم" : "Back to Dashboard",
    redirecting: isAr
      ? `سيتم إعادة توجيهك خلال ${countdown} ثانية...`
      : `Redirecting in ${countdown} seconds...`,
    verifying: isAr ? "جاري التحقق من الدفع..." : "Verifying payment...",
  };

  return (
    <div
      className="min-h-screen bg-gradient-to-br from-emerald-50 via-white to-teal-50 flex items-center justify-center p-4"
      dir={isAr ? "rtl" : "ltr"}
    >
      <div className="w-full max-w-lg">
        {/* Success Card */}
        <div className="bg-white rounded-3xl shadow-xl overflow-hidden">
          {/* Header with success animation */}
          <div className="bg-gradient-to-r from-emerald-500 to-teal-600 px-8 py-12 text-center relative overflow-hidden">
            {/* Background pattern */}
            <div className="absolute inset-0 opacity-10">
              <div className="absolute inset-0 bg-[radial-gradient(circle_at_1px_1px,white_1px,transparent_0)] bg-[length:24px_24px]" />
            </div>

            {/* Success icon with animation */}
            <div className="relative">
              <div className="w-24 h-24 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center mx-auto mb-6">
                <div className="w-20 h-20 bg-white rounded-full flex items-center justify-center animate-pulse">
                  <CheckCircle2 className="w-12 h-12 text-emerald-500" />
                </div>
              </div>
              <h1 className="text-3xl font-bold text-white mb-2">{t.title}</h1>
              <p className="text-emerald-100 text-lg">{t.subtitle}</p>
            </div>
          </div>

          {/* Content */}
          <div className="px-8 py-8">
            {/* Confirmation Badge */}
            <div className="bg-emerald-50 border border-emerald-200 rounded-2xl p-6 mb-8">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-xl bg-emerald-500 flex items-center justify-center">
                  <Calendar className="w-5 h-5 text-white" />
                </div>
                <h2 className="text-lg font-bold text-emerald-900">
                  {t.confirmed}
                </h2>
              </div>
              <p className="text-emerald-700 text-sm">{t.confirmationNote}</p>
            </div>

            {/* What's Next Section */}
            <div className="mb-8">
              <h3 className="text-lg font-bold text-slate-900 mb-4">
                {t.whatNext}
              </h3>
              <div className="space-y-4">
                <div className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                    <span className="text-sm font-bold text-emerald-600">
                      1
                    </span>
                  </div>
                  <p className="text-slate-600">{t.step1}</p>
                </div>
                <div className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                    <span className="text-sm font-bold text-emerald-600">
                      2
                    </span>
                  </div>
                  <p className="text-slate-600">{t.step2}</p>
                </div>
                <div className="flex items-start gap-4">
                  <div className="w-8 h-8 rounded-full bg-emerald-100 flex items-center justify-center shrink-0 mt-0.5">
                    <span className="text-sm font-bold text-emerald-600">
                      3
                    </span>
                  </div>
                  <p className="text-slate-600">{t.step3}</p>
                </div>
              </div>
            </div>

            {/* Action Button */}
            <Link
              href={`/${lang}/dashboard`}
              className="w-full inline-flex items-center justify-center gap-2 px-6 py-4 rounded-xl bg-gradient-to-r from-emerald-500 to-teal-600 text-white font-semibold shadow-lg shadow-emerald-500/30 hover:shadow-emerald-500/50 hover:-translate-y-0.5 transition-all"
            >
              <Home className="w-5 h-5" />
              {t.backToHome}
            </Link>

            {/* Redirect countdown */}
            <p className="text-center text-sm text-slate-400 mt-4">
              {verifying ? (
                <span className="flex items-center justify-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  {t.verifying}
                </span>
              ) : (
                t.redirecting
              )}
            </p>
          </div>
        </div>

        {/* Footer */}
        <div className="text-center mt-6">
          <p className="text-sm text-slate-500">
            © {new Date().getFullYear()} Mawidi.{" "}
            {isAr ? "جميع الحقوق محفوظة." : "All rights reserved."}
          </p>
        </div>
      </div>
    </div>
  );
}
