import React, { useEffect, useState } from "react";
import { useParams, useNavigate, useLocation } from "react-router-dom";
import { Card, Button, Spin, Tag, Typography, Divider, Row, Col, Pagination } from "antd";
import {
  CreditCard,
  ArrowLeft,
  User,
  CheckCircle,
  ShieldCheck,
  Phone,
  Mail,
  Wallet,
  Zap,
} from "lucide-react";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import dayjs from "dayjs";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { loadRazorpayScript } from "@/utils/razorpay.utils";

const { Title, Text } = Typography;

const PaymentProcess: React.FC = () => {
  const { studentId, isSingleStudent, studentData } = useLocation().state;
  const navigate = useNavigate();
  const [students, setStudents] = useState<any[]>([]);
  const [plans, setPlans] = useState<any[]>([]);
  const [selectedPlan, setSelectedPlan] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState(false);
  const [quote, setQuote] = useState<any>(null);
  const [loadingQuote, setLoadingQuote] = useState(false);
  const [planPage, setPlanPage] = useState(1);
  const [planPageSize, setPlanPageSize] = useState(5);
  const hasOnlyTrialPlan = plans.length > 0 && plans.every((plan: any) => plan.planType === "trial");

  const fetchData = async () => {
    try {
      setLoading(true);
      const institutionId = students.length > 0 ? students[0]?.institutionId : undefined;
      const sameInstitution = institutionId
        ? students.every((student) => student.institutionId === institutionId)
        : false;
      const params: any = {};

      if (sameInstitution && institutionId) {
        params.institutionId = institutionId;
      }

      const plansRes = await API_Instance.get(API_Constants.subscriptionPlans, {
        params: { ...params, limit: 1000 },
      });

      setPlans(plansRes.data.data);

      // if (isSingleStudent && studentId) {
      //   const studentRes = await API_Instance.get(`${API_Constants.students}/${studentId}`);
      //   const sData = studentRes.data.data;
      //   setStudents([sData]);
      //   if (sData.subscriptionPlan) {
      //     setSelectedPlan(sData.subscriptionPlan);
      //   }
      // } else if (studentData) {
      setStudents(studentData);
      const firstPaidPlan = plansRes.data.data.find((p: any) => p.planType !== "trial");
      if (firstPaidPlan) {
        setSelectedPlan(firstPaidPlan);
      } else if (plansRes.data.data.length > 0) {
        setSelectedPlan(plansRes.data.data[0]);
      }
      // }
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
      navigate(ROUTE_CONSTANTS.Students);
    } finally {
      setLoading(false);
    }
  };

  const fetchQuote = async () => {
    if (!selectedPlan || students.length === 0) return;
    try {
      setLoadingQuote(true);
      const res = await API_Instance.post(API_Constants.bulkQuote, {
        studentIds: students.map((s) => s.id),
        planId: selectedPlan.id,
      });
      setQuote(res.data.data);
    } catch (error) {
      toast.error("Failed to fetch payment quote");
      console.error(error);
    } finally {
      setLoadingQuote(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  useEffect(() => {
    if (selectedPlan && students.length > 0) {
      fetchQuote();
    }
  }, [selectedPlan, students]);
  
  const handleProcessPayment = async () => {
    if (!selectedPlan || students.length === 0 || !quote) return;

    const res = await loadRazorpayScript();
    if (!res) {
      toast.error("Razorpay SDK failed to load. Are you online?");
      return;
    }

    setProcessing(true);
    try {
      // 1. Create Razorpay Order
      const orderRes = await API_Instance.post(API_Constants.createRazorpayOrder, {
        amount: quote.grandTotal,
        currency: "INR",
        studentIds: students.map((s) => s.id),
        planId: selectedPlan.id,
        quoteData: quote,
      });

      const orderData = orderRes.data.data;

      // 2. Open Razorpay Checkout
      const options = {
        key: window.APP_CONFIG.RAZORPAY_KEY_ID || import.meta.env.VITE_RAZORPAY_KEY_ID || "rzp_test_placeholder",
        amount: orderData.amount,
        currency: orderData.currency,
        name: "Exam Infra",
        description: `Bulk Payment for ${students.length} students - ${selectedPlan.planName}`,
        order_id: orderData.id,
        handler: async (response: any) => {
          try {
            setProcessing(true);
            // 3. Verify Payment and Process Bulk Update
            const verifyRes = await API_Instance.post(API_Constants.verifyBulkPayment, {
              razorpay_order_id: response.razorpay_order_id,
              razorpay_payment_id: response.razorpay_payment_id,
              razorpay_signature: response.razorpay_signature,
              studentIds: students.map((s) => s.id),
              planId: selectedPlan.id,
            });

            toast.success("Payment verified and subscriptions updated!");
            navigate(ROUTE_CONSTANTS.PaymentSuccess.replace(":transactionId", verifyRes.data.data.id), { replace: true });
          } catch (error) {
            toast.error(getAxiosErrorMessage(error));
          } finally {
            setProcessing(false);
          }
        },
        prefill: {
          name: students.length === 1 ? `${students[0].firstName} ${students[0].lastName}` : "Institution",
          email: students.length === 1 ? students[0].email : "",
        },
        theme: {
          color: "#2563eb", // blue-600
        },
        modal: {
          ondismiss: async () => {
            toast.error("Payment cancelled");
            setProcessing(false);
            try {
              await API_Instance.post(API_Constants.cancelPayment, {
                orderId: orderData.id,
                reason: "User closed the payment modal"
              });
            } catch (err) {
              console.error("Failed to track cancellation", err);
            }
          }
        }
      };

      const rzp = new (window as any).Razorpay(options);

      rzp.on("payment.failed", async function (response: any) {
        toast.error(`Payment Failed: ${response.error.description}`);
        console.error("Payment failed details:", response.error);
        setProcessing(false);
        try {
          await API_Instance.post(API_Constants.cancelPayment, {
            orderId: orderData.id,
            reason: `Payment Failed: ${response.error.description}`
          });
        } catch (err) {
          console.error("Failed to track failure", err);
        }
      });

      rzp.open();
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
      setProcessing(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen bg-white">
        <Spin tip="Preparing secure checkout..." />
      </div>
    );
  }

  if (hasOnlyTrialPlan) {
    return (
      <div className="flex justify-center items-center h-screen bg-slate-50">
        <div className="p-8 bg-white rounded-3xl shadow-sm border border-slate-200 text-center max-w-md">
          <div className="w-16 h-16 bg-yellow-50 text-amber-600 rounded-full flex items-center justify-center mx-auto mb-4">
            <ShieldCheck size={32} />
          </div>
          <h2 className="text-xl font-bold text-slate-800 mb-2">Only Trial Plan Available</h2>
          <p className="text-slate-500 mb-6">
            This institution currently has only a trial subscription plan configured. Please contact administration to add paid subscription plans before checkout.
          </p>
          <Button type="primary" onClick={() => navigate(ROUTE_CONSTANTS.Students)}>
            Back to Students
          </Button>
        </div>
      </div>
    );
  }

  if (!selectedPlan || students.length === 0) {
    return (
      <div className="flex flex-col justify-center items-center h-[calc(100vh-100px)] bg-slate-50">
        <div className="p-8 bg-white rounded-3xl shadow-sm border border-slate-200 text-center max-w-md">
          <div className="w-16 h-16 bg-red-50 text-red-500 rounded-full flex items-center justify-center mx-auto mb-4">
            <CreditCard size={32} />
          </div>
          <h2 className="text-xl font-bold text-slate-800 mb-2">No Plans Available</h2>
          <p className="text-slate-500 mb-6">
            There are no subscription plans available for checkout. Please contact admin support.
          </p>
          <Button type="primary" onClick={() => navigate(ROUTE_CONSTANTS.Students)}>
            Go Back
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50/50 py-6 px-4 sm:px-6">
      <div className="max-w-4xl mx-auto">
        <div className="mb-4">
          <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <CreditCard className="text-blue-600" /> {students.length > 1 ? "Bulk Checkout" : "Checkout"}
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Review {students.length > 1 ? "students" : "student"} details and subscription choice.
          </p>
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
          {/* Left Column: Student & Plan Summary */}
          <div className="lg:col-span-7 flex flex-col gap-6">
            <Card className="shadow-sm border-slate-200/60 rounded-3xl overflow-hidden bg-white">
              <div className="p-2">
                <div className="mb-2 pt-4 border-slate-100">
                  <Text className="text-[12px] uppercase tracking-[0.15em] text-slate-400 font-semibold block mb-4">
                    Subscription Plan (Applying to all)
                  </Text>
                  {(() => {
                    const filteredPlans = plans.filter((p) => p.planType !== "trial");
                    const paginatedPlans = filteredPlans.slice((planPage - 1) * planPageSize, planPage * planPageSize);
                    return (
                      <>
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                          {paginatedPlans.map((plan) => {
                            const isSelected = selectedPlan.id === plan.id;
                            return (
                              <div
                                key={plan.id}
                                onClick={() => setSelectedPlan(plan)}
                                className={`group relative p-6 rounded-2xl cursor-pointer transition-all duration-300 border-2 ${isSelected
                                  ? "border-blue-600 bg-blue-50/40 ring-4 ring-blue-50 shadow-md"
                                  : "border-slate-100 bg-white hover:border-blue-200 hover:shadow-sm"
                                  }`}
                              >
                                {isSelected && (
                                  <div className="absolute -top-3 -right-3 w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white shadow-lg border-4 border-white">
                                    <CheckCircle size={16} fill="currentColor" />
                                  </div>
                                )}
                                <div className="flex flex-col gap-3">
                                  <span className={`text-[10px] uppercase tracking-[0.2em] font-black transition-colors ${isSelected ? "text-blue-600" : "text-slate-400"}`}>
                                    {plan.planType} Plan
                                  </span>
                                  <div className="flex flex-col">
                                    <span className={`text-lg font-bold transition-colors ${isSelected ? "text-blue-900" : "text-slate-700"}`}>
                                      {plan.planName}
                                    </span>
                                    <div className="flex items-baseline gap-1 mt-1">
                                      <span className="text-3xl font-black text-slate-900">
                                        ₹{Number(plan.priceAfterDiscount).toLocaleString()}
                                      </span>
                                      <span className="text-slate-400 text-[10px] font-bold uppercase tracking-wider">
                                        / {plan.duration} days
                                      </span>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                        {filteredPlans.length > 0 && (
                          <div className="flex justify-end mt-3">
                            <Pagination
                              current={planPage}
                              pageSize={planPageSize}
                              total={filteredPlans.length}
                              onChange={(page, size) => { setPlanPage(page); setPlanPageSize(size || 10); }}
                              showSizeChanger
                              hideOnSinglePage={false}
                              pageSizeOptions={["5", "10", "20", "50", "100"]}
                              showTotal={(total) => `Total ${total} plans`}
                            />
                          </div>
                        )}
                      </>
                    );
                  })()}
                </div>
                <div className="mt-4 p-5 border border-blue-50 bg-blue-50/30 rounded-2xl flex items-start gap-4">
                  <div className="w-10 h-10 bg-white rounded-xl flex items-center justify-center text-blue-600 shadow-sm shrink-0">
                    <ShieldCheck size={24} />
                  </div>
                  <div>
                    <Text className="block font-bold text-blue-900 text-sm mb-0.5">
                      Secure Bulk Provisioning
                    </Text>
                    <Text className="text-blue-700/60 text-xs leading-relaxed">
                      All {students.length} students will be upgraded to {selectedPlan.planName} immediately.
                      Access remains valid for {selectedPlan.duration} days from deployment.
                    </Text>
                  </div>
                </div>
                <div className="mt-3 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                  <Text className="text-[12px] uppercase tracking-[0.15em] text-slate-400 font-semibold block mb-4">
                    {students.length > 1 ? "Selected Students" : "Student Details"}
                  </Text>

                  <div className="space-y-4 max-h-[300px] overflow-y-auto pr-2 custom-scrollbar">
                    {students.map((s) => {
                      const curQuote = quote?.quotes?.find((q: any) => q.studentId === s.id);
                      return (
                        <div key={s.id} className="group relative flex flex-col sm:flex-row sm:items-center gap-4 p-4 bg-white rounded-2xl border border-slate-100 shadow-sm hover:shadow-md hover:border-blue-100 transition-all duration-200">
                          {/* Left Side: Avatar & Info */}
                          <div className="flex items-center gap-4 flex-1 min-w-0">
                            <div className="w-12 h-12 bg-blue-50 rounded-xl flex items-center justify-center text-blue-600 group-hover:bg-blue-600 group-hover:text-white transition-colors duration-200 shadow-inner shrink-0">
                              <User size={22} />
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex flex-wrap items-center gap-2 mb-1">
                                <h4 className="font-bold text-slate-900 group-hover:text-blue-700 transition-colors truncate max-w-[150px] sm:max-w-none">
                                  {s.firstName} {s.lastName}
                                </h4>
                                <div className="flex gap-1.5 flex-wrap">
                                  <span className="px-2 py-0.5 bg-blue-50 text-blue-700 text-[10px] font-bold uppercase tracking-wider rounded-md border border-blue-100/50 whitespace-nowrap">
                                    {curQuote?.currentPlanName || "No Plan"}
                                  </span>
                                  {curQuote?.currentPlanStatus === "ACTIVE" && (
                                    <span className="px-2 py-0.5 bg-emerald-50 text-emerald-700 text-[10px] font-bold uppercase tracking-wider rounded-md border border-emerald-100/50 whitespace-nowrap">
                                      Active
                                    </span>
                                  )}
                                  {curQuote?.currentPlanStatus === "EXPIRED" && (
                                    <span className="px-2 py-0.5 bg-rose-50 text-rose-700 text-[10px] font-bold uppercase tracking-wider rounded-md border border-rose-100/50 whitespace-nowrap">
                                      Expired
                                    </span>
                                  )}
                                </div>
                              </div>
                              <div className="flex items-center gap-1.5 text-slate-500 text-[11px] font-medium">
                                <Mail size={12} className="shrink-0 opacity-60" />
                                <span className="truncate">{s.email}</span>
                              </div>
                            </div>
                          </div>

                          {/* Right Side: Credit Info */}
                          <div className="shrink-0 flex sm:flex-col items-center sm:items-end justify-between sm:justify-center gap-2 pt-3 sm:pt-0 border-t sm:border-t-0 border-slate-50">
                            <span className="text-[10px] text-slate-400 font-bold uppercase tracking-widest sm:hidden">
                              Credit Details
                            </span>
                            {curQuote?.chargedAmount > 0 ? (
                              <div className="flex flex-col items-end">
                                <span className="text-red-600 font-extrabold text-sm flex items-center gap-0.5">
                                  ₹{Number(curQuote.chargedAmount).toLocaleString()}
                                </span>
                                <span className="text-[9px] text-red-500/80 font-bold uppercase tracking-tight">
                                  To be charged
                                </span>
                              </div>
                            ) : (
                              <div className="flex flex-col items-end opacity-40">
                                <span className="text-red-400 font-extrabold text-sm">
                                  ₹0
                                </span>
                                <span className="text-[9px] text-red-400 font-bold uppercase tracking-tight">
                                  To be charged
                                </span>
                              </div>
                            )}
                            {curQuote?.creditValue > 0 ? (
                              <div className="flex flex-col items-end">
                                <span className="text-emerald-600 font-extrabold text-sm flex items-center gap-0.5">
                                  -₹{Number(curQuote.creditValue).toLocaleString()}
                                </span>
                                <span className="text-[9px] text-emerald-500/80 font-bold uppercase tracking-tight">
                                  Unused Credit
                                </span>
                              </div>
                            ) : (
                              <div className="flex flex-col items-end opacity-40">
                                <span className="text-slate-400 font-extrabold text-sm">
                                  ₹0
                                </span>
                                <span className="text-[9px] text-slate-400 font-bold uppercase tracking-tight">
                                  No Credit
                                </span>
                              </div>
                            )}

                          </div>
                        </div>
                      )
                    })}
                  </div>
                </div>
              </div>
            </Card>
          </div>

          {/* Right Column: Payment Summary */}
          <div className="lg:col-span-5">
            <Card className="shadow-2xl border-none rounded-[2rem] overflow-hidden bg-white sticky top-8">
              <div className="rounded-t-2xl bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 p-8 text-white">
                <div className="flex items-center gap-3 mb-2 opacity-80">
                  <Wallet size={18} className="text-blue-400" />
                  <span className="text-[10px] uppercase tracking-[0.2em] font-bold text-blue-100">
                    Order Summary
                  </span>
                </div>
                <Title
                  level={3}
                  className="!text-white !m-0 !font-black !tracking-tight"
                >
                  Final Checkout
                </Title>
              </div>

              <div className="p-8">
                {loadingQuote ? (
                  <div className="py-16 flex flex-col items-center justify-center gap-6">
                    <div className="relative">
                      <Spin size="large" />
                      <div className="absolute inset-0 flex items-center justify-center">
                        <Zap size={16} className="text-blue-600 animate-pulse" />
                      </div>
                    </div>
                    <Text className="text-slate-400 font-medium italic animate-pulse text-xs tracking-wide">
                      Recalculating proration credits...
                    </Text>
                  </div>
                ) : quote ? (
                  <div className="space-y-6">
                    <div className="space-y-3">
                      <div className="flex justify-between items-center text-slate-500 font-medium text-sm px-1">
                        <span>Base Subtotal</span>
                        <span className="text-slate-900 font-bold">
                          ₹{(quote.quotes.reduce((acc: number, q: any) => acc + q.totalPrice, 0)).toLocaleString()}
                        </span>
                      </div>

                      {quote.quotes.some((q: any) => q.creditValue > 0) && (
                        <div className="flex justify-between items-center text-emerald-600 bg-emerald-50/50 p-3 rounded-xl border border-emerald-100/50">
                          <span className="flex items-center gap-2 font-bold text-xs uppercase tracking-wider">
                            <Zap size={14} fill="currentColor" />
                            Proration Credit
                          </span>
                          <span className="font-black text-sm">
                            -₹{(quote.quotes.reduce((acc: number, q: any) => acc + q.creditValue, 0)).toLocaleString()}
                          </span>
                        </div>
                      )}
                    </div>

                    <div className="bg-slate-50 p-6 rounded-2xl border border-slate-100/50 ring-4 ring-slate-50/50">
                      <span className="text-slate-400 text-[10px] uppercase font-black tracking-[0.2em] block mb-2">
                        Total Amount Payable
                      </span>
                      <div className="flex items-baseline justify-between">
                        <span className="text-4xl font-black text-slate-900 tracking-tighter">
                          ₹{quote.grandTotal.toLocaleString()}
                        </span>
                        <span className="text-xs font-bold text-blue-600 bg-blue-100 px-2 py-0.5 rounded-md">
                          INR
                        </span>
                      </div>
                    </div>

                    <Button
                      type="primary"
                      size="middle"
                      block
                      disabled={quote.grandTotal === 0 || quote?.quotes?.filter((q: any) => q?.chargedAmount == 0)?.length > 0}
                      className="h-16 rounded-1xl bg-blue-600 hover:bg-blue-700 hover:scale-[1.02] active:scale-[0.98] border-none text-lg font-black shadow-xl shadow-blue-200 transition-all duration-300 mt-4 group overflow-hidden relative"
                      onClick={handleProcessPayment}
                      loading={processing}
                    >
                      <span className="relative z-10 flex items-center justify-center gap-2">
                        Confirm & Pay Now <ArrowLeft size={20} className="rotate-180 transition-transform group-hover:translate-x-1" />
                      </span>
                      <div className="absolute inset-0 bg-gradient-to-r from-blue-600 to-indigo-600 opacity-0 group-hover:opacity-100 transition-opacity" />
                    </Button>
                    <div className="text-xs text-yellow-500">
                      * Grand total and to be charged amount (from student) should not 0.
                    </div>
                    <div className="pt-6 flex flex-col items-center gap-4 border-t border-slate-100 mt-6">
                      <div className="flex items-center gap-6 opacity-40 grayscale hover:grayscale-0 transition-all duration-500">
                        <ShieldCheck size={24} />
                        <CreditCard size={24} />
                        <Zap size={24} />
                      </div>
                      <span className="text-slate-400 text-[10px] font-bold uppercase tracking-[0.1em]">
                        Protected by 256-bit SSL Encryption
                      </span>
                    </div>
                  </div>
                ) : (
                  <div className="py-20 flex flex-col items-center justify-center gap-4 text-center">
                    <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center text-slate-300 mb-2">
                      <CreditCard size={32} />
                    </div>
                    <Text className="text-slate-400 italic text-sm">Select a plan to see breakdown</Text>
                  </div>
                )}
              </div>
            </Card>
          </div>
        </div>
      </div >
    </div >
  );
};

export default PaymentProcess;
