"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import toast from "react-hot-toast";
import {
  usePlansControllerFindAllV1,
  usePlansControllerCreateV1,
  usePlansControllerUpdateV1,
  usePlansControllerToggleV1,
  usePlansControllerRemoveV1,
  getPlansControllerFindAllV1QueryKey,
} from "@/api/admin/admin-subscription-plans/admin-subscription-plans";
import type { AdminPlanData } from "@/api/admin/generated.schemas";

export default function AdminPlansPage() {
  const router = useRouter();
  const t = useTranslations();
  const queryClient = useQueryClient();

  // ─── Data ─────────────────────────────────────────────────────
  const { data: plansResponse, isLoading } = usePlansControllerFindAllV1();
  const plans: AdminPlanData[] = (plansResponse as any)?.data ?? [];

  const invalidatePlans = () =>
    queryClient.invalidateQueries({ queryKey: getPlansControllerFindAllV1QueryKey() });

  // ─── Mutations ────────────────────────────────────────────────
  const createMutation = usePlansControllerCreateV1({
    mutation: {
      onSuccess: () => {
        toast.success(t("admin.plans.planCreated"));
        setModalOpen(false);
        invalidatePlans();
      },
      onError: () => toast.error(t("admin.plans.planCreateFailed")),
    },
  });

  const updateMutation = usePlansControllerUpdateV1({
    mutation: {
      onSuccess: () => {
        toast.success(t("admin.plans.planUpdated"));
        setModalOpen(false);
        invalidatePlans();
      },
      onError: () => toast.error(t("admin.plans.planUpdateFailed")),
    },
  });

  const toggleMutation = usePlansControllerToggleV1({
    mutation: {
      onSuccess: (_, vars) => {
        const plan = plans.find((p) => String(p.id) === vars.id);
        toast.success(`Plan ${plan?.is_active ? t("admin.plans.planDeactivated") : t("admin.plans.planActivated")}`);
        invalidatePlans();
      },
      onError: () => toast.error(t("admin.plans.planToggleFailed")),
    },
  });

  const removeMutation = usePlansControllerRemoveV1({
    mutation: {
      onSuccess: () => {
        toast.success(t("admin.plans.planDeleted"));
        setDeleteModal(false);
        setPlanToDelete(null);
        invalidatePlans();
      },
      onError: () => toast.error(t("admin.plans.planDeleteFailed")),
    },
  });

  const saving = createMutation.isPending || updateMutation.isPending;
  const deleting = removeMutation.isPending;

  // ─── Create/Edit modal ────────────────────────────────────────
  const [modalOpen, setModalOpen] = useState(false);
  const [editingPlan, setEditingPlan] = useState<AdminPlanData | null>(null);
  const [formData, setFormData] = useState({
    name: "",
    name_es: "",
    description: "",
    description_es: "",
    price_monthly: "",
    price_yearly: "",
    subscription_type: "individual" as "individual" | "group",
    is_active: true,
    max_practitioners: "",
    features_monthly: "",
    features_yearly: "",
  });

  // ─── Delete modal ─────────────────────────────────────────────
  const [deleteModal, setDeleteModal] = useState(false);
  const [planToDelete, setPlanToDelete] = useState<AdminPlanData | null>(null);

  // ─── Filter / Search / Sort ───────────────────────────────────
  const [search, setSearch] = useState("");
  const [sortBy, setSortBy] = useState("default");
  const [filterType, setFilterType] = useState<"all" | "individual" | "group">("all");
  const [showFilterMenu, setShowFilterMenu] = useState(false);

  const handleOpenCreate = () => {
    setEditingPlan(null);
    setFormData({
      name: "", name_es: "", description: "", description_es: "",
      price_monthly: "", price_yearly: "", subscription_type: "individual",
      is_active: true, max_practitioners: "", features_monthly: "", features_yearly: "",
    });
    setModalOpen(true);
  };

  const handleOpenEdit = (plan: AdminPlanData) => {
    setEditingPlan(plan);
    const f = plan.features as any;
    setFormData({
      name: plan.name,
      name_es: plan.name_es || "",
      description: plan.description || "",
      description_es: plan.description_es || "",
      price_monthly: String(plan.price_monthly),
      price_yearly: String(plan.price_yearly),
      subscription_type: (plan.subscription_type as "individual" | "group") ?? "individual",
      is_active: plan.is_active,
      max_practitioners: plan.max_practitioners ? String(plan.max_practitioners) : "",
      features_monthly: (f?.monthly || []).join("\n"),
      features_yearly: (f?.yearly || []).join("\n"),
    });
    setModalOpen(true);
  };

  const handleSave = () => {
    if (!formData.name || !formData.price_monthly || !formData.price_yearly) {
      toast.error(t("admin.plans.validationRequired"));
      return;
    }
    const body = {
      name: formData.name,
      name_es: formData.name_es || undefined,
      description: formData.description || undefined,
      description_es: formData.description_es || undefined,
      price_monthly: Number(formData.price_monthly),
      price_yearly: Number(formData.price_yearly),
      subscription_type: formData.subscription_type as any,
      is_active: formData.is_active,
      max_practitioners: formData.max_practitioners
        ? Number(formData.max_practitioners)
        : undefined,
      features: {
        monthly: formData.features_monthly.split("\n").filter(Boolean),
        yearly: formData.features_yearly.split("\n").filter(Boolean),
      } as any,
    };
    if (editingPlan) {
      updateMutation.mutate({ id: String(editingPlan.id), data: body });
    } else {
      createMutation.mutate({ data: body });
    }
  };

  const handleToggle = (plan: AdminPlanData) => {
    toggleMutation.mutate({ id: String(plan.id) });
  };

  const handleDeleteConfirm = () => {
    if (!planToDelete) return;
    removeMutation.mutate({ id: String(planToDelete.id) });
  };

  // ─── Filtered + sorted cards ──────────────────────────────────
  const filteredCards = plans
    .filter((p) => {
      const matchesSearch =
        search === "" ||
        p.name.toLowerCase().includes(search.toLowerCase()) ||
        (p.description || "").toLowerCase().includes(search.toLowerCase());
      const matchesType = filterType === "all" || p.subscription_type === filterType;
      return matchesSearch && matchesType;
    })
    .sort((a, b) => {
      if (sortBy === "name-asc") return a.name.localeCompare(b.name);
      if (sortBy === "name-desc") return b.name.localeCompare(a.name);
      if (sortBy === "price-asc") return Number(a.price_monthly) - Number(b.price_monthly);
      if (sortBy === "price-desc") return Number(b.price_monthly) - Number(a.price_monthly);
      return 0;
    })
    .flatMap((plan) => {
      const f = plan.features as any;
      const cards: Array<{
        plan: AdminPlanData;
        billing: "monthly" | "yearly";
        price: number;
        period: string;
        features: string[];
      }> = [];
      if (plan.price_monthly) {
        cards.push({
          plan,
          billing: "monthly",
          price: Number(plan.price_monthly),
          period: t("admin.plans.perMonth"),
          features: Array.isArray(f?.monthly) ? f.monthly : [],
        });
      }
      if (plan.price_yearly) {
        cards.push({
          plan,
          billing: "yearly",
          price: Number(plan.price_yearly),
          period: t("admin.plans.perYear"),
          features: Array.isArray(f?.yearly) ? f.yearly : [],
        });
      }
      return cards;
    });

  return (
    <main className="pt-6 pb-8">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        {/* Back link */}
        <button
          onClick={() => router.push("/admin/subscription")}
          className="flex items-center gap-2 text-sm text-gray-500 hover:text-gray-700 mb-6 transition cursor-pointer"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
          </svg>
          {t("admin.plans.back")}
        </button>

        {/* Main Card Container */}
        <div className="bg-white rounded-2xl border border-gray-200 shadow-sm">

          {/* Filter Header */}
          <div className="flex items-center gap-3 px-6 py-4 border-b border-gray-100 flex-wrap">
            {/* Title */}
            <span className="text-base font-semibold text-gray-900 mr-1">{t("admin.plans.title")}</span>

            {/* Search */}
            <div className="relative flex-1 min-w-[160px] max-w-xs">
              <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-4.35-4.35M17 11A6 6 0 111 11a6 6 0 0116 0z" />
              </svg>
              <input
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                placeholder={t("admin.plans.searchPlaceholder")}
                className="w-full pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
              />
            </div>

            {/* Sort by */}
            <div className="relative">
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent bg-white appearance-none cursor-pointer"
              >
                <option value="default">{t("admin.plans.sortBy")}</option>
                <option value="name-asc">{t("admin.plans.nameAsc")}</option>
                <option value="name-desc">{t("admin.plans.nameDesc")}</option>
                <option value="price-asc">{t("admin.plans.priceAsc")}</option>
                <option value="price-desc">{t("admin.plans.priceDesc")}</option>
              </select>
              <svg className="absolute right-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
              </svg>
            </div>

            {/* Filter dropdown */}
            <div className="relative">
              <button
                onClick={() => setShowFilterMenu(!showFilterMenu)}
                className={`flex items-center gap-2 px-3 py-2 border rounded-lg text-sm font-medium transition cursor-pointer ${
                  filterType !== "all"
                    ? "border-[#3B9EC9] text-[#3B9EC9] bg-[#3B9EC9]/5"
                    : "border-gray-200 text-gray-600 hover:border-gray-300"
                }`}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M3 4h18M7 8h10M11 12h2" />
                </svg>
                {t("admin.plans.filter")}
                {filterType !== "all" && (
                  <span className="w-1.5 h-1.5 rounded-full bg-[#3B9EC9]" />
                )}
              </button>
              {showFilterMenu && (
                <div className="absolute top-full mt-1 right-0 bg-white border border-gray-200 rounded-xl shadow-lg z-20 py-1 min-w-[160px]">
                  {(["all", "individual", "group"] as const).map((type) => (
                    <button
                      key={type}
                      onClick={() => { setFilterType(type); setShowFilterMenu(false); }}
                      className={`w-full text-left px-4 py-2 text-sm transition cursor-pointer ${
                        filterType === type ? "text-[#3B9EC9] font-medium bg-[#3B9EC9]/5" : "text-gray-600 hover:bg-gray-50"
                      }`}
                    >
                      {type === "all" ? t("admin.plans.allTypes") : type === "individual" ? t("admin.plans.individual") : t("admin.plans.groupPM")}
                    </button>
                  ))}
                </div>
              )}
            </div>

            {/* Create New Subscription */}
            <button
              onClick={handleOpenCreate}
              className="ml-auto flex items-center gap-2 px-4 py-2 bg-[#3B9EC9] text-white text-sm font-medium rounded-lg hover:bg-[#2d8ab5] transition cursor-pointer whitespace-nowrap"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 4v16m8-8H4" />
              </svg>
              {t("admin.plans.createNew")}
            </button>
          </div>

          {/* Plans Grid */}
          <div className="p-6">
            {isLoading ? (
              <div className="flex items-center justify-center py-16">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
              </div>
            ) : filteredCards.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-16 px-4">
                <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mb-4">
                  <svg className="w-8 h-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                    <path strokeLinecap="round" strokeLinejoin="round" 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 2" />
                  </svg>
                </div>
                <p className="text-gray-500 text-sm">
                  {search || filterType !== "all" ? t("admin.plans.noMatchSearch") : t("admin.plans.noPlansFound")}
                </p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {filteredCards.map(({ plan, billing, price, period, features }) => (
                  <div
                    key={`${plan.id}-${billing}`}
                    className="bg-white rounded-2xl border border-gray-200 p-6 flex flex-col"
                  >
                    {/* Toggle */}
                    <div className="mb-4">
                      <button
                        onClick={() => handleToggle(plan)}
                        className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors cursor-pointer ${
                          plan.is_active ? "bg-[#3B9EC9]" : "bg-gray-300"
                        }`}
                        title={plan.is_active ? t("admin.plans.clickDeactivate") : t("admin.plans.clickActivate")}
                      >
                        <span
                          className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                            plan.is_active ? "translate-x-6" : "translate-x-1"
                          }`}
                        />
                      </button>
                    </div>

                    {/* Price */}
                    <div className="flex items-baseline gap-1 mb-2">
                      <span className="text-4xl font-bold text-gray-900">${price.toLocaleString()}</span>
                      <span className="text-sm text-gray-500">{period}</span>
                    </div>

                    {/* Plan Name */}
                    <p className="text-base font-semibold text-gray-900 mb-1">{plan.name}</p>

                    {/* Description */}
                    {plan.description && (
                      <p className="text-sm text-gray-400 mb-3">{plan.description}</p>
                    )}

                    {/* Divider */}
                    <div className="border-t border-gray-100 my-3" />

                    {/* What's Included */}
                    <div className="flex-1 mb-6">
                      <p className="text-sm font-semibold text-gray-900 mb-3">{t("admin.plans.whatsIncluded")}</p>
                      {features.length > 0 ? (
                        <ul className="space-y-2">
                          {features.map((feature: string, fi: number) => (
                            <li key={fi} className="flex items-start gap-2 text-sm text-gray-600">
                              <svg className="w-4 h-4 text-[#3B9EC9] mt-0.5 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                              </svg>
                              {feature}
                            </li>
                          ))}
                        </ul>
                      ) : (
                        <p className="text-xs text-gray-400">{t("admin.plans.noFeatures")}</p>
                      )}
                    </div>

                    {/* Actions */}
                    <div className="flex gap-3">
                      <button
                        onClick={() => handleOpenEdit(plan)}
                        className="flex-1 py-2.5 text-sm font-medium text-[#3B9EC9] border border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 transition cursor-pointer"
                      >
                        {t("admin.plans.edit")}
                      </button>
                      <button
                        onClick={() => { setPlanToDelete(plan); setDeleteModal(true); }}
                        className="flex-1 py-2.5 text-sm font-medium text-gray-600 border border-gray-300 rounded-full hover:bg-gray-50 transition cursor-pointer"
                      >
                        {t("admin.plans.delete")}
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* ─── Create / Edit Modal ─── */}
        {modalOpen && (
          <div
            className="fixed inset-0 z-50 flex items-center justify-center"
            style={{ animation: 'fadeIn 0.2s ease-out' }}
          >
            <style dangerouslySetInnerHTML={{ __html: `
              @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
              }
              @keyframes scaleIn {
                from { opacity: 0; transform: scale(0.9) translateY(10px); }
                to { opacity: 1; transform: scale(1) translateY(0); }
              }
            `}} />

            {/* Backdrop */}
            <div
              className="absolute inset-0 bg-black/30"
              onClick={() => setModalOpen(false)}
            />

            {/* Modal */}
            <div
              className="relative bg-white rounded-3xl shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto"
              style={{ animation: 'scaleIn 0.3s ease-out' }}
            >
              {/* Close button */}
              <button
                onClick={() => setModalOpen(false)}
                className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition z-10 cursor-pointer"
              >
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>

              {/* Content */}
              <div className="p-8">
                <h3 className="text-2xl font-bold text-gray-900 mb-6">
                  {editingPlan ? t("admin.plans.editSubscription") : t("admin.plans.createNew")}
                </h3>

                <div className="space-y-6">

                  {/* ── Plan Name row ── */}
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t("admin.plans.planNameEn")} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        value={formData.name}
                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                        placeholder={t("admin.plans.enterName")}
                        className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        {t("admin.plans.planNameEs")} <span className="text-red-500">*</span>
                      </label>
                      <input
                        type="text"
                        value={formData.name_es}
                        onChange={(e) => setFormData({ ...formData, name_es: e.target.value })}
                        placeholder={t("admin.plans.enterNameEs")}
                        className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                      />
                    </div>
                  </div>

                  {/* ── Subscription Type ── */}
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">{t("admin.plans.subscriptionType")}</label>
                    <div className="relative">
                      <select
                        value={formData.subscription_type}
                        onChange={(e) =>
                          setFormData({
                            ...formData,
                            subscription_type: e.target.value as "individual" | "group",
                            max_practitioners: e.target.value === "individual" ? "" : formData.max_practitioners,
                          })
                        }
                        className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent bg-white appearance-none cursor-pointer"
                      >
                        <option value="" disabled>{t("admin.plans.selectUserRole")}</option>
                        <option value="individual">{t("admin.plans.individual")}</option>
                        <option value="group">{t("admin.plans.groupPracticeManager")}</option>
                      </select>
                      <div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none">
                        <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                        </svg>
                      </div>
                    </div>
                  </div>

                  {/* ── Max Practitioners (group only) ── */}
                  {formData.subscription_type === "group" && (
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">{t("admin.plans.maxPractitioners")}</label>
                      <input
                        type="number"
                        min="1"
                        value={formData.max_practitioners}
                        onChange={(e) => setFormData({ ...formData, max_practitioners: e.target.value })}
                        placeholder={t("admin.plans.maxPractitionersPlaceholder")}
                        className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-600 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                      />
                    </div>
                  )}

                  {/* ── Billing Periods ── */}
                  <div>
                    <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-3">{t("admin.plans.billingPeriods")}</p>
                    <div className="grid grid-cols-2 gap-4">

                      {/* Monthly */}
                      <div className="bg-gray-50 rounded-2xl p-5 border border-gray-100 space-y-4">
                        <p className="text-sm font-semibold text-gray-800">{t("admin.plans.monthly")}</p>
                        <div>
                          <label className="block text-sm font-medium text-gray-600 mb-1.5">
                            {t("admin.plans.priceLabel")} <span className="text-red-500">*</span>
                          </label>
                          <input
                            type="number"
                            min="0"
                            value={formData.price_monthly}
                            onChange={(e) => setFormData({ ...formData, price_monthly: e.target.value })}
                            placeholder="25"
                            className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent bg-white"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-gray-600 mb-1.5">
                            {t("admin.plans.includedOnePerLine")} <span className="font-normal text-gray-400">{t("admin.plans.onePerLine")}</span>
                          </label>
                          <textarea
                            rows={6}
                            value={formData.features_monthly}
                            onChange={(e) => setFormData({ ...formData, features_monthly: e.target.value })}
                            placeholder={t("admin.plans.writePlaceholder")}
                            className="w-full px-4 py-3 border border-gray-200 rounded-2xl text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent resize-none bg-white leading-relaxed"
                          />
                        </div>
                      </div>

                      {/* Annual */}
                      <div className="bg-gray-50 rounded-2xl p-5 border border-gray-100 space-y-4">
                        <p className="text-sm font-semibold text-gray-800">{t("admin.plans.annual")}</p>
                        <div>
                          <label className="block text-sm font-medium text-gray-600 mb-1.5">
                            {t("admin.plans.priceLabel")} <span className="text-red-500">*</span>
                          </label>
                          <input
                            type="number"
                            min="0"
                            value={formData.price_yearly}
                            onChange={(e) => setFormData({ ...formData, price_yearly: e.target.value })}
                            placeholder="100"
                            className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent bg-white"
                          />
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-gray-600 mb-1.5">
                            {t("admin.plans.includedOnePerLine")} <span className="font-normal text-gray-400">{t("admin.plans.onePerLine")}</span>
                          </label>
                          <textarea
                            rows={6}
                            value={formData.features_yearly}
                            onChange={(e) => setFormData({ ...formData, features_yearly: e.target.value })}
                            placeholder={t("admin.plans.writePlaceholder")}
                            className="w-full px-4 py-3 border border-gray-200 rounded-2xl text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent resize-none bg-white leading-relaxed"
                          />
                        </div>
                      </div>

                    </div>
                  </div>

                  {/* ── Description ── */}
                  <div>
                    <p className="text-xs font-semibold text-gray-400 uppercase tracking-widest mb-1">{t("admin.plans.descriptionSection")}</p>
                    <p className="text-xs text-gray-400 mb-3">{t("admin.plans.descriptionHint")}</p>
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">{t("admin.plans.english")}</label>
                        <input
                          type="text"
                          value={formData.description}
                          onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                          placeholder={t("admin.plans.descPlaceholderEn")}
                          className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          {t("admin.plans.spanish")}
                        </label>
                        <input
                          type="text"
                          value={formData.description_es}
                          onChange={(e) => setFormData({ ...formData, description_es: e.target.value })}
                          placeholder={t("admin.plans.descPlaceholderEs")}
                          className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm text-gray-700 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent"
                        />
                      </div>
                    </div>
                  </div>

                  {/* ── Status toggle ── */}
                  <div className="flex items-center gap-3">
                    <button
                      type="button"
                      onClick={() => setFormData({ ...formData, is_active: !formData.is_active })}
                      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors cursor-pointer ${
                        formData.is_active ? "bg-[#3B9EC9]" : "bg-gray-300"
                      }`}
                    >
                      <span
                        className={`inline-block h-4 w-4 transform rounded-full bg-white shadow transition-transform ${
                          formData.is_active ? "translate-x-6" : "translate-x-1"
                        }`}
                      />
                    </button>
                    <span className="text-sm text-gray-700">
                      {t("admin.plans.activeLabel")}
                      <span className="text-gray-400 text-xs ml-1">{t("admin.plans.activeHint")}</span>
                    </span>
                  </div>

                </div>
              </div>

              {/* Footer */}
              <div className="px-8 py-5 border-t border-gray-100 flex justify-end">
                <button
                  onClick={handleSave}
                  disabled={saving}
                  className="px-8 py-3 bg-[#3B9EC9] rounded-full text-white text-sm font-medium hover:bg-[#2d8ab5] transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer"
                >
                  {saving && (
                    <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                  )}
                  {saving ? t("admin.plans.saving") : editingPlan ? t("admin.plans.saveChanges") : t("admin.plans.addSubscription")}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* ─── Delete Confirmation Modal ─── */}
        {deleteModal && planToDelete && (
          <div
            className="fixed inset-0 z-50 flex items-center justify-center"
            style={{ animation: 'fadeIn 0.2s ease-out' }}
          >
            <style dangerouslySetInnerHTML={{ __html: `
              @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
              }
              @keyframes scaleIn {
                from { opacity: 0; transform: scale(0.9) translateY(10px); }
                to { opacity: 1; transform: scale(1) translateY(0); }
              }
            `}} />

            {/* Backdrop */}
            <div
              className="absolute inset-0 bg-black/30"
              onClick={() => { setDeleteModal(false); setPlanToDelete(null); }}
            />

            {/* Modal */}
            <div
              className="relative bg-white rounded-2xl shadow-xl w-full max-w-md mx-4 p-8 pt-12"
              style={{ animation: 'scaleIn 0.3s ease-out' }}
            >
              {/* Close button */}
              <button
                onClick={() => { setDeleteModal(false); setPlanToDelete(null); }}
                className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition cursor-pointer"
              >
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>

              {/* Icon */}
              <div className="flex justify-center mb-6">
                <div className="w-20 h-20 bg-red-50 rounded-full flex items-center justify-center">
                  <svg className="w-10 h-10 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </div>
              </div>

              {/* Content */}
              <div className="text-center mb-8">
                <h3 className="text-2xl font-semibold text-[#E05A5A] mb-3">{t("admin.plans.deletePlan")}</h3>
                <p className="text-gray-500 text-base">
                  {t("admin.plans.deleteConfirm")}{" "}
                  <span className="font-medium text-gray-700">&quot;{planToDelete.name}&quot;</span>?
                  {t("admin.plans.cannotUndo")}
                </p>
              </div>

              {/* Actions */}
              <div className="flex gap-4 justify-center">
                <button
                  onClick={() => { setDeleteModal(false); setPlanToDelete(null); }}
                  className="px-10 py-3 border border-gray-300 rounded-full text-gray-600 font-medium hover:bg-gray-50 transition cursor-pointer"
                >
                  {t("admin.plans.cancel")}
                </button>
                <button
                  onClick={handleDeleteConfirm}
                  disabled={deleting}
                  className="px-10 py-3 bg-[#E05A5A] rounded-full text-white font-medium hover:bg-[#D04A4A] transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 cursor-pointer"
                >
                  {deleting && (
                    <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                    </svg>
                  )}
                  {deleting ? t("admin.plans.deleting") : t("admin.plans.delete")}
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </main>
  );
}
