/**
 * Current Package Card Component
 * Displays the user's current subscription package prominently with full feature list
 */

"use client";

import { useMemo } from "react";
import type { Lang } from "@/lib/config";
import type { DashboardSubscriptionDetails } from "../types";
import { PRICING_TIERS } from "@/lib/config/pricing-tiers";

interface CurrentPackageCardProps {
  lang: Lang;
  subscriptionData: DashboardSubscriptionDetails | null;
  loading: boolean;
  onChangePlan: () => void;
  onViewHistory: () => void;
}

export default function CurrentPackageCard({
  lang,
  subscriptionData,
  loading,
  onChangePlan,
  onViewHistory,
}: CurrentPackageCardProps) {
  const isAr = lang === "ar";

  // Find the current tier details from PRICING_TIERS
  const currentTier = useMemo(() => {
    if (!subscriptionData?.subscription?.tierId) return null;
    return PRICING_TIERS.find(
      (tier) => tier.id === subscriptionData.subscription.tierId,
    );
  }, [subscriptionData]);

  // Calculate yearly savings
  const yearlySavings = useMemo(() => {
    if (
      !currentTier ||
      subscriptionData?.subscription?.billingPeriod !== "yearly"
    ) {
      return null;
    }
    const monthlyTotal = currentTier.priceGBP * 12;
    const yearlyPrice = currentTier.priceGBP * 10; // 2 months free
    return monthlyTotal - yearlyPrice;
  }, [currentTier, subscriptionData]);

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

  // Status color variants for Tailwind JIT compiler
  const statusColorVariants: Record<string, string> = {
    emerald: "bg-emerald-100 text-emerald-700 border-emerald-200",
    blue: "bg-blue-100 text-blue-700 border-blue-200",
    orange: "bg-orange-100 text-orange-700 border-orange-200",
    slate: "bg-slate-100 text-slate-700 border-slate-200",
    red: "bg-red-100 text-red-700 border-red-200",
  };

  // Loading state
  if (loading) {
    return (
      <div className="rounded-2xl bg-white p-8 shadow-lg border border-slate-200">
        <div className="animate-pulse space-y-6">
          <div className="flex items-start justify-between">
            <div className="space-y-3 flex-1">
              <div className="h-4 bg-slate-200 rounded w-32"></div>
              <div className="h-8 bg-slate-200 rounded w-48"></div>
              <div className="h-4 bg-slate-200 rounded w-40"></div>
            </div>
            <div className="h-8 w-24 bg-slate-200 rounded-full"></div>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="h-24 bg-slate-100 rounded-xl"></div>
            <div className="h-24 bg-slate-100 rounded-xl"></div>
          </div>
          <div className="space-y-2">
            {[1, 2, 3, 4, 5].map((i) => (
              <div key={i} className="h-5 bg-slate-100 rounded"></div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  // No subscription state
  if (!subscriptionData || !currentTier) {
    return (
      <div className="rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 p-8 shadow-lg border border-slate-200">
        <div className="text-center space-y-4">
          <div className="w-16 h-16 bg-slate-200 rounded-full mx-auto flex items-center justify-center">
            <svg
              className="w-8 h-8 text-slate-400"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"
              />
            </svg>
          </div>
          <div>
            <h3 className="text-xl font-bold text-slate-900">
              {isAr ? "لا يوجد اشتراك نشط" : "No Active Subscription"}
            </h3>
            <p className="text-sm text-slate-600 mt-2">
              {isAr
                ? "يرجى اختيار خطة للبدء في استخدام منصة موعدي"
                : "Please choose a plan to start using the Mawidi platform"}
            </p>
          </div>
        </div>
      </div>
    );
  }

  const { subscription } = subscriptionData;
  const status = statusLabels[subscription.status] || {
    en: subscription.status,
    ar: subscription.status,
    color: "slate",
  };

  // Get tier name and features
  const tierName = isAr ? currentTier.nameAr : currentTier.nameEn;
  const features = isAr ? currentTier.featuresAr : currentTier.featuresEn;

  // Calculate price display
  const monthlyPrice = currentTier.priceGBP;
  const displayPrice =
    subscription.billingPeriod === "yearly"
      ? monthlyPrice * 10 // Yearly price (10 months)
      : monthlyPrice;

  // Format renewal date
  const renewalDate = subscription.trialEndsAt || subscription.currentPeriodEnd;
  const formattedDate = new Date(renewalDate).toLocaleDateString(
    isAr ? "ar-SA" : "en-US",
    { month: "long", day: "numeric", year: "numeric" },
  );

  return (
    <div className="rounded-2xl bg-gradient-to-br from-white via-emerald-50/30 to-white p-8 shadow-lg border-2 border-emerald-200/50 hover:shadow-xl transition-shadow duration-300">
      {/* Header Section */}
      <div className="flex items-start justify-between mb-6">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-brand-green to-emerald-600 flex items-center justify-center shadow-md">
              <svg
                className="w-7 h-7 text-white"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"
                />
              </svg>
            </div>
            <div>
              <p className="text-xs font-medium text-slate-500 uppercase tracking-wide">
                {isAr ? "خطتك الحالية" : "Current Plan"}
              </p>
              <h2 className="text-3xl font-bold text-slate-900 mt-0.5">
                {tierName}
              </h2>
            </div>
          </div>
          {currentTier.popular && (
            <span className="inline-flex items-center gap-1 px-3 py-1 rounded-full bg-amber-100 text-amber-700 text-xs font-semibold border border-amber-200">
              <svg
                className="w-3.5 h-3.5"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
              </svg>
              {isAr ? "الأكثر شيوعاً" : "Most Popular"}
            </span>
          )}
        </div>
        <div>
          <span
            className={`inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-sm font-semibold border ${statusColorVariants[status.color] || statusColorVariants.slate}`}
          >
            <span className="w-2 h-2 rounded-full bg-current animate-pulse"></span>
            {isAr ? status.ar : status.en}
          </span>
        </div>
      </div>

      {/* Price Section */}
      <div className="mb-6 pb-6 border-b border-slate-200">
        <div className="flex items-baseline gap-2">
          <span className="text-4xl font-bold text-slate-900">
            £{displayPrice}
          </span>
          <span className="text-lg text-slate-600">
            {subscription.billingPeriod === "yearly"
              ? isAr
                ? "/ سنوياً"
                : "/ year"
              : isAr
                ? "/ شهرياً"
                : "/ month"}
          </span>
        </div>

        {subscription.billingPeriod === "yearly" && yearlySavings && (
          <div className="mt-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-emerald-100 border border-emerald-200">
            <svg
              className="w-4 h-4 text-emerald-700"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
            <span className="text-sm font-semibold text-emerald-700">
              {isAr
                ? `توفير £${yearlySavings} سنوياً`
                : `Save £${yearlySavings} per year`}
            </span>
          </div>
        )}

        <div className="mt-4 flex items-center gap-2 text-sm text-slate-600">
          <svg
            className="w-4 h-4"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
            />
          </svg>
          <span>
            {subscription.trialEndsAt
              ? isAr
                ? "تنتهي الفترة التجريبية في"
                : "Trial ends on"
              : isAr
                ? "التجديد التالي في"
                : "Next renewal on"}{" "}
            <span className="font-semibold text-slate-900">
              {formattedDate}
            </span>
          </span>
        </div>

        {subscription.cancelAtPeriodEnd && (
          <div className="mt-3 flex items-start gap-2 p-3 rounded-lg bg-orange-50 border border-orange-200">
            <svg
              className="w-5 h-5 text-orange-600 flex-shrink-0 mt-0.5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
              />
            </svg>
            <div>
              <p className="text-sm font-semibold text-orange-900">
                {isAr ? "الإلغاء المجدول" : "Scheduled Cancellation"}
              </p>
              <p className="text-xs text-orange-700 mt-0.5">
                {isAr
                  ? `سيتم إلغاء اشتراكك في ${formattedDate}`
                  : `Your subscription will cancel on ${formattedDate}`}
              </p>
            </div>
          </div>
        )}
      </div>

      {/* Features Section */}
      <div className="mb-6">
        <h3 className="text-sm font-bold text-slate-900 uppercase tracking-wide mb-4 flex items-center gap-2">
          <svg
            className="w-4 h-4 text-emerald-600"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"
            />
          </svg>
          {isAr ? "الميزات المضمنة" : "Included Features"}
        </h3>
        <div className="grid gap-2.5">
          {features.map((feature, index) => (
            <div
              key={index}
              className="flex items-start gap-3 p-2.5 rounded-lg hover:bg-emerald-50/50 transition-colors"
            >
              <div className="flex-shrink-0 w-5 h-5 rounded-full bg-emerald-100 flex items-center justify-center mt-0.5">
                <svg
                  className="w-3.5 h-3.5 text-emerald-700"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={3}
                    d="M5 13l4 4L19 7"
                  />
                </svg>
              </div>
              <span className="text-sm text-slate-700 leading-relaxed flex-1">
                {feature}
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* Setup Fee Info */}
      {subscription.setupFeePaid && subscription.setupFeeAmount && (
        <div className="mb-6 p-4 rounded-xl bg-gradient-to-r from-slate-50 to-slate-100 border border-slate-200">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-white shadow-sm flex items-center justify-center">
                <svg
                  className="w-5 h-5 text-emerald-600"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                  />
                </svg>
              </div>
              <div>
                <p className="text-sm font-semibold text-slate-900">
                  {isAr ? "رسوم الإعداد مدفوعة" : "Setup Fee Paid"}
                </p>
                <p className="text-xs text-slate-600">
                  £{(subscription.setupFeeAmount / 100).toFixed(2)}
                  {subscription.setupFeePaidAt && (
                    <span className="mx-1">•</span>
                  )}
                  {subscription.setupFeePaidAt &&
                    new Date(subscription.setupFeePaidAt).toLocaleDateString(
                      isAr ? "ar-SA" : "en-US",
                      { month: "short", day: "numeric", year: "numeric" },
                    )}
                </p>
              </div>
            </div>
            <span className="text-emerald-600 text-2xl">✓</span>
          </div>
        </div>
      )}

      {/* Action Buttons */}
      <div className="flex flex-col sm:flex-row gap-3">
        <button
          onClick={onChangePlan}
          className="flex-1 flex items-center justify-center gap-2 px-5 py-3.5 rounded-xl bg-gradient-to-r from-brand-green to-emerald-600 text-white font-semibold text-sm shadow-lg shadow-emerald-200 hover:shadow-xl hover:scale-[1.02] transition-all duration-200"
        >
          <svg
            className="w-5 h-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"
            />
          </svg>
          {isAr ? "تغيير الخطة" : "Change Plan"}
        </button>
        <button
          onClick={onViewHistory}
          className="flex-1 flex items-center justify-center gap-2 px-5 py-3.5 rounded-xl bg-white border-2 border-slate-300 text-slate-700 font-semibold text-sm hover:border-brand-green hover:text-brand-green hover:bg-emerald-50/50 transition-all duration-200"
        >
          <svg
            className="w-5 h-5"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
            />
          </svg>
          {isAr ? "سجل الفواتير" : "Billing History"}
        </button>
      </div>

      {/* Additional Info Footer */}
      <div className="mt-6 pt-6 border-t border-slate-200">
        <div className="flex items-center justify-between text-xs text-slate-500">
          <div className="flex items-center gap-1.5">
            <svg
              className="w-3.5 h-3.5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
            <span>{isAr ? "معرف الاشتراك:" : "Subscription ID:"}</span>
          </div>
          <span className="font-mono text-[10px] bg-slate-100 px-2 py-1 rounded">
            {subscription.id.slice(0, 8)}...
          </span>
        </div>
      </div>
    </div>
  );
}
