import React, { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { Card, Button, Spin, Tag, Typography, Pagination } from "antd";
import {
  Send,
  ArrowLeft,
  User,
  CheckCircle,
  ShieldCheck,
  Mail,
} 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 ROUTE_CONSTANTS from "@/constants/route.constants";
import Modal from "@/components/shared/Modal";

const { Text } = Typography;

interface StudentData {
  id: string;
  firstName: string;
  lastName: string;
  email: string;
  institutionId?: string;
  subscriptionPlan?: { id: string; planName: string; planType: string; duration: number };
  studentInstitutionId?: string;
}

interface ValidationResult {
  totalEligible: number;
  totalSelected: number;
  planName: string;
  duration: number;
  priceAfterDiscount: number;
  gstPercentage: number;
  students: { studentId: string; name: string; email: string; studentInstitutionId: string }[];
  skipped: {
    missingFromInstitution: string[];
    hasProcessingPayment: string[];
  };
}

const SubscriptionRequestCheckout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const { studentData } = (location.state || {}) as { studentData?: StudentData[] };

  const [students, setStudents] = useState<StudentData[]>([]);
  const [plans, setPlans] = useState<any[]>([]);
  const [selectedPlan, setSelectedPlan] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [planPage, setPlanPage] = useState(1);
  const [planPageSize, setPlanPageSize] = useState(5);
  const hasOnlyTrialPlan = plans.length > 0 && plans.every((plan: any) => plan.planType === "trial");

  const [validating, setValidating] = useState(false);
  const [validationData, setValidationData] = useState<ValidationResult | null>(null);
  const [validationError, setValidationError] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);

  useEffect(() => {
    if (!studentData || studentData.length === 0) {
      toast.error("No students selected");
      navigate(ROUTE_CONSTANTS.Students, { replace: true });
      return;
    }
    setStudents(studentData);
  }, [studentData, navigate]);

  const fetchPlans = 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 res = await API_Instance.get(API_Constants.subscriptionPlans, {
        params: { ...params, limit: 1000 },
      });
      const fetchedPlans = res.data.data || [];
      setPlans(fetchedPlans);
      
      const firstPaidPlan = fetchedPlans.find((p: any) => p.planType !== "trial");
      if (firstPaidPlan) {
        setSelectedPlan(firstPaidPlan);
      } else if (fetchedPlans.length > 0) {
        setSelectedPlan(fetchedPlans[0]);
      }
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
      navigate(ROUTE_CONSTANTS.Students, { replace: true });
    } finally {
      setLoading(false);
    }
  };

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

  const runValidation = async (plan: any) => {
    if (!plan || students.length === 0) return;
    setValidating(true);
    setValidationError(false);
    try {
      const res = await API_Instance.post(
        `${API_Constants.subscriptionRequests}/bulk-validate`,
        { studentInstitutionIds: students.map((s) => s.studentInstitutionId), planId: plan.id },
      );
      setValidationData(res.data.data as ValidationResult);
    } catch {
      setValidationError(true);
      setValidationData(null);
    } finally {
      setValidating(false);
    }
  };

  useEffect(() => {
    if (selectedPlan) {
      runValidation(selectedPlan);
    }
  }, [selectedPlan]);

  const handleSendRequest = () => {
    if (!validationData || validationData.totalEligible === 0) {
      toast.error("No eligible students found");
      return;
    }
    setShowConfirmModal(true);
  };

  const handleConfirmSend = async () => {
    if (!validationData) return;
    setConfirmLoading(true);
    try {
      const sendRes = await API_Instance.post(
        `${API_Constants.subscriptionRequests}/bulk-send`,
        {
          studentInstitutionIds: validationData.students.map((s) => (s.studentInstitutionId)),
          planId: selectedPlan?.id,
        },
      );
      toast.success(`${sendRes.data.data.totalSent} request(s) sent successfully`);
      setShowConfirmModal(false);
      setValidationData(null);
      navigate(ROUTE_CONSTANTS.SubscriptionRequests, { replace: true });
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setConfirmLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-screen bg-white">
        <Spin tip="Loading 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">
            <Send 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">
            There are no paid subscription plans available to send a request for. Please contact administration to add paid plans for your institution.
          </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">
            <Send 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 to send a request for. 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">
            <Send className="text-blue-600" /> Subscription Request Checkout
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Review student details and send subscription requests.
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
          {/* Left Column: Plan Selector + Student List */}
          <div className="lg:col-span-7 flex flex-col gap-6">
            {/* Plan Selection */}
            <Card className="shadow-sm border-slate-200/60 rounded-3xl overflow-hidden bg-white">
              <div className="p-2">
                <div>
                  <Text className="text-[12px] uppercase tracking-[0.15em] text-slate-400 font-semibold block mb-4">
                    Select Subscription Plan
                  </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">
                      Bulk Request
                    </Text>
                    <Text className="text-blue-700/60 text-xs leading-relaxed">
                      {validationData
                        ? `Subscription requests will be sent to ${validationData.totalEligible} eligible student(s) for the ${selectedPlan.planName} plan.`
                        : `Subscription requests will be sent to ${students.length} student(s) for the ${selectedPlan.planName} plan.`
                      }
                    </Text>
                  </div>
                </div>

                <div className="mt-3 p-4 bg-slate-50 rounded-2xl border border-slate-100">
                  <div className="flex items-center justify-between mb-4">
                    <Text className="text-[12px] uppercase tracking-[0.15em] text-slate-400 font-semibold">
                      Selected Students
                    </Text>
                    {validating ? (
                      <Spin size="small" />
                    ) : validationData ? (
                      <div className="flex items-center gap-2">
                        <Tag color="blue" className="text-xs px-2 py-0.5 rounded-md">{validationData.totalEligible} Eligible</Tag>
                        {validationData.skipped.missingFromInstitution.length + validationData.skipped.hasProcessingPayment.length > 0 && (
                          <Tag className="text-xs px-2 py-0.5 rounded-md">{validationData.skipped.missingFromInstitution.length + validationData.skipped.hasProcessingPayment.length} Skipped</Tag>
                        )}
                      </div>
                    ) : null}
                  </div>
                  <div className="space-y-4 max-h-[300px] overflow-y-auto pr-2 custom-scrollbar">
                    {students.map((s) => {
                      const eligible = validationData?.students?.find(vs => vs.studentInstitutionId === s.studentInstitutionId);
                      const skippedMissing = validationData?.skipped?.missingFromInstitution?.includes(s.studentInstitutionId);
                      const skippedProcessing = validationData?.skipped?.hasProcessingPayment?.includes(s.studentInstitutionId);
                      const isEligible = !!eligible;
                      const isSkipped = skippedMissing || skippedProcessing;

                      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 shadow-sm transition-all duration-200 ${isSkipped
                            ? "border-amber-200 bg-amber-50/30"
                            : isEligible
                              ? "border-emerald-100 hover:shadow-md hover:border-emerald-200"
                              : "border-slate-100 hover:shadow-md hover:border-blue-100"
                            }`}
                        >
                          <div className="flex items-center gap-4 flex-1 min-w-0">
                            <div className={`w-12 h-12 rounded-xl flex items-center justify-center shadow-inner shrink-0 ${isSkipped
                              ? "bg-amber-100 text-amber-500"
                              : isEligible
                                ? "bg-emerald-50 text-emerald-600"
                                : "bg-blue-50 text-blue-600"
                              }`}>
                              <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 truncate max-w-[150px] sm:max-w-none">
                                  {s.firstName} {s.lastName}
                                </h4>
                                {s.subscriptionPlan && (
                                  <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">
                                    {s.subscriptionPlan.planName}
                                  </span>
                                )}
                                {validationData && isSkipped && (
                                  <span className="px-2 py-0.5 bg-amber-100 text-amber-700 text-[10px] font-bold uppercase tracking-wider rounded-md whitespace-nowrap">
                                    {skippedMissing ? "Not in institution" : "Payment in progress"}
                                  </span>
                                )}
                                {validationData && isEligible && (
                                  <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">
                                    Eligible
                                  </span>
                                )}
                              </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>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            </Card>
          </div>

          {/* Right Column: Summary & Send Action */}
          <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">
                  <Send size={18} className="text-blue-400" />
                  <span className="text-[10px] uppercase tracking-[0.2em] font-bold text-blue-100">
                    Request Summary
                  </span>
                </div>
                <h3 className="!text-white !m-0 !font-black !tracking-tight text-xl">
                  Send Requests
                </h3>
              </div>

              <div className="p-8">
                <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>Plan</span>
                      <span className="text-slate-900 font-bold">{selectedPlan.planName}</span>
                    </div>
                    <div className="flex justify-between items-center text-slate-500 font-medium text-sm px-1">
                      <span>Type</span>
                      <span className="text-slate-900 font-bold capitalize">{selectedPlan.planType}</span>
                    </div>
                    <div className="flex justify-between items-center text-slate-500 font-medium text-sm px-1">
                      <span>Duration</span>
                      <span className="text-slate-900 font-bold">{selectedPlan.duration} days</span>
                    </div>
                    <div className="flex justify-between items-center text-slate-500 font-medium text-sm px-1">
                      <span>Price</span>
                      <span className="text-slate-900 font-bold">
                        ₹{Number(selectedPlan.priceAfterDiscount).toLocaleString()}
                        {selectedPlan.gstPercentage > 0 && (
                          <span className="text-xs text-slate-400 font-normal ml-1">
                            (including {selectedPlan.gstPercentage}% GST)
                          </span>
                        )}
                      </span>
                    </div>
                  </div>

                  {validating ? (
                    <div className="bg-slate-50 p-6 rounded-2xl border border-slate-100/50 ring-4 ring-slate-50/50 flex flex-col items-center gap-3">
                      <Spin />
                      <span className="text-slate-400 text-xs font-medium">Validating students...</span>
                    </div>
                  ) : validationData ? (
                    <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">
                        Eligibility
                      </span>
                      <div className="flex items-baseline justify-between mb-3">
                        <span className="text-4xl font-black text-slate-900 tracking-tighter">
                          {validationData.totalEligible}
                        </span>
                        <div className="flex items-center gap-2">
                          <span className="text-xs font-bold text-blue-600 bg-blue-100 px-2 py-0.5 rounded-md">
                            eligible
                          </span>
                          <span className="text-xs text-slate-400">
                            / {validationData.totalSelected} selected
                          </span>
                        </div>
                      </div>

                      {validationData.skipped && (validationData.skipped.missingFromInstitution.length > 0 || validationData.skipped.hasProcessingPayment.length > 0) && (
                        <div className="bg-amber-50 p-3 rounded-xl border border-amber-200 mt-2">
                          <span className="text-[10px] text-amber-600 font-bold uppercase tracking-wider">
                            Skipped ({validationData.skipped.missingFromInstitution.length + validationData.skipped.hasProcessingPayment.length})
                          </span>
                          {validationData.skipped.missingFromInstitution.length > 0 && (
                            <p className="text-xs text-amber-700 mt-1">
                              {validationData.skipped.missingFromInstitution.length} student(s) not found in your institution
                            </p>
                          )}
                          {validationData.skipped.hasProcessingPayment.length > 0 && (
                            <p className="text-xs text-amber-700 mt-1">
                              {validationData.skipped.hasProcessingPayment.length} student(s) have a payment in progress
                            </p>
                          )}
                        </div>
                      )}
                    </div>
                  ) : validationError ? (
                    <div className="bg-rose-50 p-6 rounded-2xl border border-rose-200">
                      <span className="text-xs text-rose-600 font-medium">Validation failed. Please try again.</span>
                    </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 Students
                      </span>
                      <div className="flex items-baseline justify-between">
                        <span className="text-4xl font-black text-slate-900 tracking-tighter">
                          {students.length}
                        </span>
                        <span className="text-xs font-bold text-blue-600 bg-blue-100 px-2 py-0.5 rounded-md">
                          selected
                        </span>
                      </div>
                    </div>
                  )}

                  <Button
                    type="primary"
                    size="middle"
                    block
                    disabled={!validationData || validationData.totalEligible === 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={handleSendRequest}
                  >
                    <span className="relative z-10 flex items-center justify-center gap-2">
                      Send Request <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="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} />
                      <Send size={24} />
                      <User size={24} />
                    </div>
                    <span className="text-slate-400 text-[10px] font-bold uppercase tracking-[0.1em]">
                      Request will be sent to selected students
                    </span>
                  </div>
                </div>
              </div>
            </Card>
          </div>
        </div>

        {/* Confirmation Modal */}
        <Modal isOpen={showConfirmModal} onClose={() => setShowConfirmModal(false)} title="Confirm Send Request">
          {validationData && (
            <div className="space-y-4">
              <div className="bg-blue-50 p-4 rounded-xl border border-blue-100">
                <div className="grid grid-cols-2 gap-4">
                  <div className="flex flex-col">
                    <span className="text-xs text-slate-400">Plan</span>
                    <span className="font-semibold text-slate-800">{validationData.planName}</span>
                  </div>
                  <div className="flex flex-col">
                    <span className="text-xs text-slate-400">Duration</span>
                    <span className="font-semibold text-slate-800">{validationData.duration} Days</span>
                  </div>
                  <div className="flex flex-col">
                    <span className="text-xs text-slate-400">Price</span>
                    <span className="font-semibold text-slate-800">
                      ₹{validationData.priceAfterDiscount} + {validationData.gstPercentage}% GST
                    </span>
                  </div>
                </div>
              </div>

              <div className="flex items-center gap-3">
                <Tag color="blue" className="text-sm px-3 py-1">
                  {validationData.totalEligible} Eligible
                </Tag>
                <Tag className="text-sm px-3 py-1">
                  {validationData.totalSelected} Selected
                </Tag>
              </div>

              {validationData.students.length > 0 && (
                <div>
                  <span className="text-xs text-slate-400 uppercase tracking-wider font-medium">Students</span>
                  <div className="mt-1 max-h-40 overflow-y-auto border border-slate-100 rounded-lg">
                    {validationData.students.map((s) => (
                      <div
                        key={s.studentId}
                        className="flex items-center justify-between px-3 py-2 border-b border-slate-50 last:border-0"
                      >
                        <span className="text-sm text-slate-700">{s.name}</span>
                        <span className="text-xs text-slate-400">{s.email}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {validationData.skipped &&
                (validationData.skipped.missingFromInstitution.length > 0 ||
                  validationData.skipped.hasProcessingPayment.length > 0) && (
                  <div className="bg-amber-50 p-3 rounded-lg border border-amber-200">
                    <span className="text-xs text-amber-600 font-medium uppercase tracking-wider">
                      Skipped Students
                    </span>
                    {validationData.skipped.missingFromInstitution.length > 0 && (
                      <p className="text-xs text-amber-700 mt-1">
                        {validationData.skipped.missingFromInstitution.length} student(s) not found in your institution.
                      </p>
                    )}
                    {validationData.skipped.hasProcessingPayment.length > 0 && (
                      <p className="text-xs text-amber-700 mt-1">
                        {validationData.skipped.hasProcessingPayment.length} student(s) have a payment in progress.
                      </p>
                    )}
                  </div>
                )}

              <div className="flex justify-end gap-2 pt-2 border-t">
                <Button onClick={() => setShowConfirmModal(false)}>Cancel</Button>
                <Button
                  type="primary"
                  className="bg-blue-600 hover:bg-blue-700 border-none flex items-center gap-2"
                  loading={confirmLoading}
                  onClick={handleConfirmSend}
                >
                  <Send size={16} />
                  Send Request to {validationData.totalEligible} Student(s)
                </Button>
              </div>
            </div>
          )}
        </Modal>
      </div>
    </div>
  );
};

export default SubscriptionRequestCheckout;
