"use client";

import { useState, useEffect, useCallback } from "react";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { customInstance } from "@/config/axios";
import { normalizeEmail, isEmailAlreadyExistsError } from "@/lib/email";
import {
  useDashboardControllerGetEarningsChartV1,
} from "@/api/admin/admin-dashboard/admin-dashboard";
import dynamic from "next/dynamic";
import deleteAnimation from "@/public/animations/delete.json";
import invitationSentAnimation from "@/public/animations/invitation-sent.json";
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
} from "recharts";
import toast from "react-hot-toast";

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

interface DashboardStats {
  total_earning: number;
  currency: string;
  total_users: number;
  total_therapists: number;
  total_individuals: number;
  total_screenings: number;
}

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;
}

interface ChartDataPoint {
  label: string;
  value: number;
}

export default function AdminDashboard() {
  const t = useTranslations();
  const router = useRouter();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [earningsPeriod, setEarningsPeriod] = useState<"daily" | "weekly" | "monthly">("monthly");
  const [screeningsPeriod, setScreeningsPeriod] = useState<"daily" | "weekly" | "monthly">("weekly");

  // Recent users state
  const [recentUsers, setRecentUsers] = useState<User[]>([]);
  const [usersLoading, setUsersLoading] = useState(true);
  const [deleteModalOpen, setDeleteModalOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);
  const [viewUserModal, setViewUserModal] = useState(false);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [togglingStatus, setTogglingStatus] = useState<string | null>(null);
  const [statusUpdateModal, setStatusUpdateModal] = useState<{ show: boolean; isActive: boolean }>({ show: false, isActive: false });

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

  // Fetch chart data from API
  const { data: earningsResponse, isLoading: earningsLoading } =
    useDashboardControllerGetEarningsChartV1({ period: earningsPeriod, year: new Date().getFullYear() });
  const earningsData: ChartDataPoint[] = (earningsResponse as any)?.data?.chart_data || [];

  const { data: screeningsResponse, isLoading: screeningsLoading } =
    useQuery({
      queryKey: ['/v1/dashboard/screenings-chart', { period: screeningsPeriod, year: new Date().getFullYear() }],
      queryFn: () => customInstance<void>({ url: '/v1/dashboard/screenings-chart', method: 'GET', params: { period: screeningsPeriod, year: new Date().getFullYear() } }),
    });
  const screeningsData: ChartDataPoint[] = (screeningsResponse as any)?.data?.chart_data || [];

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

  const fetchRecentUsers = useCallback(async () => {
    try {
      setUsersLoading(true);
      const usersResponse = await customInstance<{
        data: {
          users: User[];
          total_count: number;
        };
      }>({
        url: '/v1/admin/users',
        method: 'GET',
        params: {
          page: 1,
          limit: 10,
          sort_field: 'created_at',
          sort_direction: 'DESC',
        },
      });
      setRecentUsers(usersResponse.data.users || []);
    } catch (error) {
      console.error('Error fetching recent users:', error);
      setRecentUsers([]);
    } finally {
      setUsersLoading(false);
    }
  }, []);

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

    // Optimistically update UI
    setRecentUsers(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
      setRecentUsers(prev =>
        prev.map(u => u.uuid === user.uuid ? { ...u, is_active: user.is_active } : u)
      );
      console.error('Error updating status:', error);
      const errorMessage = error instanceof Error ? error.message : t("admin.dashboard.statusUpdateFailed");
      toast.error(errorMessage);
    } finally {
      setTogglingStatus(null);
    }
  };

  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',
      });
      fetchRecentUsers();
      fetchStats();
      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"));
        fetchRecentUsers();
        fetchStats();
      } 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 handleViewUser = (user: User) => {
    setSelectedUser(user);
    setViewUserModal(true);
  };

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

  // Add User modal handlers
  const handleOpenAddUserModal = () => {
    setAddUserModal(true);
  };

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

  const handleAddUser = async () => {
    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();
      setInvitationSuccessModal(true);
      fetchRecentUsers();
      fetchStats();
    } catch (error: unknown) {
      if (isEmailAlreadyExistsError(error)) {
        toast.error(t("auth.emailAlreadyRegistered"));
        return;
      }
      console.error('Error sending invitation:', error);
      const errMsg = (error as any)?.response?.data?.message;
      toast.error(errMsg || t("admin.users.invitationFailed"));
    } finally {
      setAddUserLoading(false);
    }
  };

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

  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 getRoleBadgeColor = (roleName: string | undefined) => {
    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' };
    }
    return { bg: 'bg-gray-50', text: 'text-gray-600', dot: 'bg-gray-400' };
  };

  const translateRole = (roleName: string | undefined): string => {
    if (!roleName) return t("admin.users.roles.Unknown");
    const translationKey = `admin.users.roles.${roleName}`;
    const translated = t(translationKey);
    return translated === translationKey ? roleName : translated;
  };

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      await Promise.all([fetchStats(), fetchRecentUsers()]);
      setLoading(false);
    };
    fetchData();
  }, [fetchStats, fetchRecentUsers]);

  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">
      {/* Stats Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 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}{stats?.currency === 'USD' ? '$' : stats?.currency}
            </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>

        {/* Total User */}
        <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.totalUser")}</p>
            <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.total_users?.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>

        {/* Total Therapists */}
        <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.totalTherapists")}</p>
            <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.total_therapists?.toLocaleString() || 0}</p>
          </div>
          <div className="w-10 h-10 rounded-lg bg-purple-50 flex items-center justify-center">
            <svg className="w-5 h-5 text-purple-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.5z"/>
            </svg>
          </div>
        </div>

        {/* Total Individuals */}
        <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.totalIndividuals")}</p>
            <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.total_individuals?.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="currentColor" viewBox="0 0 24 24">
              <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
            </svg>
          </div>
        </div>

        {/* Total Screenings */}
        <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.totalScreenings")}</p>
            <p className="text-2xl font-bold text-gray-900 mt-1">{stats?.total_screenings?.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="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 002.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 00-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 00.75-.75 2.25 2.25 0 00-.1-.664m-5.8 0A2.251 2.251 0 0113.5 2.25H15c1.012 0 1.867.668 2.15 1.586m-5.8 0c-.376.023-.75.05-1.124.08C9.095 4.01 8.25 4.973 8.25 6.108V8.25m0 0H4.875c-.621 0-1.125.504-1.125 1.125v11.25c0 .621.504 1.125 1.125 1.125h9.75c.621 0 1.125-.504 1.125-1.125V9.375c0-.621-.504-1.125-1.125-1.125H8.25zM6.75 12h.008v.008H6.75V12zm0 3h.008v.008H6.75V15zm0 3h.008v.008H6.75V18z" />
            </svg>
          </div>
        </div>
      </div>

      {/* Charts Section - Side by Side */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Total Earning Chart */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900">{t("admin.dashboard.totalEarning")}</h3>
            <select
              value={earningsPeriod}
              onChange={(e) => setEarningsPeriod(e.target.value as "daily" | "weekly" | "monthly")}
              className="text-sm border border-gray-200 rounded-lg px-3 py-1.5 text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] bg-white cursor-pointer"
            >
              <option value="monthly">{t("admin.dashboard.monthly")}</option>
              <option value="weekly">{t("admin.dashboard.weekly")}</option>
              <option value="daily">{t("admin.dashboard.daily")}</option>
            </select>
          </div>
          <div className="h-[250px]">
            {earningsLoading ? (
              <div className="flex items-center justify-center h-full">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
              </div>
            ) : earningsData.length === 0 ? (
              <div className="flex items-center justify-center h-full text-gray-400 text-sm">
                {t("admin.common.noDataAvailable")}
              </div>
            ) : (
            <ResponsiveContainer width="100%" height={250}>
              <AreaChart data={earningsData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                <defs>
                  <linearGradient id="colorEarnings" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="5%" stopColor="#3B9EC9" stopOpacity={0.3}/>
                    <stop offset="95%" stopColor="#3B9EC9" stopOpacity={0.05}/>
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
                <XAxis
                  dataKey="label"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 11, fill: '#9ca3af' }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 11, fill: '#9ca3af' }}
                  tickFormatter={(value) => {
                    if (value >= 1000) return `${(value / 1000).toFixed(0)}k`;
                    return value.toString();
                  }}
                  width={35}
                />
                <Tooltip
                  formatter={(value) => [Number(value).toLocaleString(), 'Earnings']}
                  contentStyle={{
                    backgroundColor: '#3B9EC9',
                    border: 'none',
                    borderRadius: '8px',
                    color: '#fff',
                    padding: '8px 12px'
                  }}
                  labelStyle={{ display: 'none' }}
                  itemStyle={{ color: '#fff' }}
                />
                <Area
                  type="monotone"
                  dataKey="value"
                  stroke="#3B9EC9"
                  strokeWidth={2}
                  fillOpacity={1}
                  fill="url(#colorEarnings)"
                />
              </AreaChart>
            </ResponsiveContainer>
            )}
          </div>
        </div>

        {/* Screenings Over Time Chart */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900">{t("admin.dashboard.screeningsOverTime")}</h3>
            <select
              value={screeningsPeriod}
              onChange={(e) => setScreeningsPeriod(e.target.value as "daily" | "weekly" | "monthly")}
              className="text-sm border border-gray-200 rounded-lg px-3 py-1.5 text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] bg-white cursor-pointer"
            >
              <option value="weekly">{t("admin.dashboard.weekly")}</option>
              <option value="monthly">{t("admin.dashboard.monthly")}</option>
              <option value="daily">{t("admin.dashboard.daily")}</option>
            </select>
          </div>
          <div className="h-[250px]">
            {screeningsLoading ? (
              <div className="flex items-center justify-center h-full">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
              </div>
            ) : screeningsData.length === 0 ? (
              <div className="flex items-center justify-center h-full text-gray-400 text-sm">
                {t("admin.common.noDataAvailable")}
              </div>
            ) : (
            <ResponsiveContainer width="100%" height={250}>
              <BarChart data={screeningsData} margin={{ top: 10, right: 10, left: 0, bottom: 0 }}>
                <defs>
                  <linearGradient id="colorScreenings" x1="0" y1="0" x2="0" y2="1">
                    <stop offset="0%" stopColor="#E8EDF2" stopOpacity={1}/>
                    <stop offset="100%" stopColor="#D1D9E0" stopOpacity={1}/>
                  </linearGradient>
                </defs>
                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" vertical={false} />
                <XAxis
                  dataKey="label"
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 11, fill: '#9ca3af' }}
                />
                <YAxis
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 11, fill: '#9ca3af' }}
                  tickFormatter={(value) => {
                    if (value >= 1000) return `${(value / 1000).toFixed(0)},000`;
                    return value.toString();
                  }}
                  width={45}
                />
                <Tooltip
                  formatter={(value) => [Number(value), 'Screenings']}
                  contentStyle={{
                    backgroundColor: '#3B9EC9',
                    border: 'none',
                    borderRadius: '8px',
                    color: '#fff',
                    padding: '8px 12px'
                  }}
                  labelStyle={{ display: 'none' }}
                  itemStyle={{ color: '#fff' }}
                />
                <Bar
                  dataKey="value"
                  fill="url(#colorScreenings)"
                  radius={[20, 20, 0, 0]}
                  barSize={12}
                />
              </BarChart>
            </ResponsiveContainer>
            )}
          </div>
        </div>
      </div>

      {/* Recent User Section */}
      <div className="bg-white rounded-xl border border-gray-200 shadow-sm mt-6">
        {/* Header */}
        <div className="p-5 border-b border-gray-200">
          <div className="flex items-center justify-between">
            <h3 className="text-lg font-semibold text-gray-900">{t("admin.dashboard.recentUser")}</h3>
            <div className="flex items-center gap-3">
              <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>
              <button
                onClick={() => router.push('/admin/users')}
                className="text-sm text-gray-500 hover:text-gray-700 transition cursor-pointer"
              >
                {t("admin.dashboard.seeAll")}
              </button>
            </div>
          </div>
        </div>

        {/* Table */}
        <div className="mx-5 mb-5 mt-5 border border-gray-300 rounded-lg overflow-hidden">
          {usersLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
            </div>
          ) : (
            <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.dashboard.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.dashboard.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.dashboard.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.dashboard.status")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-300">{t("admin.dashboard.action")}</th>
                </tr>
              </thead>
              <tbody>
                {recentUsers.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="px-5 py-8 text-center text-gray-500">
                      {t("admin.common.noUsersFound")}
                    </td>
                  </tr>
                ) : (
                  recentUsers.map((user, index) => {
                    const roleName = getRoleName(user.role);
                    const roleColors = getRoleBadgeColor(roleName);
                    const displayName = getUserDisplayName(user);
                    const avatarUrl = getUserAvatar(user);
                    return (
                      <tr key={user.uuid} className="hover:bg-gray-50/50 transition">
                        <td className={`px-5 py-4 border-r border-gray-300 ${index !== recentUsers.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 !== recentUsers.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          {formatDate(user.created_at)}
                        </td>
                        <td className={`px-5 py-4 border-r border-gray-300 ${index !== recentUsers.length - 1 ? 'border-b border-gray-300' : ''}`}>
                          <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 !== recentUsers.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 !== recentUsers.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>
                          </div>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
            </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>
    )}

    {/* 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"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
          onClick={handleCloseViewModal}
        ></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={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">
            {/* User Avatar and Name */}
            <div className="flex items-center gap-4 mb-6">
              {getUserAvatar(selectedUser)?.startsWith('http') ? (
                <img
                  src={getUserAvatar(selectedUser) || ''}
                  alt=""
                  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={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>
    )}

    {/* 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"
          style={{ animation: 'fadeIn 0.2s ease-out' }}
          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">
            <h3 className="text-xl font-bold text-gray-900 mb-6">{t("admin.users.addUser")}</h3>

            {/* Name Field */}
            <div className="mb-4">
              <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({ ...newUser, name: e.target.value })}
                placeholder={t("admin.users.enterNamePlaceholder")}
                className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent placeholder:text-gray-400"
              />
            </div>

            {/* Email Field */}
            <div className="mb-4">
              <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({ ...newUser, email: e.target.value })}
                placeholder={t("admin.users.enterEmailPlaceholder")}
                className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent placeholder:text-gray-400"
              />
            </div>

            {/* Role Field */}
            <div className="mb-2">
              <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({ ...newUser, role: e.target.value as 'Individuals' | 'Practitioners' | '' })}
                  className="w-full px-4 py-3 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] focus:border-transparent appearance-none bg-white text-gray-900"
                >
                  <option value="" disabled className="text-gray-400">{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 inset-y-0 right-0 flex items-center pr-4 pointer-events-none">
                  <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </div>
            </div>
          </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] text-white text-sm font-medium rounded-full hover:bg-[#2d8ab5] transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {addUserLoading ? (
                <span className="flex items-center gap-2">
                  <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                  </svg>
                  {t("admin.users.sendInvitation")}
                </span>
              ) : (
                t("admin.users.sendInvitation")
              )}
            </button>
          </div>
        </div>
      </div>
    )}

    {/* Invitation Success Modal */}
    {invitationSuccessModal && (
      <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={() => setInvitationSuccessModal(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={() => setInvitationSuccessModal(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>

          {/* Invitation Sent Animation */}
          <div className="flex justify-center mb-6">
            <div className="w-40 h-40">
              <Lottie
                animationData={invitationSentAnimation}
                loop={true}
                autoplay={true}
              />
            </div>
          </div>

          {/* Content */}
          <div className="text-center mb-8">
            <h3 className="text-2xl font-semibold text-[#3B9EC9] 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={() => setInvitationSuccessModal(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>
    )}

    {/* 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>
    )}
  </>
  );
}
