import React, { useEffect, useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { Card, Button, Spin, Typography, Divider, Result } from "antd";
import {
  CheckCircle2,
  Users,
  CreditCard,
  ArrowRight,
  ShieldCheck,
  LayoutDashboard,
  History,
} from "lucide-react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import dayjs from "dayjs";

const { Title, Text } = Typography;

const PaymentSuccessPage: React.FC = () => {
  const { transactionId } = useParams<{ transactionId: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [payment, setPayment] = useState<any>(null);
  const [polling, setPolling] = useState(false);

  const fetchPaymentDetails = async (isRetry = false) => {
    try {
      if (!isRetry) setLoading(true);
      const res = await API_Instance.get(`${API_Constants.payments}/${transactionId}`);
      const data = res.data.data;
      setPayment(data);

      if (data.status === "PENDING") {
        setPolling(true);
        // Retry after 3 seconds
        setTimeout(() => fetchPaymentDetails(true), 3000);
      } else {
        setPolling(false);
        setLoading(false);
      }
    } catch (error) {
      if (!isRetry) {
        toast.error(getAxiosErrorMessage(error));
        setLoading(false);
      }
      setPolling(false);
    }
  };

  useEffect(() => {
    if (transactionId) {
      fetchPaymentDetails();
    }
  }, [transactionId]);

  if (loading || polling) {
    return (
      <div className="flex flex-col justify-center items-center h-screen bg-slate-50">
        <Spin size="large" tip={polling ? "Finalizing your subscription..." : "Confirming your transaction..."} />
      </div>
    );
  }

  const isFailed = ["FAILED", "CANCELLED", "EXPIRED"].includes(payment?.status);

  if (!payment || isFailed) {
    return (
      <div className="flex flex-col justify-center items-center h-screen bg-slate-50">
        <Result
          status="error"
          title={payment?.status === "CANCELLED" ? "Payment Cancelled" : "Transaction Error"}
          subTitle={payment?.failureReason || "We couldn't find the details for this transaction or it was unsuccessful."}
          extra={[
            <Button type="primary" onClick={() => navigate(ROUTE_CONSTANTS.Payments)}>
              Go to Payment History
            </Button>
          ]}
        />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50 flex items-center justify-center p-4 sm:p-6 lg:p-8">
      <div className="max-w-2xl w-full">
        <Card className="shadow-2xl border-none rounded-[2.5rem] overflow-hidden bg-white">
          <div className="bg-gradient-to-br from-emerald-500 to-teal-600 p-10 text-center relative overflow-hidden">
            {/* Background Decorative Elements */}
            <div className="absolute top-0 left-0 w-full h-full opacity-10 pointer-events-none">
              <div className="absolute -top-10 -left-10 w-40 h-40 bg-white rounded-full blur-3xl animate-pulse" />
              <div className="absolute -bottom-10 -right-10 w-40 h-40 bg-white rounded-full blur-3xl animate-pulse" />
            </div>

            <div className="relative z-10 flex flex-col items-center">
              <div className="w-20 h-20 bg-white/20 backdrop-blur-md rounded-3xl flex items-center justify-center text-white mb-6 border border-white/30 shadow-xl animate-bounce">
                <CheckCircle2 size={48} strokeWidth={2.5} />
              </div>
              <Title level={2} className="!text-white !m-0 !font-black !tracking-tight">
                Payment Successful!
              </Title>
              <Text className="text-emerald-50 font-medium block mt-2 opacity-90">
                Your subscription has been upgraded successfully.
              </Text>
            </div>
          </div>

          <div className="p-8 sm:p-12">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-10">
              <div className="bg-slate-50 p-6 rounded-3xl border border-slate-100 flex flex-col items-center text-center group hover:bg-blue-50 transition-colors duration-300">
                <div className="w-12 h-12 bg-blue-100 text-blue-600 rounded-2xl flex items-center justify-center mb-4 group-hover:bg-blue-600 group-hover:text-white transition-all duration-300">
                  <Users size={24} />
                </div>
                <Text className="text-slate-400 text-xs font-black uppercase tracking-widest block mb-1">
                  Students Subscribed
                </Text>
                <Title level={3} className="!m-0 !text-slate-900 !font-black">
                  {payment.studentCount}
                </Title>
              </div>

              <div className="bg-slate-50 p-6 rounded-3xl border border-slate-100 flex flex-col items-center text-center group hover:bg-emerald-50 transition-colors duration-300">
                <div className="w-12 h-12 bg-emerald-100 text-emerald-600 rounded-2xl flex items-center justify-center mb-4 group-hover:bg-emerald-600 group-hover:text-white transition-all duration-300">
                  <CreditCard size={24} />
                </div>
                <Text className="text-slate-400 text-xs font-black uppercase tracking-widest block mb-1">
                  Total Amount Paid
                </Text>
                <Title level={3} className="!m-0 !text-slate-900 !font-black">
                  ₹{Number(payment.amount).toLocaleString()}
                </Title>
              </div>
            </div>

            <div className="bg-slate-900 rounded-[2rem] p-8 text-white mb-10 relative overflow-hidden group">
              <div className="relative z-10">
                 <div className="flex items-center gap-2 mb-4">
                    <ShieldCheck size={18} className="text-emerald-400" />
                    <span className="text-[10px] font-black uppercase tracking-[0.2em] text-slate-400">
                      Active Plan Details
                    </span>
                 </div>
                 <div className="flex justify-between items-end">
                    <div>
                        <Title level={3} className="!text-white !m-0 !font-black !tracking-tight">
                            {payment.planName}
                        </Title>
                        <Text className="text-slate-400 text-xs font-medium block mt-1">
                            Validity: Active until {dayjs(payment.endDate).format('DD MMM YYYY')}
                        </Text>
                    </div>
                    <div className="px-3 py-1 bg-emerald-500/20 text-emerald-400 rounded-lg border border-emerald-500/30 text-[10px] font-black uppercase tracking-widest">
                        ACTIVE
                    </div>
                 </div>
              </div>
              <div className="absolute top-0 right-0 p-4 opacity-10 group-hover:opacity-20 transition-opacity">
                <CreditCard size={120} />
              </div>
            </div>

            <div className="flex flex-col gap-4">
              <Button
                type="primary"
                size="large"
                block
                className="h-16 rounded-2xl bg-blue-600 hover:bg-blue-700 border-none text-base font-black shadow-xl shadow-blue-200 transition-all duration-300 flex items-center justify-center gap-3"
                onClick={() => navigate(ROUTE_CONSTANTS.Students)}
              >
                <LayoutDashboard size={20} /> Navigate to Student Management
              </Button>
              <Button
                size="large"
                block
                className="h-16 rounded-2xl border-slate-200 text-slate-600 hover:text-blue-600 hover:border-blue-200 font-bold flex items-center justify-center gap-3 transition-all duration-300"
                onClick={() => navigate(ROUTE_CONSTANTS.Payments)}
              >
                <History size={20} /> Navigate to Payment Details
              </Button>
            </div>

            <div className="mt-10 pt-8 border-t border-slate-100 flex justify-center grayscale opacity-40">
              <div className="flex items-center gap-6">
                 <Text className="text-[10px] font-black uppercase tracking-[0.3em] text-slate-400">
                   Secure Transaction Verified
                 </Text>
              </div>
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default PaymentSuccessPage;
