"use client";

import { useEffect, useState } from "react";
import { Check, Star, Crown, Sparkles, ArrowLeft } from "lucide-react";
import { useRouter } from "next/navigation";
import Sidebar from "@/components/modals/ui/Sidebar";
import {
  getSubscriptionPlansApi,
  SubscriptionPlan,
} from "@/app/services/subscription";
import {
  createSubscriptionApi,
  verifyPaymentApi,
  cancelSubscriptionApi,
} from "@/app/services/payment";
import { loadRazorpayScript, openRazorpay } from "@/app/utils/razorpay";
import { RazorpayResponse } from "@/app/types/razorpay";
import RazorpayScript from "@/components/modals/ui/RazorpayScript";

function formatPrice(price: string) {
  const num = Number(price);
  if (!num) return "₹0";
  return `₹${num.toLocaleString("en-IN")}`;
}

function perDay(price: string, months: number) {
  const num = Number(price);
  if (!num) return null;
  const days = (months / 12) * 365;
  return (num / days).toFixed(2);
}

export default function SubscriptionPlansPage() {
  const router = useRouter();
  const [plans, setPlans] = useState<SubscriptionPlan[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedPlanId, setSelectedPlanId] = useState<string | null>(null);
  const [upgrading, setUpgrading] = useState<string | null>(null);
  const [user, setUser] = useState<any>(null);
  const [toast, setToast] = useState<{
    type: "success" | "error" | "info";
    msg: string;
  } | null>(null);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [cancelling, setCancelling] = useState(false);

  const currentPlanName = user?.subscriptionPlan || "Free";

  useEffect(() => {
    const saved = localStorage.getItem("user");
    if (saved) {
      try {
        setUser(JSON.parse(saved));
      } catch {}
    }
  }, []);

  useEffect(() => {
    const fetchPlans = async () => {
      try {
        const res = await getSubscriptionPlansApi();
        if (res.status === 1) {
          setPlans(res.data);
        }
      } catch (error) {
        console.error("Error loading subscription plans:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchPlans();
  }, []);

  useEffect(() => {
    if (!toast) return;
    const t = setTimeout(() => setToast(null), 4000);
    return () => clearTimeout(t);
  }, [toast]);

  const handleUpgrade = async () => {
    if (!selectedPlanId) return;
    const plan = plans.find((p) => p.id === selectedPlanId);
    if (!plan) return;
    setUpgrading(plan.id);

    try {
      const createRes = await createSubscriptionApi(plan.id);

      if (createRes.status !== 1) {
        setToast({
          type: "error",
          msg: createRes.msg || "Failed to create subscription",
        });
        setUpgrading(null);
        return;
      }

      const { subscriptionId, razorpayKeyId, planName } = createRes.data;

      const scriptLoaded = await loadRazorpayScript();
      if (!scriptLoaded) {
        setToast({
          type: "error",
          msg: "Unable to load payment gateway. Check your connection.",
        });
        setUpgrading(null);
        return;
      }

      openRazorpay({
        key: razorpayKeyId,
        subscriptionId,
        planName,
        prefillName: user?.name,
        prefillEmail: user?.email,
        prefillContact: user?.phone,
        onSuccess: async (response: RazorpayResponse) => {
          await handleVerify(response, planName);
        },
        onDismiss: () => {
          setToast({ type: "info", msg: "Payment cancelled" });
          setUpgrading(null);
        },
      });
    } catch (error) {
      console.error(error);
      setToast({
        type: "error",
        msg: "Something went wrong. Please try again.",
      });
      setUpgrading(null);
    }
  };

  const handleVerify = async (response: RazorpayResponse, planName: string) => {
    try {
      const verifyRes = await verifyPaymentApi({
        razorpay_payment_id: response.razorpay_payment_id,
        razorpay_subscription_id: response.razorpay_subscription_id,
        razorpay_signature: response.razorpay_signature,
      });

      if (verifyRes.status === 1) {
        setToast({
          type: "success",
          msg: "Subscription activated successfully!",
        });

        const saved = localStorage.getItem("user");
        if (saved) {
          try {
            const parsed = JSON.parse(saved);
            parsed.subscriptionPlan = planName; // use the known plan name, not verifyRes.data
            parsed.razorpaySubscriptionId = verifyRes.data?.subscriptionId;
            parsed.subscriptionEndDate = verifyRes.data?.expiryDate;
            localStorage.setItem("user", JSON.stringify(parsed));
            setUser(parsed);
          } catch {}
        }

        setTimeout(() => {
          router.push("/dashboard");
        }, 1200);
      } else {
        setToast({
          type: "error",
          msg: verifyRes.msg || "Payment verification failed",
        });
      }
    } catch (error) {
      console.error(error);
      setToast({
        type: "error",
        msg: "Payment verification failed. Contact support if amount was debited.",
      });
    } finally {
      setUpgrading(null);
    }
  };

  const handleCancelSubscription = async () => {
    if (!user?.razorpaySubscriptionId) {
      setToast({ type: "error", msg: "No active subscription found" });
      setShowCancelModal(false);
      return;
    }
    setCancelling(true);
    try {
      const res = await cancelSubscriptionApi(user.razorpaySubscriptionId);
      if (res.status === 1) {
        setToast({
          type: "success",
          msg: "Subscription cancelled. Active until end of billing period.",
        });
        const saved = localStorage.getItem("user");
        if (saved) {
          try {
            const parsed = JSON.parse(saved);
            parsed.subscriptionStatus = "cancelled";
            localStorage.setItem("user", JSON.stringify(parsed));
            setUser(parsed);
          } catch {}
        }
      } else {
        setToast({
          type: "error",
          msg: res.msg || "Failed to cancel subscription",
        });
      }
    } catch (err) {
      console.error(err);
      setToast({ type: "error", msg: "Something went wrong" });
    } finally {
      setCancelling(false);
      setShowCancelModal(false);
    }
  };

  const selectedPlan = plans.find((p) => p.id === selectedPlanId);
  const isSelectedCurrent =
    selectedPlan &&
    currentPlanName.toLowerCase() === selectedPlan.plan_name.toLowerCase();

  return (
    <div className="flex min-h-screen bg-[#f7f7f8] font-sans">
      {/* <RazorpayScript /> */}

      <aside className="hidden md:block w-64 shrink-0 bg-white border-r border-[#e5e7eb] sticky top-0 h-screen">
        <Sidebar user={user} />
      </aside>

      <div className="flex-1 flex flex-col min-w-0">
        <header className="h-[72px] flex items-center gap-4 px-7 bg-white border-b border-[#e5e7eb] sticky top-0 z-20">
          <button
            onClick={() => router.back()}
            className="w-9 h-9 rounded-xl bg-[#f7f7f8] flex items-center justify-center text-[#374151] border-none cursor-pointer hover:bg-[#f0f0f0] transition-colors"
          >
            <ArrowLeft size={18} />
          </button>
          <div className="flex items-center gap-3">
            <span className="w-9 h-9 rounded-xl bg-[#fceef3] text-[#d4537e] flex items-center justify-center">
              <Sparkles size={18} />
            </span>
            <div>
              <h1 className="text-base font-semibold text-gray-900 leading-tight">
                Choose your plan
              </h1>
              <p className="text-xs text-gray-400">
                Manage your plans and billing details
              </p>
            </div>
          </div>
        </header>

        <main className="flex-1 py-8 px-4 sm:px-7 pb-32">
          <div className="max-w-[960px] mx-auto flex flex-col gap-7">
            {currentPlanName !== "Free" && (
              <div className="bg-white rounded-3xl border border-[#e5e7eb] shadow-sm px-8 py-6 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                  <p className="text-xs text-[#9ca3af] mb-1">
                    Current Subscription
                  </p>
                  <h3 className="text-lg font-semibold text-[#111111]">
                    {currentPlanName} Plan
                  </h3>
                  <p className="text-sm text-[#6b7280] mt-1">
                    Status:{" "}
                    <span
                      className={`font-medium ${
                        user?.subscriptionStatus === "cancelled"
                          ? "text-red-600"
                          : "text-emerald-600"
                      }`}
                    >
                      {user?.subscriptionStatus === "cancelled"
                        ? "Cancelled"
                        : "Active"}
                    </span>
                  </p>
                  {user?.subscriptionRenewsAt && (
                    <p className="text-sm text-[#9ca3af]">
                      Renews on{" "}
                      {new Date(user.subscriptionRenewsAt).toLocaleDateString(
                        "en-IN",
                      )}
                    </p>
                  )}
                </div>
                {user?.subscriptionStatus !== "cancelled" && (
                  <button
                    onClick={() => setShowCancelModal(true)}
                    className="px-5 py-2.5 rounded-xl text-sm font-medium text-red-600 border border-red-200 bg-red-50 hover:bg-red-100 cursor-pointer"
                  >
                    Cancel Subscription
                  </button>
                )}
              </div>
            )}

            <div className="bg-white rounded-3xl border border-[#e5e7eb] shadow-sm px-8 py-8 text-center">
              <h2 className="text-2xl font-semibold text-[#111111] mb-2">
                Upgrade your practice
              </h2>
              <p className="text-[#6b7280] text-[15px] leading-relaxed">
                Start free. Upgrade anytime. Cancel whenever you want — no
                lock-ins.
              </p>
            </div>

            {loading ? (
              <p className="text-sm text-[#9ca3af] text-center py-10">
                Loading plans...
              </p>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-3 gap-5">
                {plans.map((plan, index) => {
                  const isCurrent =
                    currentPlanName.toLowerCase() ===
                    plan.plan_name.toLowerCase();
                  const isSelected = selectedPlanId === plan.id;

                  return (
                    <PlanCard
                      key={plan.id}
                      plan={plan}
                      isCurrent={isCurrent}
                      isSelected={isSelected}
                      currentPlanName={currentPlanName}
                      onSelect={() => {
                        if (!isCurrent)
                          setSelectedPlanId((prev) =>
                            prev === plan.id ? null : plan.id,
                          );
                      }}
                      previousPlanName={plans[index - 1]?.plan_name}
                    />
                  );
                })}
              </div>
            )}

            <div className="text-center pb-2">
              <button className="text-[15px] font-medium text-[#0e7490] bg-transparent border-none cursor-pointer">
                Restore Purchases
              </button>
              <p className="text-sm text-[#9ca3af] mt-3">
                <span className="cursor-pointer hover:text-[#4b5563]">
                  Privacy Policy
                </span>
                {"  ·  "}
                <span className="cursor-pointer hover:text-[#4b5563]">
                  Terms of Use
                </span>
              </p>
            </div>
          </div>
        </main>

        {selectedPlan && !isSelectedCurrent && (
          <div className="fixed bottom-0 left-0 right-0 md:left-64 bg-white border-t border-[#e5e7eb] px-7 py-4 z-30">
            <div className="max-w-[960px] mx-auto flex items-center justify-between gap-4">
              <div>
                <p className="text-sm font-medium text-[#111111]">
                  {selectedPlan.plan_name} Plan
                  <span className="ml-2 text-[#6b7280] font-normal">
                    {formatPrice(selectedPlan.plan_price)}
                    {Number(selectedPlan.plan_price) > 0
                      ? " / year"
                      : " / forever"}
                  </span>
                </p>
                <p className="text-xs text-[#9ca3af]">
                  Tap to upgrade from {currentPlanName}
                </p>
              </div>
              <button
                onClick={handleUpgrade}
                disabled={!!upgrading}
                className={`px-8 py-3.5 rounded-2xl text-sm font-medium text-white border-none cursor-pointer transition-opacity disabled:opacity-60 disabled:cursor-not-allowed ${
                  selectedPlan.plan_name === "Advanced"
                    ? "bg-indigo-600 hover:bg-indigo-700"
                    : selectedPlan.plan_name === "Elite"
                      ? "bg-amber-700 hover:bg-amber-800"
                      : "bg-sky-600 hover:bg-sky-700"
                }`}
              >
                {upgrading
                  ? "Processing..."
                  : `Upgrade to ${selectedPlan.plan_name}`}
              </button>
            </div>
          </div>
        )}

        {showCancelModal && (
          <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 px-4">
            <div className="bg-white rounded-2xl p-6 max-w-sm w-full">
              <h3 className="text-lg font-semibold mb-2 text-[#111111]">
                Cancel Subscription?
              </h3>
              <p className="text-sm text-[#6b7280] mb-5">
                You'll keep access until the end of your current billing period.
              </p>
              <div className="flex gap-3 justify-end">
                <button
                  onClick={() => setShowCancelModal(false)}
                  className="px-4 py-2 rounded-xl text-sm font-medium text-[#374151] bg-[#f1f2f4] border-none cursor-pointer"
                >
                  Keep Plan
                </button>
                <button
                  onClick={handleCancelSubscription}
                  disabled={cancelling}
                  className="px-4 py-2 rounded-xl text-sm font-medium text-white bg-red-600 border-none cursor-pointer disabled:opacity-60"
                >
                  {cancelling ? "Cancelling..." : "Yes, Cancel"}
                </button>
              </div>
            </div>
          </div>
        )}

        {toast && (
          <div
            className={`fixed top-6 right-6 z-50 px-5 py-3.5 rounded-2xl shadow-lg text-sm font-medium text-white ${
              toast.type === "success"
                ? "bg-emerald-600"
                : toast.type === "error"
                  ? "bg-red-600"
                  : "bg-gray-800"
            }`}
          >
            {toast.msg}
          </div>
        )}
      </div>
    </div>
  );
}

function PlanCard({
  plan,
  isCurrent,
  isSelected,
  onSelect,
  previousPlanName,
  currentPlanName,
}: {
  plan: SubscriptionPlan;
  isCurrent: boolean;
  isSelected: boolean;
  onSelect: () => void;
  previousPlanName?: string;
  currentPlanName: string;
}) {
  const isFree = plan.plan_name === "Free";
  const isAdvanced = plan.plan_name === "Advanced";
  const isElite = plan.plan_name === "Elite";

  const dayRate = perDay(plan.plan_price, plan.plan_duration_months);

  const cardBorderClass = isSelected
    ? isAdvanced
      ? "border-indigo-500 ring-2 ring-indigo-200"
      : isElite
        ? "border-yellow-400 ring-2 ring-yellow-100"
        : "border-sky-400 ring-2 ring-sky-100"
    : isCurrent
      ? isAdvanced
        ? "border-indigo-300"
        : isElite
          ? "border-yellow-300"
          : "border-sky-300"
      : "border-[#e5e7eb]";

  const priceColorClass = isFree
    ? "text-sky-700"
    : isAdvanced
      ? "text-indigo-600"
      : "text-amber-800";

  const tagClass = isFree
    ? "bg-sky-100 text-sky-700"
    : isAdvanced
      ? "bg-indigo-100 text-indigo-700"
      : "bg-yellow-100 text-amber-800";

  const checkBgClass = isFree
    ? "bg-sky-100 text-sky-700"
    : isAdvanced
      ? "bg-indigo-100 text-indigo-700"
      : "bg-yellow-100 text-amber-800";

  const showSwitchNote = !isCurrent && currentPlanName !== "Free" && !isFree;

  return (
    <div
      onClick={onSelect}
      className={`relative bg-white rounded-3xl border-2 ${cardBorderClass} shadow-sm p-6 flex flex-col transition-all ${
        isCurrent ? "cursor-default" : "cursor-pointer hover:shadow-md"
      }`}
    >
      {isCurrent && (
        <div
          className={`absolute -top-3.5 left-1/2 -translate-x-1/2 px-4 py-1 rounded-full text-[11px] font-semibold text-white whitespace-nowrap ${
            isFree
              ? "bg-sky-500"
              : isAdvanced
                ? "bg-indigo-500"
                : "bg-amber-600"
          }`}
        >
          ✓ Current Plan
        </div>
      )}

      {isSelected && (
        <div
          className={`absolute -top-3.5 left-1/2 -translate-x-1/2 px-4 py-1 rounded-full text-[11px] font-semibold text-white whitespace-nowrap ${
            isAdvanced
              ? "bg-indigo-500"
              : isElite
                ? "bg-amber-600"
                : "bg-sky-500"
          }`}
        >
          ✓ Selected
        </div>
      )}

      <div className="flex items-center justify-between mb-5 mt-2">
        <span
          className={`px-3 py-1.5 rounded-full text-xs font-medium ${tagClass}`}
        >
          {plan.plan_name}
        </span>
        {isAdvanced && (
          <span className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border border-indigo-400 text-indigo-600">
            <Star size={12} className="fill-current" />
            Most Popular
          </span>
        )}
        {isElite && (
          <span className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border border-yellow-400 text-amber-800">
            <Crown size={12} className="fill-current" />
            Best Value
          </span>
        )}
      </div>

      <h3 className="text-xl font-semibold text-[#111111] mb-2">
        {plan.plan_name} Plan
      </h3>

      <div className="flex items-baseline gap-1.5 mb-1">
        <span className={`text-3xl font-semibold ${priceColorClass}`}>
          {formatPrice(plan.plan_price)}
        </span>
        <span className="text-[#9ca3af] text-sm">
          {isFree ? "/ forever" : "/ year"}
        </span>
      </div>
      {dayRate && (
        <p className={`text-sm mb-3 ${priceColorClass}`}>≈ ₹{dayRate} / day</p>
      )}

      <p className="text-[#6b7280] text-sm mb-5">
        {isFree
          ? "Everything you need to get started."
          : isElite
            ? "For established practices that need it all."
            : "Perfect for growing practices."}
      </p>

      <div className="h-px bg-[#f1f2f4] mb-4" />

      <p className="text-[10px] font-medium uppercase tracking-wider text-[#9ca3af] mb-3">
        Included features
      </p>

      <div className="flex flex-col gap-3 flex-1">
        {previousPlanName && (
          <div className="flex items-center gap-2.5">
            <Check size={16} className="text-[#111111] flex-shrink-0" />
            <span className="text-sm text-[#6b7280]">
              Everything in {previousPlanName}, plus
            </span>
          </div>
        )}
        {plan.features.map((feature, i) => (
          <div key={i} className="flex items-start gap-2.5">
            <span
              className={`w-5 h-5 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5 ${checkBgClass}`}
            >
              <Check size={11} />
            </span>
            <span className="text-sm text-[#111111]">{feature}</span>
          </div>
        ))}
      </div>

      {isCurrent && (
        <div className="mt-6 w-full py-3.5 rounded-2xl text-sm font-medium text-center bg-[#f1f2f4] text-[#9ca3af]">
          Current Plan
        </div>
      )}

      {showSwitchNote && (
        <p className="text-xs text-[#9ca3af] text-center mt-3">
          Plan switching will be enabled after checkout goes live
        </p>
      )}
    </div>
  );
}
