import { Crown, Calendar, Check, X } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@/lib/queryClient";
import { useAuth } from "@/contexts/auth-context";
import type { SubscriptionResponse } from "@/types/types";
import { useLocation } from "wouter";
import { useTranslation } from "@/lib/i18n";

export default function BillingSubscriptionPage() {
  const { t } = useTranslation();
  const { user, currency, currencySymbol } = useAuth();
  const [, setLocation] = useLocation();

  const {
    data: activeplandata,
    isLoading,
    isError,
  } = useQuery<SubscriptionResponse>({
    queryKey: [`api/subscriptions/user/${user?.id}`],
    queryFn: () =>
      apiRequest("GET", `api/subscriptions/user/${user?.id}`).then((res) =>
        res.json()
      ),
    enabled: !!user?.id,
  });

  if (isLoading) {
    return (
      <div className="flex-1 min-h-screen flex items-center justify-center p-4 bg-white text-gray-700">
        <p>{t("billing_subscription.loading")}</p>
      </div>
    );
  }


  console.log("Active Plan Data:", activeplandata);

  return (
    <div className="flex-1 bg-white text-gray-900 dots-bg">
      <div className="p-6 pb-0 bg-white border">
        <div className="flex items-center gap-3 mb-2">
          <div className="p-2 bg-green-100 rounded-lg">
            <Crown className="w-6 h-6 text-green-600" />
          </div>
          <h2 className="text-2xl font-bold text-gray-900">
            Active Plan Details
          </h2>
        </div>
        <p className="text-gray-500 text-sm ml-14 pb-2">
          View and manage your current subscription plans
        </p>
      </div>
      <main className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-6 p-6">
        {isError ||
        !activeplandata?.success ||
        activeplandata.data.length === 0 ? (
          <div className="col-span-full flex flex-col items-center justify-center py-16 bg-white rounded-2xl border border-gray-200 shadow-sm">
            <div className="p-4 bg-gray-100 rounded-full">
              <svg
                className="w-10 h-10 text-gray-500"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M9 13h6m-3-3v6m9 1V7a2 2 0 00-2-2h-3.5L14 3H10L8.5 5H5a2 2 0 00-2 2v10a2 2 0 002 2h14a2 2 0 002-2z"
                />
              </svg>
            </div>

            <h3 className="mt-4 text-lg font-semibold text-gray-800">
              {t("billing_subscription.noSubscription.title")}
            </h3>
            <p className="text-gray-500 text-sm mt-1">
              {t("billing_subscription.noSubscription.description")}
            </p>

            <button
              className="mt-6 px-5 py-2.5 text-sm font-medium bg-green-700 text-white rounded-xl hover:bg-green-800"
              onClick={() => setLocation("/plan-upgrade")}
            >
              {t("billing_subscription.noSubscription.upgradePlan")}
            </button>
          </div>
        ) : (
          activeplandata.data.map((item) => {
            const subscription = item.subscription;
            const planData = subscription.planData;
            const renewsDate = subscription.endDate
              ? new Date(subscription.endDate).toLocaleDateString()
              : "-";
            const startDate = subscription.startDate
              ? new Date(subscription.startDate).toLocaleDateString()
              : "-";

            return (
              <div
                key={subscription.id}
                className="bg-white rounded-xl shadow-lg border border-gray-200 hover:shadow-xl transition-all duration-300 overflow-hidden flex flex-col h-full max-w-sm"
              >
                {/* Header with gradient */}
                <div className="bg-gradient-to-r from-green-600 to-green-700 text-white p-4 relative">
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <Crown className="w-5 h-5 text-yellow-300" />
                      <h2 className="text-lg font-bold">{planData.name}</h2>
                    </div>
                    <span className="bg-white/20 backdrop-blur-sm text-white text-xs font-semibold rounded-full px-2.5 py-1 capitalize">
                      {subscription.status}
                    </span>
                  </div>
                  <p className="text-green-100 text-xs line-clamp-2">
                    {planData.description}
                  </p>
                </div>

                {/* Body Content */}
                <div className="p-4 flex-grow flex flex-col space-y-4">
                  {/* Date Info - Compact */}
                  <div className="grid grid-cols-3 gap-2 text-xs">
                    <div className="bg-blue-50 rounded-lg p-2 text-center">
                      <Calendar className="w-3.5 h-3.5 text-blue-600 mx-auto mb-1" />
                      <p className="text-gray-500 text-[10px] mb-0.5">
                        {t("billing_subscription.card.billing")}
                      </p>
                      <p className="font-semibold text-gray-800 capitalize truncate">
                        {subscription.billingCycle}
                      </p>
                    </div>
                    <div className="bg-green-50 rounded-lg p-2 text-center">
                      <Calendar className="w-3.5 h-3.5 text-green-600 mx-auto mb-1" />
                      <p className="text-gray-500 text-[10px] mb-0.5">
                        {t("billing_subscription.card.starts")}
                      </p>
                      <p className="font-semibold text-gray-800 text-[10px]">
                        {startDate}
                      </p>
                    </div>
                    <div className="bg-purple-50 rounded-lg p-2 text-center">
                      <Calendar className="w-3.5 h-3.5 text-purple-600 mx-auto mb-1" />
                      <p className="text-gray-500 text-[10px] mb-0.5">
                        {t("billing_subscription.card.renews")}
                      </p>
                      <p className="font-semibold text-gray-800 text-[10px]">
                        {renewsDate}
                      </p>
                    </div>
                  </div>

                  {/* Pricing */}
                  <div>
                    <h3 className="text-xs font-semibold text-gray-700 mb-2">
                      {t("billing_subscription.card.pricing")}
                    </h3>
                    <div className="flex gap-2">
                      <div className="flex-1 bg-gradient-to-br from-yellow-100 to-orange-100 border border-yellow-200 rounded-lg px-3 py-2 text-center">
                        <p className="text-[10px] text-gray-600">
                          {t("billing_subscription.card.monthly")}
                        </p>
                        <p className="text-sm font-bold text-yellow-700">
                          {currencySymbol} {planData.monthlyPrice}
                        </p>
                      </div>
                      <div className="flex-1 bg-gradient-to-br from-green-100 to-emerald-100 border border-green-200 rounded-lg px-3 py-2 text-center">
                        <p className="text-[10px] text-gray-600">
                          {t("billing_subscription.card.annual")}
                        </p>
                        <p className="text-sm font-bold text-green-700">
                          {currencySymbol} {planData.annualPrice}
                        </p>
                      </div>
                    </div>
                  </div>

                  {/* Permissions */}
                  {planData.permissions && (
                    <div>
                      <h3 className="text-xs font-semibold text-gray-700 mb-2">
                        {t("billing_subscription.card.details")}
                      </h3>
                      <div className="flex flex-wrap gap-1.5">
                        {Object.entries(planData.permissions).map(
                          ([key, value]) => (
                            <div
                              key={key}
                              className="flex items-center gap-1 text-[10px] bg-gray-100 rounded-md px-2 py-1"
                            >
                              <Check className="w-3 h-3 text-green-600" />
                              <span className="text-gray-700 capitalize">
                                {value} {key}
                              </span>
                            </div>
                          )
                        )}
                      </div>
                    </div>
                  )}

                  {/* Features - Scrollable */}
                  <div className="flex-grow">
                    <h3 className="text-xs font-semibold text-gray-700 mb-2">
                      {t("billing_subscription.card.features")}
                    </h3>
                    <ul className="space-y-1.5 max-h-32 overflow-y-auto pr-1 custom-scrollbar">
                      {planData.features.map((feature, idx) => (
                        <li
                          key={idx}
                          className={`flex items-start gap-1.5 text-xs ${
                            feature.included
                              ? "text-gray-700"
                              : "text-gray-400 line-through"
                          }`}
                        >
                          {feature.included ? (
                            <Check className="w-3.5 h-3.5 text-green-500 flex-shrink-0 mt-0.5" />
                          ) : (
                            <X className="w-3.5 h-3.5 text-gray-400 flex-shrink-0 mt-0.5" />
                          )}
                          <span className="leading-tight">{feature.name}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>

                {/* Footer Button */}
                {/* <div className="p-4 pt-0 border-t border-gray-100">
                  <button
                    onClick={() => setLocation("/plan-upgrade")}
                    className="w-full py-2 bg-gradient-to-r from-green-600 to-green-700 text-white text-sm font-semibold rounded-lg hover:from-green-700 hover:to-green-800 transition-all shadow-sm hover:shadow-md"
                  >
                    Manage Plan
                  </button>
                </div> */}
              </div>
            );
          })
        )}
      </main>

      {/* Custom Scrollbar */}
      <style>{`
        .custom-scrollbar::-webkit-scrollbar {
          width: 3px;
        }
        .custom-scrollbar::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 10px;
        }
        .custom-scrollbar::-webkit-scrollbar-thumb {
          background: #10b981;
          border-radius: 10px;
        }
      `}</style>
    </div>
  );
}
