"use client";

import Image from "next/image";
import { useState, useEffect, useCallback, useRef } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { customInstance } from "@/config/axios";
import toast from "react-hot-toast";
import ComplimentaryBadge from "@/components/admin/ComplimentaryBadge";
import GrantComplimentaryModal from "@/components/admin/GrantComplimentaryModal";
import { useSubscriptionControllerRevokeComplimentaryV1 } from "@/api/admin/admin-subscriptions/admin-subscriptions";

interface Subscription {
  uuid: string;
  user?: {
    uuid: string;
    username: string;
    email: string;
    avatar?: string | null;
    role?: string | null;
  } | null;
  plan?: {
    uuid?: string | null;
    name: string;
  } | null;
  billing_cycle?: string | null;
  renewal_date?: string | null;
  status: string;
  started_at?: string | null;
  expires_at?: string | null;
  canceled_at?: string | null;
  amount?: number;
  currency?: string;
  trial_end?: string | null;
  is_trial?: boolean;
  is_complimentary?: boolean;
  created_at?: string | null;
}

interface SubscriptionStats {
  active_subscriptions: number;
  total_earning: number;
  cancelled_this_month: number;
  new_this_month: number;
}

export default function AdminSubscription() {
  const t = useTranslations();
  const router = useRouter();
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("");
  const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);
  const [allSubscriptions, setAllSubscriptions] = useState<Subscription[]>([]);
  const [stats, setStats] = useState<SubscriptionStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(50);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [viewModalOpen, setViewModalOpen] = useState(false);
  const [selectedSubscription, setSelectedSubscription] = useState<Subscription | null>(null);
  const [userSubscriptionHistory, setUserSubscriptionHistory] = useState<Subscription[]>([]);

  // Revoke confirmation modal — replaces the native confirm() so admin sees
  // a styled prompt with full context (user name, consequences, audit note).
  const [revokeConfirmOpen, setRevokeConfirmOpen] = useState(false);
  const [subscriptionToRevoke, setSubscriptionToRevoke] = useState<Subscription | null>(null);
  // Holds the revoked user's email across the mutation lifecycle. Captured at
  // click time so the success toast (fired after subscriptionToRevoke is cleared)
  // can name the freed email.
  const revokedEmailRef = useRef<string | null>(null);

  // Grant-Again modal — for re-granting access to a user whose complimentary
  // sub was previously revoked or auto-expired. Reuses GrantComplimentaryModal
  // in "existing user" mode (passes user prop).
  const [regrantModalOpen, setRegrantModalOpen] = useState(false);
  const [userToRegrant, setUserToRegrant] = useState<{ uuid: string; name?: string; email: string } | null>(null);

  // Filters
  const [statusFilter, setStatusFilter] = useState("");
  const [billingCycleFilter, setBillingCycleFilter] = useState("");

  // Action states
  const [actionLoading, setActionLoading] = useState(false);

  const fetchSubscriptions = useCallback(async () => {
    try {
      const params: Record<string, string | number> = {
        page: currentPage,
        limit: itemsPerPage,
      };

      if (searchQuery) {
        params.search = searchQuery;
      }

      if (sortBy) {
        params.sort_field = sortBy;
        params.sort_direction = 'DESC';
      }

      if (statusFilter) {
        params.status = statusFilter;
      }

      if (billingCycleFilter) {
        params.billing_cycle = billingCycleFilter;
      }

      const subscriptionsResponse = await customInstance<{
        data: {
          subscriptions: Subscription[];
          total_count: number;
          page: number;
          limit: number;
          total_pages: number;
        };
      }>({
        url: '/v1/subscriptions',
        method: 'GET',
        params,
      });

      setSubscriptions(subscriptionsResponse.data.subscriptions || []);
      setTotalCount(subscriptionsResponse.data.total_count || 0);
      setTotalPages(subscriptionsResponse.data.total_pages || 1);
    } catch (error) {
      console.error('Error fetching subscriptions:', error);
      setSubscriptions([]);
    }
  }, [currentPage, itemsPerPage, searchQuery, sortBy, statusFilter, billingCycleFilter]);

  // Fetch every subscription by iterating pages.
  // Backend caps per-page size, so a single `limit: 10000` request may be silently truncated —
  // we page through using the server's reported total_pages instead.
  // Pass `filters` to scope the result to the current table filters (used by export).
  // Without `filters`, returns the full unfiltered set (used by the user-history modal cache).
  type ExportFilters = {
    search?: string;
    status?: string;
    billing_cycle?: string;
    sort_field?: string;
    sort_direction?: 'ASC' | 'DESC';
  };
  const fetchAllSubscriptions = useCallback(async (
    filters: ExportFilters = {},
  ): Promise<{ rows: Subscription[]; complete: boolean }> => {
    const PAGE_SIZE = 1000;
    const all: Subscription[] = [];
    let page = 1;
    let totalPagesRemote = 1;
    let totalCountRemote = 0;
    try {
      do {
        const response = await customInstance<{
          data: {
            subscriptions: Subscription[];
            total_count: number;
            total_pages: number;
          };
        }>({
          url: '/v1/subscriptions',
          method: 'GET',
          params: { page, limit: PAGE_SIZE, ...filters },
        });
        all.push(...(response.data.subscriptions || []));
        totalPagesRemote = response.data.total_pages || 1;
        totalCountRemote = response.data.total_count || all.length;
        page += 1;
      } while (page <= totalPagesRemote);
      const complete = all.length >= totalCountRemote;
      // Only refresh the history-modal cache when fetching the full unfiltered set.
      if (!filters.search && !filters.status && !filters.billing_cycle) {
        setAllSubscriptions(all);
      }
      return { rows: all, complete };
    } catch (error) {
      console.error('Error fetching all subscriptions:', error);
      if (!filters.search && !filters.status && !filters.billing_cycle) {
        setAllSubscriptions(all);
      }
      return { rows: all, complete: false };
    }
  }, []);

  const fetchStats = useCallback(async () => {
    try {
      const statsResponse = await customInstance<{ data: SubscriptionStats }>({
        url: '/v1/subscriptions/statistics',
        method: 'GET',
      });
      setStats(statsResponse.data);
    } catch (error) {
      console.error('Error fetching stats:', error);
    }
  }, []);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        await Promise.all([fetchStats(), fetchSubscriptions(), fetchAllSubscriptions()]);
      } catch (error) {
        console.error('Error fetching initial data:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (!loading) {
      fetchSubscriptions();
    }
  }, [currentPage, itemsPerPage, sortBy, statusFilter, billingCycleFilter]);

  // Debounced search
  useEffect(() => {
    const delayDebounceFn = setTimeout(() => {
      if (currentPage === 1) {
        fetchSubscriptions();
      } else {
        setCurrentPage(1);
      }
    }, 500);

    return () => clearTimeout(delayDebounceFn);
  }, [searchQuery]);

  const formatDate = (dateString: string | null | undefined) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleDateString('en-US', {
      day: 'numeric',
      month: 'short',
      year: 'numeric'
    });
  };

  const formatBillingCycle = (cycle: string | null | undefined) => {
    if (!cycle || cycle === 'none') return '-';
    if (cycle === 'one_time') return 'One-time';
    return cycle.charAt(0).toUpperCase() + cycle.slice(1);
  };

  // Backend reports trial users as status="active" — `is_trial` is authoritative.
  // Trial rows have no real charge yet, so render "-" in the Amount column. The status badge
  // already labels them "Free Trial" — no need to duplicate the label here.
  const formatCurrency = (
    amount: number | undefined,
    currency: string | undefined,
    isTrial?: boolean,
  ) => {
    if (isTrial) return '-';
    if (amount === undefined || amount === null) return '-';
    if (amount === 0) return '$0';
    const symbol = currency === 'USD' ? '$' : (currency || '$');
    return `${symbol}${amount.toLocaleString()}`;
  };

  const handleViewClick = (subscription: Subscription) => {
    setSelectedSubscription(subscription);
    // Find all subscriptions for this user
    const userHistory = allSubscriptions.filter(
      (sub) => sub.user?.uuid === subscription.user?.uuid
    );
    setUserSubscriptionHistory(userHistory);
    setViewModalOpen(true);
  };

  const handleCloseViewModal = () => {
    setViewModalOpen(false);
    setSelectedSubscription(null);
    setUserSubscriptionHistory([]);
  };

  const exportToCSV = async () => {
    // Build the filter set from current table state so the export matches what's visible.
    const exportFilters: ExportFilters = {};
    if (searchQuery) exportFilters.search = searchQuery;
    if (statusFilter) exportFilters.status = statusFilter;
    if (billingCycleFilter) exportFilters.billing_cycle = billingCycleFilter;
    if (sortBy) {
      exportFilters.sort_field = sortBy;
      exportFilters.sort_direction = 'DESC';
    }

    // Iterate pages to grab every row matching the filters; not capped to the current page.
    const { rows: dataToExport, complete } = await fetchAllSubscriptions(exportFilters);

    if (dataToExport.length === 0) {
      toast.error(t("admin.subscription.noDataToExport"));
      return;
    }

    if (!complete) {
      toast.error(t("admin.subscription.exportTruncated"));
    }

    toast.success(t("admin.subscription.exportingRows", { count: dataToExport.length }));

    const headers = [
      'Sr No',
      'Name',
      'Email',
      'Renewal Date',
      'Billing Cycle',
      'Amount',
      'Status',
      'Started At',
      'Expires At',
    ];

    // Trial rows are reported by the backend as status="active" + is_trial=true; the badge text in
    // the table reads "Free Trial". Mirror that here so the export matches what's on screen.
    const statusLabel = (sub: Subscription) =>
      sub.is_trial
        ? t("admin.subscription.freeTrial")
        : (sub.status?.charAt(0).toUpperCase() + sub.status?.slice(1) || '');

    const rows = dataToExport.map((sub, index) => [
      (index + 1).toString(),
      sub.user?.username || '',
      sub.user?.email || '',
      formatDate(sub.renewal_date || sub.expires_at),
      formatBillingCycle(sub.billing_cycle),
      formatCurrency(sub.amount, sub.currency, sub.is_trial),
      statusLabel(sub),
      formatDate(sub.started_at),
      formatDate(sub.expires_at),
    ]);

    // Output an HTML table saved as .xls so Excel/Sheets/Numbers render the title as a single
    // merged centered cell across all columns (CSV cannot represent merged cells).
    // Formula-guarded HTML escape for XLS cells. Values starting with =, +, -, @, tab, or CR
    // can be interpreted as formulas by Excel (CSV injection / formula injection). Prefix with
    // a single quote to neutralize. Then escape HTML entities for the HTML-as-XLS container.
    const escape = (v: string) => {
      const guarded = /^[=+\-@\t\r]/.test(v) ? `'${v}` : v;
      return guarded.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    };
    const title = 'Subscription Users List';
    const colCount = headers.length;

    const xlsContent = `<html xmlns:x="urn:schemas-microsoft-com:office:excel"><head><meta charset="UTF-8"/></head><body>
<table border="1">
  <tr><th colspan="${colCount}" style="text-align:center;font-size:14px;background:#f3f4f6;padding:8px">${escape(title)}</th></tr>
  <tr>${headers.map((h) => `<th style="background:#f9fafb;text-align:left;padding:6px">${escape(h)}</th>`).join('')}</tr>
  ${rows.map((row) => `<tr>${row.map((cell) => `<td style="padding:4px 6px">${escape(cell)}</td>`).join('')}</tr>`).join('\n  ')}
</table>
</body></html>`;

    const blob = new Blob([xlsContent], { type: 'application/vnd.ms-excel;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `subscriptions_${new Date().toISOString().split('T')[0]}.xls`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  const { mutate: revokeComplimentary, isPending: isRevoking } = useSubscriptionControllerRevokeComplimentaryV1({
    mutation: {
      onSuccess: async () => {
        const email = revokedEmailRef.current;
        revokedEmailRef.current = null;
        toast.success(
          email
            ? `Access revoked. ${email} is now free to re-register or be re-invited.`
            : "Access revoked."
        );
        await fetchSubscriptions();
        await fetchAllSubscriptions();
        handleCloseViewModal();
      },
      onError: (err: unknown) => {
        revokedEmailRef.current = null;
        const message =
          (err as { response?: { data?: { message?: string } } })?.response?.data?.message ||
          "Failed to revoke complimentary access";
        toast.error(message);
      },
    },
  });

  // Opens the styled confirmation modal (no longer native confirm).
  const handleRevokeComplimentary = (sub: Subscription) => {
    setSubscriptionToRevoke(sub);
    setRevokeConfirmOpen(true);
  };

  const handleCancelRevoke = () => {
    if (isRevoking) return;
    setRevokeConfirmOpen(false);
    setSubscriptionToRevoke(null);
  };

  const handleConfirmRevoke = () => {
    if (!subscriptionToRevoke) return;
    revokedEmailRef.current = subscriptionToRevoke.user?.email ?? null;
    revokeComplimentary({ uuid: subscriptionToRevoke.uuid });
    // Close the confirm modal optimistically — the mutation onSuccess closes
    // the parent detail modal and refreshes the list. Errors fall back to a toast.
    setRevokeConfirmOpen(false);
    setSubscriptionToRevoke(null);
  };

  // Eligibility check for "Grant Again" on the subscription detail modal.
  // Only auto-expired comp subs are eligible: those keep is_complimentary=true
  // and the user record is still alive. Manually-revoked subs soft-delete the
  // user, so re-granting against the same user_uuid would 404 — admin should
  // re-invite via the user management flow instead (same email is now accepted).
  const isRegrantEligible = (sub: Subscription | null): boolean => {
    if (!sub || sub.status !== 'cancelled') return false;
    return Boolean(sub.is_complimentary);
  };

  const handleOpenRegrant = (sub: Subscription) => {
    if (!sub.user) return;
    setUserToRegrant({
      uuid: sub.user.uuid,
      name: sub.user.username,
      email: sub.user.email,
    });
    setRegrantModalOpen(true);
  };

  const handleCloseRegrant = () => {
    setRegrantModalOpen(false);
    setUserToRegrant(null);
  };

  const handleRegrantSuccess = async () => {
    await fetchSubscriptions();
    await fetchAllSubscriptions();
    handleCloseRegrant();
    handleCloseViewModal();
  };

  const handleCancelSubscription = async (subscriptionUuid: string) => {
    if (!confirm(t("admin.subscription.confirmCancel"))) {
      return;
    }

    setActionLoading(true);
    try {
      await customInstance({
        url: `/v1/subscriptions/${subscriptionUuid}/cancel`,
        method: 'PATCH',
      });
      toast.success(t("admin.subscription.cancelSuccess"));
      // Refresh data
      await fetchSubscriptions();
      await fetchAllSubscriptions();
      handleCloseViewModal();
    } catch (error) {
      console.error('Error cancelling subscription:', error);
      toast.error(t("admin.subscription.cancelError"));
    } finally {
      setActionLoading(false);
    }
  };

  const renderPagination = () => {
    const pages: (number | string)[] = [];

    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) {
        pages.push(i);
      }
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, '...', totalPages - 1, totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, 2, '...', totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages);
      }
    }

    return pages.map((page, index) => (
      typeof page === 'number' ? (
        <button
          key={index}
          onClick={() => setCurrentPage(page)}
          className={`w-8 h-8 rounded-lg text-sm font-medium cursor-pointer ${
            currentPage === page
              ? 'bg-gray-100 text-gray-900'
              : 'text-gray-600 hover:bg-gray-50'
          }`}
        >
          {page}
        </button>
      ) : (
        <span key={index} className="px-2 text-gray-400">{page}</span>
      )
    ));
  };

  if (loading) {
    return (
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#3B9EC9]"></div>
        </div>
      </main>
    );
  }

  return (
    <>
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Page Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-6">
          <h1 className="text-2xl font-semibold text-gray-900">{t("admin.subscription.title")}</h1>
          <div className="flex flex-wrap items-center gap-2">
            <button
              onClick={() => router.push('/admin/transactions')}
              className="flex items-center gap-2 px-4 py-2 bg-white border border-[#3B9EC9] text-[#3B9EC9] text-sm font-medium rounded-lg hover:bg-[#3B9EC9]/5 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="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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>
              {t("admin.subscription.transactionLog")}
            </button>
            <button
              onClick={() => router.push('/admin/plans')}
              className="flex items-center gap-2 px-4 py-2 bg-white border border-[#3B9EC9] text-[#3B9EC9] text-sm font-medium rounded-lg hover:bg-[#3B9EC9]/5 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="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>
              {t("admin.plans.managePlans")}
            </button>
          </div>
        </div>
        {/* Stats Cards */}
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
          {/* Total Earning */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">{t("admin.dashboard.totalEarning")}</p>
              <p className="text-2xl font-bold text-[#3B9EC9] mt-1">
                ${stats?.total_earning?.toLocaleString() || 0}
              </p>
            </div>
            <div className="w-10 h-10 rounded-lg bg-yellow-100 flex items-center justify-center">
              <span className="text-xl font-bold text-yellow-600">$</span>
            </div>
          </div>

          {/* Active Subscriptions */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">{t("admin.subscription.activeSubscriptions")}</p>
              <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.active_subscriptions?.toLocaleString() || 0}</p>
            </div>
            <div className="w-10 h-10 rounded-lg bg-blue-50 flex items-center justify-center">
              <svg className="w-5 h-5 text-blue-500" fill="currentColor" viewBox="0 0 24 24">
                <path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
              </svg>
            </div>
          </div>

          {/* Cancelled This Month */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">{t("admin.subscription.cancelledThisMonth")}</p>
              <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.cancelled_this_month?.toLocaleString() || 0}</p>
            </div>
            <div className="w-10 h-10 rounded-lg bg-orange-50 flex items-center justify-center">
              <svg className="w-5 h-5 text-orange-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
              </svg>
            </div>
          </div>

          {/* New This Month */}
          <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5 flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-500">{t("admin.subscription.newThisMonth")}</p>
              <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.new_this_month?.toLocaleString() || 0}</p>
            </div>
            <div className="w-10 h-10 rounded-lg bg-cyan-50 flex items-center justify-center">
              <svg className="w-5 h-5 text-cyan-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
              </svg>
            </div>
          </div>
        </div>

        {/* Subscriptions Table */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
          {/* Table Header */}
          <div className="p-5 border-b border-gray-200">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <h3 className="text-lg font-semibold text-gray-900">
                {t("admin.subscription.title")}
                {totalCount > 0 && (
                  <span className="ml-2 text-sm font-normal text-gray-500">
                    ({totalCount} {totalCount === 1 ? 'subscription' : 'subscriptions'})
                  </span>
                )}
              </h3>
              <div className="flex flex-wrap items-center gap-2">
                {/* Search */}
                <div className="relative flex-1 sm:flex-none">
                  <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">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                  <input
                    type="text"
                    placeholder={t("admin.common.search")}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9 pr-4 py-2 w-full sm:w-48 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                  />
                </div>

                {/* Sort By */}
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer"
                >
                  <option value="">{t("admin.common.sortBy")}</option>
                  <option value="created_at">{t("admin.common.newest")}</option>
                  <option value="renewal_date">{t("admin.subscription.renewalDate")}</option>
                  <option value="status">{t("admin.subscription.status")}</option>
                </select>

                {/* Status Filter */}
                <select
                  value={statusFilter}
                  onChange={(e) => setStatusFilter(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer"
                >
                  <option value="">{t("admin.subscription.allStatuses")}</option>
                  <option value="active">{t("admin.subscription.active")}</option>
                  <option value="cancelled">{t("admin.subscription.cancelled")}</option>
                  <option value="past_due">{t("admin.subscription.pastDue")}</option>
                  <option value="incomplete">{t("admin.subscription.incomplete")}</option>
                  <option value="paused">{t("admin.subscription.paused")}</option>
                </select>

                {/* Billing Cycle Filter */}
                <select
                  value={billingCycleFilter}
                  onChange={(e) => setBillingCycleFilter(e.target.value)}
                  className="px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer"
                >
                  <option value="">All</option>
                  <option value="one_time">One-time</option>
                  <option value="monthly">Monthly</option>
                  <option value="yearly">Yearly</option>
                </select>

                {/* Export Button */}
                <button
                  onClick={exportToCSV}
                  className="flex items-center gap-2 px-4 py-2 bg-[#3B9EC9] text-white rounded-lg text-sm hover:bg-[#2B8EB9] 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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                  </svg>
                  {t("admin.subscription.export")}
                </button>
              </div>
            </div>
          </div>

          {/* Table */}
          <div className="mx-5 mb-5 mt-5 border border-gray-300 rounded-lg overflow-hidden">
            <div className="overflow-x-auto">
            <table className="w-full border-collapse min-w-[600px]">
              <thead>
                <tr className="bg-gray-50">
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.subscription.user")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.subscription.renewalDate")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.subscription.billingCycle")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.subscription.amount")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-300">{t("admin.subscription.status")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-300">{t("admin.lead.action")}</th>
                </tr>
              </thead>
              <tbody>
                {subscriptions.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-5 py-8 text-center text-gray-500">
                      {t("admin.common.noSubscriptionsFound")}
                    </td>
                  </tr>
                ) : (
                  subscriptions.map((sub, index) => (
                    <tr key={sub.uuid} className="hover:bg-gray-50/50 transition">
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== subscriptions.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <div className="flex items-center gap-3">
                          {sub.user?.avatar ? (
                            <Image
                              src={sub.user.avatar}
                              alt={sub.user.username}
                              width={40}
                              height={40}
                              className="w-10 h-10 rounded-full object-cover"
                            />
                          ) : (
                            <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center">
                              <span className="text-gray-500 text-sm font-medium">
                                {sub.user?.username?.charAt(0)?.toUpperCase() || 'U'}
                              </span>
                            </div>
                          )}
                          <div>
                            <p className="text-sm font-medium text-gray-900">{sub.user?.username || 'Unknown'}</p>
                            <p className="text-xs text-gray-500">{sub.user?.email || '-'}</p>
                          </div>
                        </div>
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== subscriptions.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {formatDate(sub.renewal_date || sub.expires_at)}
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== subscriptions.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {formatBillingCycle(sub.billing_cycle)}
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== subscriptions.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {formatCurrency(sub.amount, sub.currency, sub.is_trial)}
                      </td>
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== subscriptions.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {sub.is_complimentary ? (
                          <ComplimentaryBadge size="sm" />
                        ) : (
                          <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full ${
                            sub.is_trial ? 'bg-blue-50 text-blue-600'
                            : sub.status === 'active' ? 'bg-green-50 text-green-600'
                            : sub.status === 'cancelled' ? 'bg-red-50 text-red-600'
                            : sub.status === 'past_due' ? 'bg-orange-50 text-orange-600'
                            : sub.status === 'incomplete' ? 'bg-yellow-50 text-yellow-600'
                            : 'bg-gray-50 text-gray-600'
                          }`}>
                            <span className={`w-1.5 h-1.5 rounded-full ${
                              sub.is_trial ? 'bg-blue-500'
                              : sub.status === 'active' ? 'bg-green-500'
                              : sub.status === 'cancelled' ? 'bg-red-500'
                              : sub.status === 'past_due' ? 'bg-orange-500'
                              : sub.status === 'incomplete' ? 'bg-yellow-500'
                              : 'bg-gray-500'
                            }`}></span>
                            {sub.is_trial ? t("admin.subscription.freeTrial") : (sub.status?.charAt(0).toUpperCase() + sub.status?.slice(1) || 'Unknown')}
                          </span>
                        )}
                      </td>
                      <td className={`px-5 py-4 ${index !== subscriptions.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <button
                          onClick={() => handleViewClick(sub)}
                          className="w-9 h-9 rounded-lg bg-blue-50 flex items-center justify-center text-blue-400 hover:bg-blue-100 hover:text-blue-600 transition cursor-pointer"
                          title={t("admin.common.view")}
                        >
                          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
                            <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          </svg>
                        </button>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
            </div>
          </div>

          {/* Pagination */}


          {totalCount > 0 && (
          <div className="px-5 py-4 border-t border-gray-200">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              {/* Showing X-Y of Z & Per-page selector */}
              <div className="flex items-center gap-4">
                <span className="text-sm text-gray-500">
                  {t("admin.common.showing")} {totalCount === 0 ? 0 : (currentPage - 1) * itemsPerPage + 1}-{Math.min(currentPage * itemsPerPage, totalCount)} {t("admin.common.of")} {totalCount}
                </span>
                <select
                  value={itemsPerPage}
                  onChange={(e) => {
                    setItemsPerPage(Number(e.target.value));
                    setCurrentPage(1);
                  }}
                  className="px-2 py-1 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                >
                  <option value={10}>10</option>
                  <option value={25}>25</option>
                  <option value={50}>50</option>
                  <option value={100}>100</option>
                  <option value={250}>250</option>
                </select>
              </div>

              {/* Page navigation */}
              {totalPages > 1 && (
                <div className="flex items-center gap-2 flex-wrap">
                  <button
                    onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                    disabled={currentPage === 1}
                    className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                  >
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                    </svg>
                    {t("admin.common.previous")}
                  </button>

                  <div className="flex items-center gap-1">
                    {renderPagination()}
                  </div>

                  <button
                    onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                    disabled={currentPage === totalPages}
                    className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
                  >
                    {t("admin.common.next")}
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                    </svg>
                  </button>
                </div>
              )}
            </div>
          </div>
          )}
        </div>
      </main>

      {/* Subscription Detail Modal */}
      {viewModalOpen && selectedSubscription && (
        <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"
            style={{ animation: 'fadeIn 0.2s ease-out' }}
            onClick={handleCloseViewModal}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-hidden"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Header */}
            <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200">
              <h3 className="text-xl font-semibold text-gray-900">
                {t("admin.modals.subscriptionDetails")}
              </h3>
              <button
                onClick={handleCloseViewModal}
                className="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>
            </div>

            {/* Content */}
            <div className="p-6 overflow-y-auto max-h-[calc(90vh-140px)]">
              {/* User Info */}
              <div className="flex items-center gap-4 mb-6 pb-6 border-b border-gray-200">
                {selectedSubscription.user?.avatar ? (
                  <Image
                    src={selectedSubscription.user.avatar}
                    alt={selectedSubscription.user.username}
                    width={64}
                    height={64}
                    className="w-16 h-16 rounded-full object-cover"
                  />
                ) : (
                  <div className="w-16 h-16 rounded-full bg-gray-200 flex items-center justify-center">
                    <span className="text-gray-500 text-xl font-medium">
                      {selectedSubscription.user?.username?.charAt(0)?.toUpperCase() || 'U'}
                    </span>
                  </div>
                )}
                <div>
                  <p className="text-lg font-semibold text-gray-900">{selectedSubscription.user?.username || 'Unknown'}</p>
                  <p className="text-sm text-gray-500">{selectedSubscription.user?.email || '-'}</p>
                </div>
                <div className="ml-auto">
                  {selectedSubscription.is_complimentary ? (
                    <ComplimentaryBadge />
                  ) : (
                    <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full ${
                      selectedSubscription.is_trial ? 'bg-blue-50 text-blue-600'
                      : selectedSubscription.status === 'active' ? 'bg-green-50 text-green-600'
                      : selectedSubscription.status === 'cancelled' ? 'bg-red-50 text-red-600'
                      : selectedSubscription.status === 'past_due' ? 'bg-orange-50 text-orange-600'
                      : selectedSubscription.status === 'incomplete' ? 'bg-yellow-50 text-yellow-600'
                      : 'bg-gray-50 text-gray-600'
                    }`}>
                      <span className={`w-2 h-2 rounded-full ${
                        selectedSubscription.is_trial ? 'bg-blue-500'
                        : selectedSubscription.status === 'active' ? 'bg-green-500'
                        : selectedSubscription.status === 'cancelled' ? 'bg-red-500'
                        : selectedSubscription.status === 'past_due' ? 'bg-orange-500'
                        : selectedSubscription.status === 'incomplete' ? 'bg-yellow-500'
                        : 'bg-gray-500'
                      }`}></span>
                      {selectedSubscription.is_trial ? t("admin.subscription.freeTrial") : (selectedSubscription.status?.charAt(0).toUpperCase() + selectedSubscription.status?.slice(1) || 'Unknown')}
                    </span>
                  )}
                </div>
              </div>

              {/* Subscription Details */}
              <div className="mb-6">
                <h4 className="text-sm font-semibold text-gray-900 mb-4">{t("admin.modals.currentSubscription")}</h4>
                <div className="grid grid-cols-2 gap-4">
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-xs text-gray-500 mb-1">{t("admin.modals.plan")}</p>
                    <p className="text-sm font-medium text-gray-900">{selectedSubscription.plan?.name || '-'}</p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-xs text-gray-500 mb-1">{t("admin.subscription.billingCycle")}</p>
                    <p className="text-sm font-medium text-gray-900">{formatBillingCycle(selectedSubscription.billing_cycle)}</p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-xs text-gray-500 mb-1">{t("admin.modals.amount")}</p>
                    <p className="text-sm font-medium text-gray-900">{formatCurrency(selectedSubscription.amount, selectedSubscription.currency, selectedSubscription.is_trial)}</p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-xs text-gray-500 mb-1">{t("admin.subscription.renewalDate")}</p>
                    <p className="text-sm font-medium text-gray-900">{formatDate(selectedSubscription.renewal_date || selectedSubscription.expires_at)}</p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-xs text-gray-500 mb-1">{t("admin.modals.startedAt")}</p>
                    <p className="text-sm font-medium text-gray-900">{formatDate(selectedSubscription.started_at)}</p>
                  </div>
                  <div className="bg-gray-50 rounded-lg p-4">
                    <p className="text-xs text-gray-500 mb-1">{t("admin.modals.expiresAt")}</p>
                    <p className="text-sm font-medium text-gray-900">{formatDate(selectedSubscription.expires_at)}</p>
                  </div>
                  {selectedSubscription.canceled_at && (
                    <div className="bg-red-50 rounded-lg p-4 col-span-2">
                      <p className="text-xs text-red-400 mb-1">{t("admin.modals.cancelledOn")}</p>
                      <p className="text-sm font-medium text-red-700">{formatDate(selectedSubscription.canceled_at)}</p>
                    </div>
                  )}
                </div>
              </div>

              {/* User Subscription History */}
              <div>
                <h4 className="text-sm font-semibold text-gray-900 mb-4">
                  {t("admin.subscription.subscriptionHistory")}
                  <span className="ml-2 text-xs font-normal text-gray-500">
                    ({userSubscriptionHistory.length} {userSubscriptionHistory.length === 1 ? 'record' : 'records'})
                  </span>
                </h4>
                {userSubscriptionHistory.length > 0 ? (
                  <div className="space-y-3 max-h-60 overflow-y-auto">
                    {userSubscriptionHistory.map((sub) => (
                      <div
                        key={sub.uuid}
                        className={`p-4 rounded-lg border ${
                          sub.uuid === selectedSubscription?.uuid
                            ? 'border-[#3B9EC9] bg-blue-50'
                            : 'border-gray-200 bg-gray-50'
                        }`}
                      >
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm font-medium text-gray-900">
                            {sub.plan?.name || 'Unknown Plan'}
                          </span>
                          <span className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full ${
                            sub.is_trial ? 'bg-blue-100 text-blue-600'
                            : sub.status === 'active' ? 'bg-green-100 text-green-600'
                            : sub.status === 'cancelled' ? 'bg-red-100 text-red-600'
                            : sub.status === 'past_due' ? 'bg-orange-100 text-orange-600'
                            : sub.status === 'incomplete' ? 'bg-yellow-100 text-yellow-600'
                            : 'bg-gray-100 text-gray-600'
                          }`}>
                            <span className={`w-1.5 h-1.5 rounded-full ${
                              sub.is_trial ? 'bg-blue-500'
                              : sub.status === 'active' ? 'bg-green-500'
                              : sub.status === 'cancelled' ? 'bg-red-500'
                              : sub.status === 'past_due' ? 'bg-orange-500'
                              : sub.status === 'incomplete' ? 'bg-yellow-500'
                              : 'bg-gray-500'
                            }`}></span>
                            {sub.is_trial ? t("admin.subscription.freeTrial") : sub.status}
                          </span>
                        </div>
                        <div className="grid grid-cols-3 gap-2 text-xs text-gray-500">
                          <div>
                            <span className="block text-gray-400">{t("admin.modals.amount")}</span>
                            {formatCurrency(sub.amount, sub.currency, sub.is_trial)}
                          </div>
                          <div>
                            <span className="block text-gray-400">{t("admin.modals.startedAt")}</span>
                            {formatDate(sub.started_at)}
                          </div>
                          <div>
                            <span className="block text-gray-400">{t("admin.modals.expiresAt")}</span>
                            {formatDate(sub.expires_at)}
                          </div>
                        </div>
                        {sub.uuid === selectedSubscription?.uuid && (
                          <div className="mt-2 pt-2 border-t border-gray-200 text-xs text-[#3B9EC9]">
                            {t("admin.subscription.currentlyViewing")}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                ) : (
                  <div className="bg-gray-50 rounded-lg p-6 text-center">
                    <p className="text-sm text-gray-500">{t("admin.subscription.noHistory")}</p>
                  </div>
                )}
              </div>
            </div>

            {/* Footer with Actions */}
            <div className="px-6 py-4 border-t border-gray-200 flex justify-between items-center">
              <div className="flex items-center gap-3">
                {/* Revoke Complimentary — only on ACTIVE complimentary subs.
                    Hidden on cancelled/expired comp subs (Grant Again replaces it). */}
                {selectedSubscription?.is_complimentary && selectedSubscription.status === 'active' && (
                  <button
                    onClick={() => handleRevokeComplimentary(selectedSubscription)}
                    disabled={isRevoking}
                    className="px-4 py-2 text-sm text-red-500 border border-red-200 rounded-full hover:bg-red-50 transition disabled:opacity-50 cursor-pointer"
                  >
                    {isRevoking ? (
                      <span className="flex items-center gap-2">
                        <div className="w-4 h-4 border-2 border-red-400 border-t-transparent rounded-full animate-spin"></div>
                        Revoking...
                      </span>
                    ) : (
                      "Revoke Complimentary Access"
                    )}
                  </button>
                )}

                {/* Grant Again — for users whose comp sub was revoked or auto-expired.
                    Reuses GrantComplimentaryModal (existing-user mode). */}
                {isRegrantEligible(selectedSubscription) && selectedSubscription?.user && (
                  <button
                    onClick={() => handleOpenRegrant(selectedSubscription)}
                    className="inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-white bg-emerald-600 hover:bg-emerald-700 rounded-full transition cursor-pointer"
                    title="Grant Therapist Manager access again to this user"
                  >
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v7a2 2 0 002 2h10a2 2 0 002-2v-7" />
                    </svg>
                    Grant Again
                  </button>
                )}
                {/*
                  Show Cancel only for recurring subscriptions (monthly / yearly) or trials.
                  Hide for one-time payments and complimentary records — both have no Stripe
                  subscription to cancel.
                */}
                {(() => {
                  const isCancellableStatus = ['active', 'past_due', 'paused'].includes(selectedSubscription?.status ?? '');
                  const cycle = selectedSubscription?.billing_cycle?.toLowerCase() ?? '';
                  const isRecurring = cycle === 'monthly' || cycle === 'yearly' || cycle === 'annual';
                  const isCancellable = isCancellableStatus && (selectedSubscription?.is_trial || isRecurring);
                  if (!isCancellable) return null;
                  return (
                    <button
                      onClick={() => handleCancelSubscription(selectedSubscription.uuid)}
                      disabled={actionLoading}
                      className="px-4 py-2 text-sm text-red-500 border border-red-200 rounded-full hover:bg-red-50 transition disabled:opacity-50 cursor-pointer"
                    >
                      {actionLoading ? (
                        <span className="flex items-center gap-2">
                          <div className="w-4 h-4 border-2 border-red-400 border-t-transparent rounded-full animate-spin"></div>
                          {t("admin.subscription.cancelling")}
                        </span>
                      ) : (
                        t("admin.subscription.cancelSubscription")
                      )}
                    </button>
                  );
                })()}
              </div>
              <button
                onClick={handleCloseViewModal}
                className="px-6 py-2.5 border border-gray-300 rounded-full text-gray-600 font-medium hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Revoke Complimentary Confirmation Modal */}
      {revokeConfirmOpen && subscriptionToRevoke && (
        <div
          className="fixed inset-0 z-[60] 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/40"
            onClick={handleCancelRevoke}
          />

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-md mx-4 p-8"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Close button */}
            <button
              onClick={handleCancelRevoke}
              disabled={isRevoking}
              className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition cursor-pointer disabled:opacity-50"
              aria-label="Close"
            >
              <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-5">
              <div className="w-14 h-14 rounded-full bg-red-50 flex items-center justify-center">
                <svg className="w-7 h-7 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" />
                </svg>
              </div>
            </div>

            {/* Title */}
            <h3 className="text-lg font-semibold text-gray-900 text-center mb-4">
              Revoke complimentary access for{' '}
              <span className="text-gray-900">
                {subscriptionToRevoke.user?.username || 'this user'}
              </span>
              ?
            </h3>

            {/* Body copy */}
            <div className="text-sm text-gray-600 space-y-3 mb-6">
              <ul className="list-disc pl-5 space-y-1.5">
                <li>Their subscription will be cancelled and they will be logged out immediately.</li>
                <li>Their account will be removed from the user list.</li>
                {subscriptionToRevoke.user?.email && (
                  <li>
                    The email{' '}
                    <span className="font-medium text-gray-900">{subscriptionToRevoke.user.email}</span>
                    {' '}will be freed so they can sign up again or be re-invited.
                  </li>
                )}
              </ul>
              <p className="text-xs text-gray-500">
                Past data (clients, screenings, audit) is preserved.
              </p>
            </div>

            {/* Actions */}
            <div className="flex gap-3 justify-end">
              <button
                onClick={handleCancelRevoke}
                disabled={isRevoking}
                className="px-5 py-2.5 border border-gray-300 rounded-full text-sm font-medium text-gray-600 hover:bg-gray-50 transition cursor-pointer disabled:opacity-50"
              >
                Cancel
              </button>
              <button
                onClick={handleConfirmRevoke}
                disabled={isRevoking}
                className="inline-flex items-center gap-2 px-5 py-2.5 bg-red-500 hover:bg-red-600 rounded-full text-sm font-medium text-white transition cursor-pointer disabled:opacity-50"
              >
                {isRevoking ? (
                  <>
                    <span className="w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin" />
                    Revoking...
                  </>
                ) : (
                  'Revoke'
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Grant Again Modal — reuses GrantComplimentaryModal in existing-user mode.
          Modal shows pre-selected user info + Duration + Reason; submit hits
          POST /v1/subscriptions/grant-complimentary with the user_uuid.
          Backend must allow re-grant when prior comp sub is cancelled (currently 409 — see BE spec). */}
      <GrantComplimentaryModal
        isOpen={regrantModalOpen}
        onClose={handleCloseRegrant}
        user={userToRegrant}
        onGranted={handleRegrantSuccess}
      />
    </>
  );
}
