/**
 * Plan Options Card Component
 * Shows available upgrade/downgrade options with proration calculations
 * Uses /api/billing/plans (GET) and /api/billing/change-plan (POST)
 */

"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 ProrationCalculation {
  currentPlan: PlanDetails;
  newPlan: PlanDetails;
  daysRemaining: number;
  daysInPeriod: number;
  creditFromCurrentPlan: number;
  chargeForNewPlan: number;
  immediateCharge: number;
  nextBillingAmount: number;
  isUpgrade: boolean;
}

interface PlanOption {
  type: string;
  name: string;
  nameAr: string;
  monthlyPrice: number;
  features: string[];
  featuresAr: string[];
  proration: ProrationCalculation;
}

interface PlanOptionsData {
  current: PlanDetails;
  upgrades: PlanOption[];
  downgrades: PlanOption[];
}

interface PlanOptionsCardProps {
  lang: Lang;
  onPlanChanged?: () => void;
}

export default function PlanOptionsCard({
  lang,
  onPlanChanged,
}: PlanOptionsCardProps) {
  const [data, setData] = useState<PlanOptionsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedPlan, setSelectedPlan] = useState<PlanOption | null>(null);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [csrfToken, setCsrfToken] = useState<string>("");

  const isAr = lang === "ar";

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

        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.error || "Failed to fetch plans");
        }

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

    // Fetch CSRF token
    async function fetchCsrfToken() {
      try {
        const response = await fetch("/api/csrf-token");
        const data = await response.json();
        setCsrfToken(data.csrfToken);
      } catch (err) {
        console.error("Failed to fetch CSRF token:", err);
      }
    }

    fetchPlans();
    fetchCsrfToken();
  }, [isAr]);

  const handlePlanSelect = (plan: PlanOption) => {
    setSelectedPlan(plan);
    setShowConfirmModal(true);
  };

  const handleConfirmChange = async () => {
    if (!selectedPlan || !csrfToken) return;

    setSubmitting(true);
    setError(null);

    try {
      const response = await fetch("/api/billing/change-plan", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-csrf-token": csrfToken,
        },
        body: JSON.stringify({
          newPlanType: selectedPlan.type,
          prorationBehavior: "create_prorations",
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to change plan");
      }

      const result = await response.json();

      // Show success message
      alert(
        isAr
          ? `✅ تم ${result.isUpgrade ? "ترقية" : "تخفيض"} الخطة بنجاح!`
          : `✅ Plan ${result.isUpgrade ? "upgraded" : "downgraded"} successfully!`,
      );

      setShowConfirmModal(false);
      setSelectedPlan(null);

      // Callback to refresh parent data
      onPlanChanged?.();
    } catch (err) {
      console.error("Error changing plan:", err);
      setError(
        err instanceof Error
          ? err.message
          : isAr
            ? "فشل تغيير الخطة"
            : "Failed to change plan",
      );
    } finally {
      setSubmitting(false);
    }
  };

  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/4"></div>
          <div className="grid gap-4 md:grid-cols-2">
            <div className="h-48 bg-slate-100 rounded-lg"></div>
            <div className="h-48 bg-slate-100 rounded-lg"></div>
          </div>
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
        <p className="text-sm text-slate-600 text-center">
          {error ||
            (isAr ? "فشل تحميل خيارات الخطط" : "Failed to load plan options")}
        </p>
      </div>
    );
  }

  const hasOptions = data.upgrades.length > 0 || data.downgrades.length > 0;

  if (!hasOptions) {
    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">
            {isAr
              ? "أنت على أفضل خطة متاحة حاليًا!"
              : "You are on the best plan available!"}
          </p>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className="space-y-6">
        {/* Upgrades Section */}
        {data.upgrades.length > 0 && (
          <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
            <h3 className="text-lg font-bold text-slate-900 mb-4">
              {isAr ? "⬆️ ترقية الخطة" : "⬆️ Upgrade Options"}
            </h3>

            <div className="space-y-4">
              {data.upgrades.map((plan) => (
                <PlanOptionItem
                  key={plan.type}
                  plan={plan}
                  lang={lang}
                  isUpgrade={true}
                  onSelect={() => handlePlanSelect(plan)}
                />
              ))}
            </div>
          </div>
        )}

        {/* Downgrades Section */}
        {data.downgrades.length > 0 && (
          <div className="rounded-xl bg-white p-6 shadow-sm border border-slate-200">
            <h3 className="text-lg font-bold text-slate-900 mb-4">
              {isAr ? "⬇️ تخفيض الخطة" : "⬇️ Downgrade Options"}
            </h3>

            <div className="space-y-4">
              {data.downgrades.map((plan) => (
                <PlanOptionItem
                  key={plan.type}
                  plan={plan}
                  lang={lang}
                  isUpgrade={false}
                  onSelect={() => handlePlanSelect(plan)}
                />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Confirmation Modal */}
      {showConfirmModal && selectedPlan && (
        <ConfirmationModal
          plan={selectedPlan}
          lang={lang}
          submitting={submitting}
          error={error}
          onConfirm={handleConfirmChange}
          onCancel={() => {
            setShowConfirmModal(false);
            setSelectedPlan(null);
            setError(null);
          }}
        />
      )}
    </>
  );
}

// Plan Option Item Component
function PlanOptionItem({
  plan,
  lang,
  isUpgrade,
  onSelect,
}: {
  plan: PlanOption;
  lang: Lang;
  isUpgrade: boolean;
  onSelect: () => void;
}) {
  const isAr = lang === "ar";
  const { proration } = plan;

  return (
    <div className="rounded-lg border border-slate-200 p-4 hover:border-brand-green transition-colors">
      <div className="flex items-start justify-between mb-3">
        <div className="flex-1">
          <h4 className="text-base font-semibold text-slate-900">
            {isAr ? plan.nameAr : plan.name}
          </h4>
          <p className="text-2xl font-bold text-brand-green mt-1">
            ${plan.monthlyPrice}
            <span className="text-sm font-normal text-slate-500">
              /{isAr ? "شهر" : "mo"}
            </span>
          </p>
        </div>
        <button
          onClick={onSelect}
          className={`rounded-lg px-4 py-2 text-sm font-semibold text-white transition-colors ${
            isUpgrade
              ? "bg-brand-green hover:bg-brand-greenHover"
              : "bg-slate-600 hover:bg-slate-700"
          }`}
        >
          {isUpgrade
            ? isAr
              ? "ترقية"
              : "Upgrade"
            : isAr
              ? "تخفيض"
              : "Downgrade"}
        </button>
      </div>

      {/* Proration Details */}
      <div className="rounded-lg bg-slate-50 p-3 space-y-2 text-xs">
        <div className="flex justify-between">
          <span className="text-slate-600">
            {isAr ? "رصيد من الخطة الحالية" : "Credit from current plan"}
          </span>
          <span className="font-semibold text-emerald-600">
            ${proration.creditFromCurrentPlan.toFixed(2)}
          </span>
        </div>
        <div className="flex justify-between">
          <span className="text-slate-600">
            {isAr ? "رسوم الخطة الجديدة" : "Charge for new plan"}
          </span>
          <span className="font-semibold text-slate-900">
            ${proration.chargeForNewPlan.toFixed(2)}
          </span>
        </div>
        <div className="border-t border-slate-200 pt-2 flex justify-between">
          <span className="font-semibold text-slate-700">
            {isAr ? "الرسوم الفورية" : "Immediate Charge"}
          </span>
          <span
            className={`font-bold text-base ${
              proration.immediateCharge < 0
                ? "text-emerald-600"
                : "text-slate-900"
            }`}
          >
            {proration.immediateCharge < 0 && "+"}$
            {Math.abs(proration.immediateCharge).toFixed(2)}
            {proration.immediateCharge < 0 && (
              <span className="text-xs font-normal ml-1">
                ({isAr ? "رصيد" : "credit"})
              </span>
            )}
          </span>
        </div>
        <div className="flex justify-between text-slate-500">
          <span>{isAr ? "الفاتورة القادمة" : "Next billing"}</span>
          <span className="font-medium">
            ${proration.nextBillingAmount.toFixed(2)}
          </span>
        </div>
        <div className="text-[10px] text-slate-400">
          {isAr
            ? `${proration.daysRemaining} يوم متبقي من ${proration.daysInPeriod} يوم`
            : `${proration.daysRemaining} days remaining of ${proration.daysInPeriod} days`}
        </div>
      </div>

      {/* Top Features Preview */}
      <div className="mt-3 space-y-1">
        {(isAr ? plan.featuresAr : plan.features)
          .slice(0, 3)
          .map((feature, index) => (
            <div
              key={index}
              className="flex items-center gap-2 text-xs text-slate-600"
            >
              <span className="text-brand-green">✓</span>
              <span>{feature}</span>
            </div>
          ))}
        {plan.features.length > 3 && (
          <p className="text-xs text-slate-400 mt-1">
            {isAr
              ? `و ${plan.features.length - 3} ميزة أخرى...`
              : `+${plan.features.length - 3} more features...`}
          </p>
        )}
      </div>
    </div>
  );
}

// Confirmation Modal Component
function ConfirmationModal({
  plan,
  lang,
  submitting,
  error,
  onConfirm,
  onCancel,
}: {
  plan: PlanOption;
  lang: Lang;
  submitting: boolean;
  error: string | null;
  onConfirm: () => void;
  onCancel: () => void;
}) {
  const isAr = lang === "ar";
  const { proration } = plan;
  const isUpgrade = proration.isUpgrade;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/70 px-4 backdrop-blur-sm">
      <div className="w-full max-w-lg rounded-2xl bg-white p-6 shadow-2xl">
        <h3 className="text-xl font-bold text-slate-900 mb-2">
          {isUpgrade
            ? isAr
              ? "⬆️ تأكيد الترقية"
              : "⬆️ Confirm Upgrade"
            : isAr
              ? "⬇️ تأكيد التخفيض"
              : "⬇️ Confirm Downgrade"}
        </h3>

        <div className="mb-4 p-4 rounded-lg bg-slate-50 space-y-3">
          <div className="flex justify-between items-baseline">
            <span className="text-sm text-slate-600">
              {isAr ? "من:" : "From:"}
            </span>
            <span className="text-base font-semibold text-slate-900">
              {isAr ? proration.currentPlan.nameAr : proration.currentPlan.name}
            </span>
          </div>
          <div className="flex justify-center">
            <span className="text-2xl text-brand-green">↓</span>
          </div>
          <div className="flex justify-between items-baseline">
            <span className="text-sm text-slate-600">
              {isAr ? "إلى:" : "To:"}
            </span>
            <span className="text-base font-semibold text-brand-green">
              {isAr ? plan.nameAr : plan.name}
            </span>
          </div>
        </div>

        {/* Proration Breakdown */}
        <div className="mb-4 rounded-lg border border-slate-200 p-4 space-y-2 text-sm">
          <p className="font-semibold text-slate-900 mb-3">
            {isAr ? "تفاصيل الرسوم" : "Charge Breakdown"}
          </p>

          <div className="flex justify-between text-slate-600">
            <span>
              {isAr ? "رصيد من الخطة الحالية" : "Credit from current plan"}
            </span>
            <span className="text-emerald-600 font-medium">
              -${proration.creditFromCurrentPlan.toFixed(2)}
            </span>
          </div>

          <div className="flex justify-between text-slate-600">
            <span>{isAr ? "رسوم الخطة الجديدة" : "New plan charge"}</span>
            <span className="font-medium">
              ${proration.chargeForNewPlan.toFixed(2)}
            </span>
          </div>

          <div className="flex justify-between text-xs text-slate-500">
            <span>
              {isAr
                ? `للأيام الـ ${proration.daysRemaining} المتبقية`
                : `For ${proration.daysRemaining} remaining days`}
            </span>
          </div>

          <div className="border-t border-slate-200 pt-2 flex justify-between font-bold text-base">
            <span className="text-slate-900">
              {isAr ? "إجمالي اليوم" : "Total Today"}
            </span>
            <span
              className={
                proration.immediateCharge < 0
                  ? "text-emerald-600"
                  : "text-slate-900"
              }
            >
              {proration.immediateCharge < 0 && "+"}$
              {Math.abs(proration.immediateCharge).toFixed(2)}
              {proration.immediateCharge < 0 && (
                <span className="text-xs font-normal ml-1">
                  ({isAr ? "رصيد" : "credit"})
                </span>
              )}
            </span>
          </div>

          <div className="mt-3 pt-3 border-t border-slate-200 flex justify-between text-slate-600">
            <span>
              {isAr ? "الفاتورة الشهرية القادمة" : "Next monthly billing"}
            </span>
            <span className="font-semibold text-slate-900">
              ${proration.nextBillingAmount.toFixed(2)}
            </span>
          </div>
        </div>

        {/* Important Notes */}
        <div
          className={`mb-4 rounded-lg border p-3 text-xs ${
            isUpgrade
              ? "bg-blue-50 border-blue-200 text-blue-700"
              : "bg-orange-50 border-orange-200 text-orange-700"
          }`}
        >
          <p className="font-semibold mb-1">
            {isAr ? "📌 ملاحظة هامة" : "📌 Important Note"}
          </p>
          <p>
            {isUpgrade
              ? isAr
                ? "سيتم تطبيق الترقية فورًا وسيتم خصم الرسوم الفورية من بطاقتك."
                : "Upgrade applies immediately and the charge will be made to your card."
              : isAr
                ? "سيتم تطبيق التخفيض في نهاية دورة الفوترة الحالية. ستحتفظ بجميع المميزات حتى ذلك الحين."
                : "Downgrade takes effect at the end of your current billing cycle. You keep all features until then."}
          </p>
        </div>

        {/* Error Message */}
        {error && (
          <div className="mb-4 rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-700">
            ⚠️ {error}
          </div>
        )}

        {/* Action Buttons */}
        <div className="flex gap-3">
          <button
            onClick={onCancel}
            disabled={submitting}
            className="flex-1 rounded-lg border border-slate-300 px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 transition-colors disabled:opacity-50"
          >
            {isAr ? "إلغاء" : "Cancel"}
          </button>
          <button
            onClick={onConfirm}
            disabled={submitting}
            className={`flex-1 rounded-lg px-4 py-2.5 text-sm font-semibold text-white transition-colors disabled:opacity-50 ${
              isUpgrade
                ? "bg-brand-green hover:bg-brand-greenHover"
                : "bg-slate-600 hover:bg-slate-700"
            }`}
          >
            {submitting
              ? isAr
                ? "جاري المعالجة..."
                : "Processing..."
              : isUpgrade
                ? isAr
                  ? "تأكيد الترقية"
                  : "Confirm Upgrade"
                : isAr
                  ? "تأكيد التخفيض"
                  : "Confirm Downgrade"}
          </button>
        </div>
      </div>
    </div>
  );
}
