/**
 * Current Plan Card Component
 * Displays user's current subscription plan using /api/billing/current
 * Shows plan details, features, billing cycle, and days remaining
 */

"use client";

import { useEffect, useState } from "react";
import type { Lang } from "@/lib/config";

interface PlanDetails {
  type: string;
  name: string;
  nameAr: string;
  monthlyPrice: number;
  features: string[];
  featuresAr: string[];
}

interface CurrentSubscription {
  id: string;
  planType: string;
  status: string;
  currentPeriodStart: string;
  currentPeriodEnd: string;
  cancelAtPeriodEnd: boolean;
  amount: number;
  currency: string;
  daysRemaining: number;
  daysInPeriod: number;
  daysUsed: number;
  planDetails: PlanDetails;
}

interface CurrentPlanData {
  hasSubscription: boolean;
  subscription: CurrentSubscription;
}

interface CurrentPlanCardProps {
  lang: Lang;
  onUpgradeClick?: () => void;
}

export default function CurrentPlanCard({
  lang,
  onUpgradeClick,
}: CurrentPlanCardProps) {
  const [data, setData] = useState<CurrentPlanData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const isAr = lang === "ar";

  useEffect(() => {
    async function fetchCurrentPlan() {
      try {
        const response = await fetch("/api/billing/current");

        if (!response.ok) {
          if (response.status === 404) {
            setError(isAr ? "لا يوجد اشتراك نشط" : "No active subscription");
          } else {
            const errorData = await response.json();
            throw new Error(errorData.error || "Failed to fetch plan");
          }
          return;
        }

        const result = await response.json();
        setData(result);
      } catch (err) {
        console.error("Error fetching current plan:", err);
        setError(isAr ? "فشل تحميل بيانات الخطة" : "Failed to load plan data");
      } finally {
        setLoading(false);
      }
    }

    fetchCurrentPlan();
  }, [isAr]);

  if (loading) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <div className="animate-pulse space-y-4">
          <div className="h-6 bg-slate-200 rounded w-1/3"></div>
          <div className="h-8 bg-slate-200 rounded w-1/2"></div>
          <div className="space-y-2">
            <div className="h-4 bg-slate-100 rounded"></div>
            <div className="h-4 bg-slate-100 rounded"></div>
            <div className="h-4 bg-slate-100 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !data?.hasSubscription) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <div className="text-center py-8">
          <div className="text-4xl mb-4">📦</div>
          <p className="text-sm text-slate-600 mb-4">
            {error || (isAr ? "لا يوجد اشتراك نشط" : "No active subscription")}
          </p>
          <a
            href={`/${lang}/pricing`}
            className="inline-block rounded-lg bg-brand-green px-6 py-2.5 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
          >
            {isAr ? "اختر خطة" : "Choose a Plan"}
          </a>
        </div>
      </div>
    );
  }

  const { subscription } = data;
  const plan = subscription.planDetails;

  // Calculate progress percentage
  const progressPercent =
    (subscription.daysUsed / subscription.daysInPeriod) * 100;

  // Status colors
  const statusColors: Record<string, string> = {
    active: "bg-emerald-100 text-emerald-700 border-emerald-200",
    trialing: "bg-blue-100 text-blue-700 border-blue-200",
    past_due: "bg-orange-100 text-orange-700 border-orange-200",
    canceled: "bg-slate-100 text-slate-700 border-slate-200",
    unpaid: "bg-red-100 text-red-700 border-red-200",
  };

  const statusColor = statusColors[subscription.status] || statusColors.active;

  // Status labels
  const statusLabels: Record<string, { en: string; ar: string }> = {
    active: { en: "Active", ar: "نشط" },
    trialing: { en: "Trial", ar: "تجريبي" },
    past_due: { en: "Past Due", ar: "متأخر" },
    canceled: { en: "Canceled", ar: "ملغى" },
    unpaid: { en: "Unpaid", ar: "غير مدفوع" },
  };

  const statusLabel = statusLabels[subscription.status] || {
    en: subscription.status,
    ar: subscription.status,
  };

  return (
    <div className="space-y-4">
      {/* Main Plan Card */}
      <div className="rounded-xl bg-gradient-to-br from-brand-green via-emerald-600 to-teal-600 p-6 text-white shadow-lg">
        <div className="flex items-start justify-between mb-4">
          <div className="flex-1">
            <p className="text-xs font-medium text-emerald-100 uppercase tracking-wide">
              {isAr ? "خطتك الحالية" : "Current Plan"}
            </p>
            <h2 className="mt-2 text-3xl font-bold">
              {isAr ? plan.nameAr : plan.name}
            </h2>
            <p className="mt-2 text-xl font-semibold text-emerald-50">
              ${subscription.amount.toFixed(2)}{" "}
              {subscription.currency.toUpperCase()}
              <span className="text-sm font-normal text-emerald-100">
                /{isAr ? "شهر" : "month"}
              </span>
            </p>
          </div>
          <span
            className={`rounded-full px-3 py-1.5 text-xs font-semibold border ${statusColor}`}
          >
            {isAr ? statusLabel.ar : statusLabel.en}
          </span>
        </div>

        {/* Billing Cycle Progress */}
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-emerald-100">
              {isAr ? "دورة الفوترة" : "Billing Cycle"}
            </span>
            <span className="font-semibold">
              {subscription.daysRemaining}{" "}
              {isAr ? "يوم متبقي" : "days remaining"}
            </span>
          </div>

          {/* Progress Bar */}
          <div className="relative h-2 bg-white/20 rounded-full overflow-hidden">
            <div
              className="absolute top-0 left-0 h-full bg-white/90 transition-all duration-500"
              style={{ width: `${progressPercent}%` }}
            />
          </div>

          <div className="flex items-center justify-between text-xs text-emerald-100">
            <span>
              {new Date(subscription.currentPeriodStart).toLocaleDateString(
                isAr ? "ar-SA" : "en-US",
                { month: "short", day: "numeric" },
              )}
            </span>
            <span>
              {new Date(subscription.currentPeriodEnd).toLocaleDateString(
                isAr ? "ar-SA" : "en-US",
                { month: "short", day: "numeric", year: "numeric" },
              )}
            </span>
          </div>
        </div>

        {/* Cancellation Warning */}
        {subscription.cancelAtPeriodEnd && (
          <div className="mt-4 rounded-lg bg-orange-500/30 border border-orange-300/40 px-4 py-3">
            <div className="flex items-start gap-2">
              <span className="text-lg">⚠️</span>
              <div className="flex-1">
                <p className="text-sm font-semibold">
                  {isAr ? "سيتم إلغاء الاشتراك" : "Subscription Ending"}
                </p>
                <p className="text-xs mt-1 text-orange-100">
                  {isAr
                    ? `سينتهي الوصول في ${new Date(subscription.currentPeriodEnd).toLocaleDateString("ar-SA")}`
                    : `Access ends ${new Date(subscription.currentPeriodEnd).toLocaleDateString("en-US")}`}
                </p>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Plan Features Card */}
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <h3 className="text-sm font-semibold text-slate-900 mb-4">
          {isAr ? "مميزات الخطة" : "Plan Features"}
        </h3>

        <div className="space-y-3">
          {(isAr ? plan.featuresAr : plan.features).map((feature, index) => (
            <div key={index} className="flex items-start gap-3">
              <span className="flex-shrink-0 flex items-center justify-center w-5 h-5 rounded-full bg-emerald-100 text-emerald-600 text-xs">
                ✓
              </span>
              <span className="text-sm text-slate-700 flex-1">{feature}</span>
            </div>
          ))}
        </div>

        {/* Action Buttons */}
        <div className="mt-6 flex flex-wrap gap-3">
          <button
            onClick={onUpgradeClick}
            className="flex-1 sm:flex-none rounded-lg bg-brand-green px-6 py-2.5 text-sm font-semibold text-white hover:bg-brand-greenHover transition-colors"
          >
            {isAr ? "⬆️ ترقية الخطة" : "⬆️ Upgrade Plan"}
          </button>
          <a
            href={`/${lang}/pricing`}
            className="flex-1 sm:flex-none rounded-lg border border-slate-200 bg-white px-6 py-2.5 text-sm font-medium text-slate-700 hover:border-brand-green hover:text-brand-green transition-colors text-center"
          >
            {isAr ? "📊 مقارنة الخطط" : "📊 Compare Plans"}
          </a>
        </div>
      </div>
    </div>
  );
}
