"use client";

import Image from "next/image";
import { useState, useEffect, useCallback, useMemo } from "react";
import { useTranslations } from "next-intl";
import dynamic from "next/dynamic";
import deleteAnimation from "@/public/animations/delete.json";
import invitationSentAnimation from "@/public/images/invitation-sent.json";
import { customInstance } from "@/config/axios";
import { normalizeEmail, isEmailAlreadyExistsError } from "@/lib/email";
import toast from "react-hot-toast";
import GrantComplimentaryModal from "@/components/admin/GrantComplimentaryModal";

const Lottie = dynamic(() => import("lottie-react"), { ssr: false });

interface User {
  uuid: string;
  username: string;
  name?: string;
  email: string;
  avatar: string | null;
  profile_photo?: string | null;
  is_active: boolean;
  created_at: string;
  role: string | { uuid: string; name: string } | null;
  coverage?: { manager_uuid: string; manager_name: string } | null;
}

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;
  status: string;
  amount?: number;
  currency?: string;
  started_at?: string | null;
  expires_at?: string | null;
  is_complimentary?: boolean;
}

export default function AdminUsers() {
  const t = useTranslations();
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("");
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);
  const [allUsers, setAllUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [subscriptionMap, setSubscriptionMap] = useState<Map<string, Subscription>>(new Map());
  const [viewSubscriptionModal, setViewSubscriptionModal] = useState(false);
  const [selectedSubscription, setSelectedSubscription] = useState<Subscription | null>(null);
  const [togglingStatus, setTogglingStatus] = useState<string | null>(null);
  const [statusUpdateModal, setStatusUpdateModal] = useState<{ show: boolean; isActive: boolean }>({ show: false, isActive: false });

  // View User Modal state
  const [viewUserModal, setViewUserModal] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);

  // Grant Complimentary Modal state
  const [grantModalOpen, setGrantModalOpen] = useState(false);
  const [userToGrant, setUserToGrant] = useState<User | null>(null);

  // Filter state (applied)
  const [filterRole, setFilterRole] = useState("");
  const [filterStatus, setFilterStatus] = useState("");
  // Filter state (temp — shown in dropdown before Apply)
  const [tempFilterRole, setTempFilterRole] = useState("");
  const [tempFilterStatus, setTempFilterStatus] = useState("");
  const [filterOpen, setFilterOpen] = useState(false);

  // Add User Modal state
  const [addUserModal, setAddUserModal] = useState(false);
  const [addUserLoading, setAddUserLoading] = useState(false);
  const [invitationSentModal, setInvitationSentModal] = useState(false);
  const [newUser, setNewUser] = useState({
    name: '',
    email: '',
    role: '' as 'Individuals' | 'Practitioners' | '',
  });

  const fetchUsers = useCallback(async () => {
    try {
      setLoading(true);
      const params: Record<string, string | number> = {
        page: 1,
        limit: 10000,
      };

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

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

      setAllUsers(usersResponse.data.users || []);
    } catch (error) {
      console.error('Error fetching users:', error);
      setAllUsers([]);
    } finally {
      setLoading(false);
    }
  }, [sortBy]);

  // Client-side filtering
  const filteredUsers = useMemo(() => {
    let result = allUsers;

    // Search filter
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim();
      result = result.filter(user => {
        const name = (user.name || user.username || '').toLowerCase();
        const email = (user.email || '').toLowerCase();
        const role = typeof user.role === 'string' ? user.role.toLowerCase() : (user.role?.name || '').toLowerCase();
        return name.includes(query) || email.includes(query) || role.includes(query);
      });
    }

    // Role filter
    if (filterRole) {
      result = result.filter(user => {
        const role = typeof user.role === 'string' ? user.role : (user.role?.name || '');
        return role.toLowerCase() === filterRole.toLowerCase();
      });
    }

    // Status filter
    if (filterStatus) {
      const isActive = filterStatus === 'active';
      result = result.filter(user => user.is_active === isActive);
    }

    return result;
  }, [allUsers, searchQuery, filterRole, filterStatus]);

  const activeFilterCount = [filterRole, filterStatus].filter(Boolean).length;

  const handleOpenFilter = () => {
    setTempFilterRole(filterRole);
    setTempFilterStatus(filterStatus);
    setFilterOpen(true);
  };

  const handleApplyFilters = () => {
    setFilterRole(tempFilterRole);
    setFilterStatus(tempFilterStatus);
    setFilterOpen(false);
    setCurrentPage(1);
  };

  const handleClearFilters = () => {
    setTempFilterRole("");
    setTempFilterStatus("");
  };

  // Close filter dropdown on outside click
  useEffect(() => {
    if (!filterOpen) return;
    const handler = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.filter-dropdown')) {
        setFilterOpen(false);
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [filterOpen]);

  // Client-side pagination
  const totalCount = filteredUsers.length;
  const totalPages = Math.max(1, Math.ceil(totalCount / itemsPerPage));
  const users = useMemo(() => {
    const start = (currentPage - 1) * itemsPerPage;
    return filteredUsers.slice(start, start + itemsPerPage);
  }, [filteredUsers, currentPage, itemsPerPage]);

  const fetchSubscriptions = useCallback(async () => {
    try {
      const response = await customInstance<{
        data: {
          subscriptions: Subscription[];
        };
      }>({
        url: '/v1/subscriptions',
        method: 'GET',
        params: { limit: 1000 }, // Get all subscriptions
      });

      // Create a map of user UUID to their subscription
      const subMap = new Map<string, Subscription>();
      (response.data.subscriptions || []).forEach((sub) => {
        if (sub.user?.uuid) {
          // Keep the most recent/active subscription for each user
          const existing = subMap.get(sub.user.uuid);
          if (!existing || sub.status === 'active') {
            subMap.set(sub.user.uuid, sub);
          }
        }
      });
      setSubscriptionMap(subMap);
    } catch (error) {
      console.error('Error fetching subscriptions:', error);
    }
  }, []);

  useEffect(() => {
    fetchUsers();
    fetchSubscriptions();
  }, [sortBy]);

  // Reset to page 1 when search changes
  useEffect(() => {
    setCurrentPage(1);
  }, [searchQuery]);

  // Clamp currentPage if it exceeds totalPages
  useEffect(() => {
    if (currentPage > totalPages) {
      setCurrentPage(totalPages);
    }
  }, [totalPages, currentPage]);

  const handleDeleteClick = (user: User) => {
    setUserToDelete(user);
    setDeleteModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!userToDelete) return;
    try {
      await customInstance({
        url: `/v1/admin/users/${userToDelete.uuid}`,
        method: 'DELETE',
      });
      fetchUsers();
      toast.success(t("admin.users.deleteSuccess"));
    } catch (error: unknown) {
      // Backend now returns a descriptive 400 when a user has linked records (clients,
      // subscriptions, screenings, payments, etc.) — surface that message to the admin so
      // they know which records to clean up first.
      const status = (error as { response?: { status?: number } })?.response?.status;
      const msg = (error as { response?: { data?: { message?: string } } })?.response?.data?.message;
      if (status === 404) {
        toast(msg || t("admin.users.userAlreadyRemoved"));
        fetchUsers();
      } else {
        toast.error(msg || t("admin.users.deleteFailed"));
      }
      console.error('Error deleting user:', error);
    } finally {
      setDeleteModalOpen(false);
      setUserToDelete(null);
    }
  };

  const handleCancelDelete = () => {
    setDeleteModalOpen(false);
    setUserToDelete(null);
  };

  const handleToggleStatus = async (user: User) => {
    setTogglingStatus(user.uuid);
    const newStatus = !user.is_active;

    // Optimistically update UI
    setAllUsers(prev =>
      prev.map(u => u.uuid === user.uuid ? { ...u, is_active: newStatus } : u)
    );

    try {
      await customInstance({
        url: `/v1/admin/users/${user.uuid}/status`,
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        data: { is_active: newStatus },
      });
      setStatusUpdateModal({ show: true, isActive: newStatus });
    } catch (error: unknown) {
      // Revert on error
      setAllUsers(prev =>
        prev.map(u => u.uuid === user.uuid ? { ...u, is_active: user.is_active } : u)
      );
      console.error('Error updating status:', error);
      toast.error(t("admin.dashboard.statusUpdateFailed"));
    } finally {
      setTogglingStatus(null);
    }
  };

  const getRoleName = (role: string | { uuid: string; name: string } | null | undefined): string => {
    if (!role) return '';
    if (typeof role === 'string') return role;
    return role.name || '';
  };

  const getUserDisplayName = (user: User): string => {
    return user.name || user.username || 'Unknown';
  };

  const getUserAvatar = (user: User): string | null => {
    return user.avatar || user.profile_photo || null;
  };

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

  const formatCurrency = (amount: number | undefined, currency: string | undefined) => {
    if (!amount) return '-';
    const symbol = currency === 'USD' ? '$' : (currency || '$');
    return `${symbol}${amount.toLocaleString()}`;
  };

  const formatBillingCycle = (cycle: string | null | undefined) => {
    if (!cycle || cycle === 'none') return '-';
    if (cycle === 'monthly') return t("admin.plans.monthly");
    if (cycle === 'annual' || cycle === 'yearly') return t("admin.plans.annual");
    return cycle.charAt(0).toUpperCase() + cycle.slice(1);
  };

  const translateRole = (roleName: string | undefined): string => {
    if (!roleName) return t("admin.users.roles.Unknown");
    // Try to get translation, fallback to original name
    const translationKey = `admin.users.roles.${roleName}`;
    const translated = t(translationKey);
    // If translation key is returned as-is, it means no translation exists
    return translated === translationKey ? roleName : translated;
  };

  const getRoleColorClasses = (roleName: string | undefined): { bg: string; text: string; dot: string } => {
    if (!roleName) {
      return { bg: 'bg-gray-50', text: 'text-gray-600', dot: 'bg-gray-400' };
    }

    const name = roleName.toLowerCase();

    if (name.includes('individual')) {
      return { bg: 'bg-blue-50', text: 'text-blue-600', dot: 'bg-blue-500' };
    }

    if (name.includes('therapist') || name.includes('practitioner')) {
      return { bg: 'bg-teal-50', text: 'text-teal-600', dot: 'bg-teal-500' };
    }

    if (name.includes('admin')) {
      return { bg: 'bg-purple-50', text: 'text-purple-600', dot: 'bg-purple-500' };
    }

    // Default gray for unknown roles
    return { bg: 'bg-gray-50', text: 'text-gray-600', dot: 'bg-gray-400' };
  };

  const getUserSubscription = (userUuid: string): Subscription | undefined => {
    return subscriptionMap.get(userUuid);
  };

  const handleViewSubscription = (subscription: Subscription) => {
    setSelectedSubscription(subscription);
    setViewSubscriptionModal(true);
  };

  const handleCloseSubscriptionModal = () => {
    setViewSubscriptionModal(false);
    setSelectedSubscription(null);
  };

  // View User handlers
  const handleViewUser = (user: User) => {
    setSelectedUser(user);
    setViewUserModal(true);
  };

  const handleCloseViewUserModal = () => {
    setViewUserModal(false);
    setSelectedUser(null);
  };

  const handleGrantClick = (user: User) => {
    setUserToGrant(user);
    setGrantModalOpen(true);
  };

  const handleCloseGrantModal = () => {
    setGrantModalOpen(false);
    setUserToGrant(null);
  };

  const handleGrantSuccess = async () => {
    // Jump to page 1 so the freshly-created user is visible at the top
    // (default sort is created_at DESC) without admin having to navigate back.
    setCurrentPage(1);
    // Refetch users AND subscriptions — the new user has a complimentary
    // sub and the row needs both pieces to render the right badge.
    await Promise.all([fetchUsers(), fetchSubscriptions()]);
  };

  // Add User handlers
  const handleOpenAddUserModal = () => {
    setNewUser({
      name: '',
      email: '',
      role: '',
    });
    setAddUserModal(true);
  };

  const handleCloseAddUserModal = () => {
    setAddUserModal(false);
    setNewUser({
      name: '',
      email: '',
      role: '',
    });
  };

  const handleAddUser = async () => {
    // Validation
    if (!newUser.name || !newUser.email || !newUser.role) {
      toast.error(t("admin.users.fillAllFields"));
      return;
    }

    // Email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(newUser.email)) {
      toast.error(t("admin.users.invalidEmail"));
      return;
    }

    setAddUserLoading(true);
    try {
      await customInstance({
        url: '/v1/admin/users/invite',
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        data: {
          name: newUser.name,
          email: normalizeEmail(newUser.email),
          role: newUser.role,
        },
      });

      handleCloseAddUserModal();
      setInvitationSentModal(true);
      fetchUsers();
    } catch (error: unknown) {
      if (isEmailAlreadyExistsError(error)) {
        toast.error(t("auth.emailAlreadyRegistered"));
        return;
      }
      console.error('Error sending invitation:', error);
      const err = error as { response?: { data?: { message?: string } } };
      const errorMessage = err?.response?.data?.message || t("admin.users.invitationFailed");
      toast.error(errorMessage);
    } finally {
      setAddUserLoading(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 && allUsers.length === 0) {
    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">
        {/* Users 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.users.title")}
                {totalCount > 0 && (
                  <span className="ml-2 text-sm font-normal text-gray-500">
                    ({t("admin.users.userCount", { count: totalCount })})
                  </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 */}
                <div className="relative">
                  <select
                    value={sortBy}
                    onChange={(e) => setSortBy(e.target.value)}
                    className="appearance-none pl-4 pr-8 py-2 border border-gray-200 rounded-full text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] min-w-[120px] cursor-pointer bg-white"
                  >
                    <option value="">{t("admin.common.sortBy")}</option>
                    <option value="created_at">{t("admin.common.newest")}</option>
                    <option value="updated_at">{t("admin.common.recentlyUpdated")}</option>
                  </select>
                  <svg className="pointer-events-none absolute right-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="M19 9l-7 7-7-7" />
                  </svg>
                </div>

                {/* Filter Button + Dropdown */}
                <div className="relative filter-dropdown">
                  <button
                    onClick={handleOpenFilter}
                    className="flex items-center gap-2 px-4 py-2 border border-gray-200 rounded-full text-sm text-gray-600 hover:bg-gray-50 transition bg-white cursor-pointer"
                  >
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 11-3 0m3 0a1.5 1.5 0 10-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-9.75 0h9.75" />
                    </svg>
                    {t("admin.common.filter")}
                    {activeFilterCount > 0 && (
                      <span className="w-5 h-5 flex items-center justify-center rounded-full bg-[#3B9EC9] text-white text-xs font-medium">
                        {activeFilterCount}
                      </span>
                    )}
                  </button>

                  {filterOpen && (
                    <div className="filter-dropdown absolute right-0 top-full mt-2 w-64 bg-white border border-gray-200 rounded-xl shadow-lg z-50 p-4">
                      <p className="text-sm font-semibold text-gray-700 mb-3">{t("admin.users.filterBy")}</p>

                      {/* Role Filter */}
                      <div className="mb-3">
                        <label className="block text-xs font-medium text-gray-500 mb-1">{t("admin.users.role")}</label>
                        <select
                          value={tempFilterRole}
                          onChange={(e) => setTempFilterRole(e.target.value)}
                          className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                        >
                          <option value="">{t("admin.users.allRoles")}</option>
                          <option value="Individuals">{t("admin.users.roles.Individuals")}</option>
                          <option value="Practitioners">{t("admin.users.roles.Practitioners")}</option>
                        </select>
                      </div>

                      {/* Status Filter */}
                      <div className="mb-4">
                        <label className="block text-xs font-medium text-gray-500 mb-1">{t("admin.users.status")}</label>
                        <select
                          value={tempFilterStatus}
                          onChange={(e) => setTempFilterStatus(e.target.value)}
                          className="w-full px-3 py-2 border border-gray-200 rounded-lg text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                        >
                          <option value="">{t("admin.users.allStatus")}</option>
                          <option value="active">{t("admin.users.active")}</option>
                          <option value="inactive">{t("admin.users.inactive")}</option>
                        </select>
                      </div>

                      {/* Actions */}
                      <div className="flex items-center gap-2">
                        <button
                          onClick={handleClearFilters}
                          className="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 hover:bg-gray-50 transition cursor-pointer"
                        >
                          {t("admin.common.clear")}
                        </button>
                        <button
                          onClick={handleApplyFilters}
                          className="flex-1 px-3 py-2 bg-[#3B9EC9] text-white rounded-lg text-sm font-medium hover:bg-[#2d8ab5] transition cursor-pointer"
                        >
                          {t("admin.common.apply")}
                        </button>
                      </div>
                    </div>
                  )}
                </div>

                {/* Grant Access Button — Therapist Manager free access */}
                <button
                  onClick={() => {
                    setUserToGrant(null);
                    setGrantModalOpen(true);
                  }}
                  className="inline-flex items-center gap-1.5 px-4 py-2 bg-emerald-600 text-white text-sm font-medium rounded-full hover:bg-emerald-700 transition cursor-pointer"
                  title="Grant Therapist Manager access for free"
                >
                  <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 Access
                </button>

                {/* Add User Button */}
                <button
                  onClick={handleOpenAddUserModal}
                  className="px-4 py-2 bg-[#3B9EC9] text-white text-sm font-medium rounded-full hover:bg-[#2d8ab5] transition cursor-pointer"
                >
                  {t("admin.dashboard.addUser")}
                </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-[700px]">
              <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.users.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.users.date")}</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.users.role")}</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.users.subscription")}</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.users.status")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-300">{t("admin.users.action")}</th>
                </tr>
              </thead>
              <tbody>
                {users.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-5 py-8 text-center text-gray-500">
                      {t("admin.common.noUsersFound")}
                    </td>
                  </tr>
                ) : (
                  users.map((user, index) => {
                    const subscription = getUserSubscription(user.uuid);
                    const displayName = getUserDisplayName(user);
                    const avatarUrl = getUserAvatar(user);
                    const roleName = getRoleName(user.role);
                    return (
                    <tr key={user.uuid} className="hover:bg-gray-50/50 transition">
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== users.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <div className="flex items-center gap-3">
                          {avatarUrl && avatarUrl.startsWith('http') ? (
                            <img
                              src={avatarUrl}
                              alt=""
                              className="w-10 h-10 rounded-full object-cover flex-shrink-0"
                              onError={(e) => {
                                const target = e.currentTarget;
                                target.onerror = null;
                                target.style.display = 'none';
                                const fallback = target.nextElementSibling as HTMLElement;
                                if (fallback) fallback.style.display = 'flex';
                              }}
                            />
                          ) : null}
                          <div
                            className="w-10 h-10 rounded-full bg-gray-200 flex-shrink-0 items-center justify-center overflow-hidden"
                            style={{ display: avatarUrl && avatarUrl.startsWith('http') ? 'none' : 'flex' }}
                          >
                            <span className="text-gray-500 text-sm font-medium">
                              {displayName.charAt(0)?.toUpperCase() || 'U'}
                            </span>
                          </div>
                          <div className="min-w-0 flex-1">
                            <p className="text-sm font-medium text-gray-900 truncate">{displayName}</p>
                            <p className="text-xs text-gray-500 truncate">{user.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className={`px-5 py-4 text-sm text-gray-600 border-r border-gray-300 ${index !== users.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {formatDate(user.created_at)}
                      </td>
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== users.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {(() => {
                          const roleColors = getRoleColorClasses(roleName);
                          return (
                            <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full ${roleColors.bg} ${roleColors.text}`}>
                              <span className={`w-1.5 h-1.5 rounded-full ${roleColors.dot}`}></span>
                              {translateRole(roleName)}
                            </span>
                          );
                        })()}
                      </td>
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== users.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        {subscription ? (
                          <button
                            onClick={() => handleViewSubscription(subscription)}
                            className={`inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full transition cursor-pointer ${
                              subscription.is_complimentary ? 'bg-emerald-50 text-emerald-700 hover:bg-emerald-100'
                              : subscription.status === 'active' ? 'bg-green-50 text-green-600 hover:bg-green-100'
                              : subscription.status === 'trialing' ? 'bg-blue-50 text-blue-600 hover:bg-blue-100'
                              : subscription.status === 'cancelled' ? 'bg-red-50 text-red-600 hover:bg-red-100'
                              : subscription.status === 'past_due' ? 'bg-orange-50 text-orange-600 hover:bg-orange-100'
                              : subscription.status === 'incomplete' ? 'bg-yellow-50 text-yellow-600 hover:bg-yellow-100'
                              : 'bg-gray-50 text-gray-600 hover:bg-gray-100'
                            }`}
                          >
                            <span className={`w-1.5 h-1.5 rounded-full ${
                              subscription.is_complimentary ? 'bg-emerald-500'
                              : subscription.status === 'active' ? 'bg-green-500'
                              : subscription.status === 'trialing' ? 'bg-blue-500'
                              : subscription.status === 'cancelled' ? 'bg-red-500'
                              : subscription.status === 'past_due' ? 'bg-orange-500'
                              : subscription.status === 'incomplete' ? 'bg-yellow-500'
                              : 'bg-gray-500'
                            }`}></span>
                            {subscription.is_complimentary ? "Complimentary"
                            : subscription.status === 'active' ? t("admin.users.subscribed")
                            : subscription.status === 'cancelled' ? t("admin.users.cancelled")
                            : subscription.status === 'trialing' ? t("admin.users.trialing")
                            : subscription.status === 'past_due' ? t("admin.users.pastDue")
                            : subscription.status === 'incomplete' ? t("admin.users.incomplete")
                            : t("admin.users.expired")}
                            <svg className="w-3 h-3 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                              <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                          </button>
                        ) : user.coverage ? (
                          <span
                            className="inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full bg-emerald-50 text-emerald-700"
                            title={`Covered by ${user.coverage.manager_name}`}
                          >
                            <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                            {t("admin.users.coveredByManager", { manager: user.coverage.manager_name })}
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1.5 px-3 py-1 text-xs font-medium rounded-full bg-gray-50 text-gray-500">
                            <span className="w-1.5 h-1.5 rounded-full bg-gray-400"></span>
                            {t("admin.users.noSubscription")}
                          </span>
                        )}
                      </td>
                      <td className={`px-5 py-4 border-r border-gray-300 ${index !== users.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <button
                          onClick={() => handleToggleStatus(user)}
                          disabled={togglingStatus === user.uuid}
                          className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:ring-offset-2 ${
                            user.is_active ? 'bg-green-500' : 'bg-gray-300'
                          } ${togglingStatus === user.uuid ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
                        >
                          <span
                            className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
                              user.is_active ? 'translate-x-6' : 'translate-x-1'
                            }`}
                          />
                        </button>
                      </td>
                      <td className={`px-5 py-4 ${index !== users.length - 1 ? 'border-b border-gray-300' : ''}`}>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => handleDeleteClick(user)}
                            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="Delete"
                          >
                            <svg className="w-5 h-5" 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>
                          </button>
                          <button
                            onClick={() => handleViewUser(user)}
                            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="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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                              <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                          </button>
                          {/* Grant Free Access — show icon whenever the user does NOT
                              have a "currently active" subscription. Backend's relaxed
                              conflict check only blocks status=active, so we mirror that:
                              cancelled / expired / no-sub → icon visible (re-grant or fresh grant);
                              active / trialing / past_due / incomplete → icon hidden. */}
                          {roleName === "Practitioners" &&
                            !user.coverage &&
                            !['active', 'trialing', 'past_due', 'incomplete'].includes(subscription?.status ?? '') && (
                            <button
                              onClick={() => handleGrantClick(user)}
                              className="w-9 h-9 rounded-lg bg-emerald-50 flex items-center justify-center text-emerald-500 hover:bg-emerald-100 hover:text-emerald-700 transition cursor-pointer"
                              title="Grant Free Access"
                            >
                              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                                <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>
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  );})
                )}
              </tbody>
            </table>
            </div>
          </div>

          {/* Pagination */}


          {totalPages > 1 && (


          <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>
                </select>
              </div>

              {/* Page navigation */}
              <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>

      {/* Delete Confirmation Modal */}
      {deleteModalOpen && (
        <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={handleCancelDelete}
          ></div>

          {/* 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={handleCancelDelete}
              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 - Lottie Animation */}
            <div className="flex justify-center mb-6">
              <div className="w-36 h-36">
                <Lottie
                  animationData={deleteAnimation}
                  loop={false}
                  autoplay={true}
                />
              </div>
            </div>

            {/* Content */}
            <div className="text-center mb-8">
              <h3 className="text-2xl font-semibold text-[#E05A5A] mb-3">{t("admin.modals.removeUser")}</h3>
              <p className="text-gray-500 text-lg">
                {t("admin.modals.removeUserConfirm")}
              </p>
            </div>

            {/* Actions */}
            <div className="flex gap-4 justify-center">
              <button
                onClick={handleCancelDelete}
                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.modals.close")}
              </button>
              <button
                onClick={handleConfirmDelete}
                className="px-10 py-3 bg-[#E05A5A] rounded-full text-white font-medium hover:bg-[#D04A4A] transition cursor-pointer"
              >
                {t("admin.modals.remove")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Subscription Detail Modal */}
      {viewSubscriptionModal && 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={handleCloseSubscriptionModal}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-lg 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={handleCloseSubscriptionModal}
                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">
              {/* Status Badge */}
              <div className="flex items-center justify-between mb-6">
                <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full ${
                  selectedSubscription.status === 'active' ? 'bg-green-50 text-green-600'
                  : selectedSubscription.status === 'trialing' ? 'bg-blue-50 text-blue-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.status === 'active' ? 'bg-green-500'
                    : selectedSubscription.status === 'trialing' ? 'bg-blue-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.status === 'active' ? t("admin.users.subscribed")
                  : selectedSubscription.status === 'cancelled' ? t("admin.users.cancelled")
                  : selectedSubscription.status === 'trialing' ? t("admin.users.trialing")
                  : selectedSubscription.status === 'past_due' ? t("admin.users.pastDue")
                  : selectedSubscription.status === 'incomplete' ? t("admin.users.incomplete")
                  : t("admin.users.expired")}
                </span>
              </div>

              {/* Subscription Details Grid */}
              <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)}</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="col-span-2 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>
              </div>
            </div>

            {/* Footer */}
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end">
              <button
                onClick={handleCloseSubscriptionModal}
                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>
      )}

      {/* View User Modal */}
      {viewUserModal && selectedUser && (
        <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={handleCloseViewUserModal}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-2xl shadow-xl w-full max-w-lg 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.dashboard.viewUser")}
              </h3>
              <button
                onClick={handleCloseViewUserModal}
                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">
              {/* User Avatar and Name */}
              <div className="flex items-center gap-4 mb-6">
                {getUserAvatar(selectedUser)?.startsWith('http') ? (
                  <Image
                    src={getUserAvatar(selectedUser) || ''}
                    alt=""
                    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">
                      {getUserDisplayName(selectedUser).charAt(0)?.toUpperCase() || 'U'}
                    </span>
                  </div>
                )}
                <div>
                  <h4 className="text-lg font-semibold text-gray-900">{getUserDisplayName(selectedUser)}</h4>
                  <p className="text-sm text-gray-500">{selectedUser.email}</p>
                </div>
              </div>

              {/* Status Badge */}
              <div className="flex items-center justify-between mb-6">
                <span className={`inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full ${
                  selectedUser.is_active
                    ? 'bg-green-50 text-green-600'
                    : 'bg-red-50 text-red-600'
                }`}>
                  <span className={`w-2 h-2 rounded-full ${
                    selectedUser.is_active ? 'bg-green-500' : 'bg-red-500'
                  }`}></span>
                  {selectedUser.is_active ? t("admin.users.active") : t("admin.users.inactive")}
                </span>
              </div>

              {/* User Details Grid */}
              <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.dashboard.role")}</p>
                  <p className="text-sm font-medium text-gray-900">{translateRole(getRoleName(selectedUser.role))}</p>
                </div>
                <div className="bg-gray-50 rounded-lg p-4">
                  <p className="text-xs text-gray-500 mb-1">{t("admin.dashboard.date")}</p>
                  <p className="text-sm font-medium text-gray-900">{formatDate(selectedUser.created_at)}</p>
                </div>
              </div>
            </div>

            {/* Footer */}
            <div className="px-6 py-4 border-t border-gray-200 flex justify-end">
              <button
                onClick={handleCloseViewUserModal}
                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>
      )}

      {/* Add User Modal */}
      {addUserModal && (
        <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={handleCloseAddUserModal}
          ></div>

          {/* Modal */}
          <div
            className="relative bg-white rounded-3xl shadow-xl w-full max-w-md mx-4 overflow-hidden"
            style={{ animation: 'scaleIn 0.3s ease-out' }}
          >
            {/* Content */}
            <div className="p-8">
              {/* Title */}
              <h3 className="text-xl font-bold text-gray-900 mb-6">
                {t("admin.users.addUser")}
              </h3>

              <div className="space-y-5">
                {/* Name */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t("admin.users.name")}
                  </label>
                  <input
                    type="text"
                    value={newUser.name}
                    onChange={(e) => setNewUser(prev => ({ ...prev, name: e.target.value }))}
                    placeholder={t("admin.users.enterNamePlaceholder")}
                    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>

                {/* Email */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t("admin.users.emailLabel")}
                  </label>
                  <input
                    type="email"
                    value={newUser.email}
                    onChange={(e) => setNewUser(prev => ({ ...prev, email: e.target.value }))}
                    placeholder={t("admin.users.enterEmailPlaceholder")}
                    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>

                {/* Role */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    {t("admin.users.role")}
                  </label>
                  <div className="relative">
                    <select
                      value={newUser.role}
                      onChange={(e) => setNewUser(prev => ({ ...prev, role: e.target.value as 'Individuals' | '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.users.selectUserRole")}</option>
                      <option value="Individuals">{t("admin.users.roles.Individuals")}</option>
                      <option value="Practitioners">{t("admin.users.roles.Practitioners")}</option>
                    </select>
                    <div className="absolute right-4 top-1/2 -translate-y-1/2 pointer-events-none">
                      <svg className="w-5 h-5 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>
              </div>
            </div>

            {/* Footer */}
            <div className="px-8 py-5 border-t border-gray-100 flex justify-end gap-3">
              <button
                onClick={handleCloseAddUserModal}
                className="px-8 py-3 border border-gray-300 text-gray-600 text-sm font-medium rounded-full hover:bg-gray-50 transition cursor-pointer"
              >
                {t("admin.modals.cancel")}
              </button>
              <button
                onClick={handleAddUser}
                disabled={addUserLoading}
                className="px-8 py-3 bg-[#3B9EC9] rounded-full text-white font-medium hover:bg-[#2d8ab5] transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                {addUserLoading && (
                  <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"></circle>
                    <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"></path>
                  </svg>
                )}
                {t("admin.users.sendInvitation")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Status Update Success Modal */}
      {statusUpdateModal.show && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
        >
          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/30"
            onClick={() => setStatusUpdateModal({ show: false, isActive: false })}
          ></div>

          {/* 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={() => setStatusUpdateModal({ show: false, isActive: false })}
              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>

            {/* Success Icon */}
            <div className="flex justify-center mb-6">
              <div className={`w-20 h-20 rounded-full flex items-center justify-center ${statusUpdateModal.isActive ? 'bg-green-100' : 'bg-gray-100'}`}>
                <svg className={`w-10 h-10 ${statusUpdateModal.isActive ? 'text-green-500' : 'text-gray-500'}`} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                </svg>
              </div>
            </div>

            {/* Content */}
            <div className="text-center mb-8">
              <h3 className="text-2xl font-semibold text-gray-900 mb-3">
                {statusUpdateModal.isActive ? t("admin.users.userActivated") : t("admin.users.userDeactivated")}
              </h3>
              <p className="text-gray-500">
                {statusUpdateModal.isActive ? t("admin.users.userActivatedDesc") : t("admin.users.userDeactivatedDesc")}
              </p>
            </div>

            {/* Action */}
            <div className="flex justify-center">
              <button
                onClick={() => setStatusUpdateModal({ show: false, isActive: false })}
                className="px-10 py-3 bg-[#3B9EC9] rounded-full text-white font-medium hover:bg-[#2d8ab5] transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Invitation Sent Success Modal */}
      {invitationSentModal && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
        >
          {/* Backdrop */}
          <div
            className="absolute inset-0 bg-black/30"
            onClick={() => setInvitationSentModal(false)}
          ></div>

          {/* 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={() => setInvitationSentModal(false)}
              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>

            {/* Envelope + Checkmark Icon */}
            <div className="flex justify-center mb-6">
              <Lottie
                animationData={invitationSentAnimation}
                loop={true}
                className="w-40 h-40"
              />
            </div>

            {/* Content */}
            <div className="text-center mb-8">
              <h3 className="text-2xl font-semibold text-gray-900 mb-3">
                {t("admin.users.invitationSent")}
              </h3>
              <p className="text-gray-500">
                {t("admin.users.invitationSentDesc")}
              </p>
            </div>

            {/* Action */}
            <div className="flex justify-center">
              <button
                onClick={() => setInvitationSentModal(false)}
                className="px-10 py-3 bg-[#3B9EC9] rounded-full text-white font-medium hover:bg-[#2d8ab5] transition cursor-pointer"
              >
                {t("admin.modals.close")}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Grant Complimentary Access Modal */}
      <GrantComplimentaryModal
        isOpen={grantModalOpen}
        onClose={handleCloseGrantModal}
        user={userToGrant ? { uuid: userToGrant.uuid, name: userToGrant.name, email: userToGrant.email } : null}
        onGranted={handleGrantSuccess}
      />
    </>
  );
}
