"use client";

import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import { useState, useMemo, useEffect, Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Link } from "@/i18n/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useRouter as useIntlRouter, usePathname } from "@/i18n/navigation";
import FlagIcon from "@/components/ui/FlagIcon";
import { ClipboardList } from "lucide-react";
import AddClientDetailsModal from "@/components/practitioner/modals/AddClientDetailsModal";
import EditClientModal from "@/components/practitioner/modals/EditClientModal";
import DeleteClientModal from "@/components/practitioner/modals/DeleteClientModal";
import SendScreeningInvitationModal from "@/components/practitioner/modals/SendScreeningInvitationModal";
import InvitationSentSuccessModal from "@/components/practitioner/modals/InvitationSentSuccessModal";
import ScreeningInvitationSentModal from "@/components/practitioner/modals/ScreeningInvitationSentModal";
import ScreeningReportsModal from "@/components/practitioner/modals/ScreeningReportsModal";
import UpgradeModal from "@/components/shared/UpgradeModal";
import Pagination from "@/components/common/Pagination";
import { useClientsControllerFindAllV1 } from "@/api/user/practitioner-clients/practitioner-clients";

import { getDashboardControllerGetDashboardStatsV1QueryKey } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { usePractitionerDashboardControllerGetCompletedScreeningsV1, getPractitionerDashboardControllerGetPendingScreeningsV1QueryKey } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { useProfile } from "@/api/user/user-profile/user-profile";
import { useQueryClient } from "@tanstack/react-query";
import { toast } from "react-hot-toast";
import { usePractitionerScreeningControllerStartScreeningV1 } from "@/api/user/practitioner-screening/practitioner-screening";
import { useAssessmentLinksControllerCreateLinkV1 } from "@/api/user/practitioner-assessment-links/practitioner-assessment-links";

interface Client {
  id: number;
  uuid?: string;
  name: string;
  email?: string;
  phone?: string;
  numberOfScreening?: number;
  age?: number;
  gender: string;
}

function ClientsPageInner() {
  const t = useTranslations();
  const locale = useLocale();
  const intlRouter = useIntlRouter();
  const pathname = usePathname();
  const queryClient = useQueryClient();

  // Fetch user profile for dynamic name display
  const { data: profileData } = useProfile();
  const userName = profileData?.data?.user?.name || "User";
  const [searchInput, setSearchInput] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [sortBy, setSortBy] = useState<string>("created_at");
  const [sortOrder, setSortOrder] = useState<"ASC" | "DESC">("DESC");
  // Compound sort value for the select element
  const sortValue = sortBy === "name"
    ? (sortOrder === "ASC" ? "name_asc" : "name_desc")
    : (sortOrder === "ASC" ? "oldest" : "newest");

  // Applied filters (used for actual filtering)
  const [filterGender, setFilterGender] = useState<string>("");
  const [filterAgeRange, setFilterAgeRange] = useState<string>("");

  // Temporary filter values (shown in dropdown, not applied until "Apply" is clicked)
  const [tempFilterGender, setTempFilterGender] = useState<string>("");
  const [tempFilterAgeRange, setTempFilterAgeRange] = useState<string>("");

  const [filterOpen, setFilterOpen] = useState(false);
  const [addClientOpen, setAddClientOpen] = useState(false);
  const [sendInvitationOpen, setSendInvitationOpen] = useState(false);
  const [invitationSentOpen, setInvitationSentOpen] = useState(false);
  const [screeningInvitationSentOpen, setScreeningInvitationSentOpen] = useState(false);
  const [pendingScreeningUuid, setPendingScreeningUuid] = useState<string | null>(null);
  const [upgradeError, setUpgradeError] = useState<{ code: "TRIAL_LIMIT_REACHED" | "TRIAL_EXPIRED" | "TRIAL_REQUIRED"; data?: any } | null>(null);
  const [screeningReportsOpen, setScreeningReportsOpen] = useState(false);
  const [editClientOpen, setEditClientOpen] = useState(false);
  const [deleteClientOpen, setDeleteClientOpen] = useState(false);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [autoOpenScreeningId, setAutoOpenScreeningId] = useState<number | undefined>(undefined);
  const searchParams = useSearchParams();

  const pageSize = 10;

  // Fetch ALL clients from API (with high limit for client-side filtering)
  const {
    data: clientsResponse,
    isLoading: isLoadingClients,
    error,
    refetch,
  } = useClientsControllerFindAllV1(
    {
      page: 1,
      limit: 100, // Fetch more data to enable client-side search/filter
      sortBy: "created_at",
      sortOrder: "DESC" as any, // Cast to any due to incorrect Swagger type generation
    },
    {
      query: {
        queryKey: ["clients"],
      },
    }
  );

  // Fetch completed screenings to count per client
  const { data: completedResponse, isLoading: isLoadingCompleted } = usePractitionerDashboardControllerGetCompletedScreeningsV1(
    { page: 1, limit: 100 }
  );

  const isLoading = isLoadingClients || isLoadingCompleted;

  // Calculate completed screening count per client (pending screenings are not counted)
  const screeningCountByClient = useMemo(() => {
    const counts: Record<number, number> = {};

    ((completedResponse as any)?.data || []).forEach((screening: any) => {
      const clientId = screening.client_id;
      counts[clientId] = (counts[clientId] || 0) + 1;
    });

    return counts;
  }, [completedResponse]);

  // Auto-open report modal when landing from "Assessment Completed" email link
  useEffect(() => {
    const clientIdParam = searchParams.get("clientId");
    const openReportParam = searchParams.get("openReport");
    if (!clientIdParam || !openReportParam) return;

    const allClients: Client[] = (clientsResponse as any)?.data || [];
    if (allClients.length === 0) return;

    const targetId = parseInt(clientIdParam, 10);
    const screeningId = parseInt(openReportParam, 10);
    const client = allClients.find((c: Client) => c.id === targetId);
    if (!client) return;

    setSelectedClient(client);
    setAutoOpenScreeningId(screeningId);
    setScreeningReportsOpen(true);
  }, [searchParams, clientsResponse]);

  // Client-side filtering, searching, and sorting for ALL fields
  const filteredAndSearchedClients = useMemo(() => {
    let filtered = (clientsResponse as any)?.data || [];

    // Search across ALL fields: name, email, phone, age, gender, screening count
    if (searchInput.trim()) {
      const query = searchInput.toLowerCase().trim();
      filtered = filtered.filter((client: Client) => {
        const nameMatch = client.name?.toLowerCase().includes(query);
        const emailMatch = client.email?.toLowerCase().includes(query);
        const phoneMatch = client.phone?.toLowerCase().includes(query);
        const ageMatch = client.age?.toString().includes(query);
        const genderMatch = client.gender?.toLowerCase().includes(query);
        const screeningCount = screeningCountByClient[client.id] || 0;
        const screeningMatch = screeningCount.toString().includes(query);

        return nameMatch || emailMatch || phoneMatch || ageMatch || genderMatch || screeningMatch;
      });
    }

    // Filter by gender dropdown
    if (filterGender) {
      filtered = filtered.filter((client: Client) => client.gender === filterGender);
    }

    // Filter by age range dropdown
    if (filterAgeRange) {
      filtered = filtered.filter((client: Client) => {
        const age = client.age || 0;
        switch(filterAgeRange) {
          case "0-18": return age >= 0 && age <= 18;
          case "19-35": return age >= 19 && age <= 35;
          case "36-50": return age >= 36 && age <= 50;
          case "51+": return age >= 51;
          default: return true;
        }
      });
    }

    // Client-side sorting
    if (sortBy) {
      filtered = [...filtered].sort((a, b) => {
        let aValue: any = "";
        let bValue: any = "";

        switch(sortBy) {
          case "name":
            aValue = a.name?.toLowerCase() || "";
            bValue = b.name?.toLowerCase() || "";
            break;
          case "created_at":
            aValue = a.id || 0; // Use id as proxy for creation order
            bValue = b.id || 0;
            break;
          case "updated_at":
            aValue = a.id || 0; // Use id as proxy for update order
            bValue = b.id || 0;
            break;
          default:
            return 0;
        }

        if (aValue < bValue) return sortOrder === "ASC" ? -1 : 1;
        if (aValue > bValue) return sortOrder === "ASC" ? 1 : -1;
        return 0;
      });
    }

    return filtered;
  }, [(clientsResponse as any)?.data, filterGender, filterAgeRange, searchInput, sortBy, sortOrder, screeningCountByClient]);

  // Client-side pagination
  const totalClients = filteredAndSearchedClients.length;
  const totalPages = Math.ceil(totalClients / pageSize);
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const clients = filteredAndSearchedClients.slice(startIndex, endIndex);

  // Reset to page 1 when search/sort/filter changes
  useEffect(() => {
    setCurrentPage(1);
  }, [searchInput, sortBy, sortOrder, filterGender, filterAgeRange]);

  // Close filter dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      if (filterOpen && !target.closest('.filter-dropdown')) {
        setFilterOpen(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [filterOpen]);

  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return t("practitioner.greetings.morning");
    if (hour < 18) return t("practitioner.greetings.afternoon");
    return t("practitioner.greetings.evening");
  };


  // Start in-person screening mutation (no email, returns screening_uuid)
  const { mutate: startScreening, isPending: isStartingScreening } = usePractitionerScreeningControllerStartScreeningV1({
    mutation: {
      onSuccess: (data: any) => {
        setSendInvitationOpen(false);
        queryClient.invalidateQueries({ queryKey: getPractitionerDashboardControllerGetPendingScreeningsV1QueryKey() });
        queryClient.invalidateQueries({ queryKey: getDashboardControllerGetDashboardStatsV1QueryKey() });
        const screeningUuid = data?.data?.screening_uuid;
        if (screeningUuid && selectedClient?.id) {
          document.body.style.overflow = "";
          intlRouter.push(`/practitioner/screening/${selectedClient.id}?uuid=${screeningUuid}`);
        } else {
          toast.error(t("practitioner.common.startScreeningError"));
        }
      },
      onError: (error: any) => {
        const backendKey = error?.response?.data?.message;
        const errorCode = error?.response?.data?.error;
        setSendInvitationOpen(false);

        if (errorCode === "TRIAL_LIMIT_REACHED" || backendKey === "practitioner.trial_limit_reached") {
          setUpgradeError({ code: "TRIAL_LIMIT_REACHED", data: error?.response?.data?.data });
          return;
        }
        if (errorCode === "TRIAL_EXPIRED" || backendKey === "practitioner.trial_expired") {
          setUpgradeError({ code: "TRIAL_EXPIRED", data: error?.response?.data?.data });
          return;
        }
        if (errorCode === "TRIAL_REQUIRED" || backendKey === "practitioner.trial_required") {
          setUpgradeError({ code: "TRIAL_REQUIRED" });
          return;
        }
        if (errorCode === "SUBSCRIPTION_CANCELLED" || backendKey === "practitioner.subscription_cancelled") {
          toast.error(t("practitioner.subscription_cancelled"), { duration: 5000 });
          intlRouter.push("/practitioner/subscription");
          return;
        }
        toast.error(backendKey || t("practitioner.common.startScreeningFailed"));
      },
    },
  });

  // Send email invitation mutation — patient receives link and takes the test on their own device
  const { mutate: sendScreeningInvitation, isPending: isSendingInvitation } = useAssessmentLinksControllerCreateLinkV1({
    mutation: {
      onSuccess: () => {
        setSendInvitationOpen(false);
        setInvitationSentOpen(true);
      },
      onError: (error: any) => {
        const backendKey = error?.response?.data?.message;
        const errorCode = error?.response?.data?.error;
        setSendInvitationOpen(false);

        if (errorCode === "TRIAL_LIMIT_REACHED" || backendKey === "practitioner.trial_limit_reached") {
          setUpgradeError({ code: "TRIAL_LIMIT_REACHED", data: error?.response?.data?.data });
          return;
        }
        if (errorCode === "TRIAL_EXPIRED" || backendKey === "practitioner.trial_expired") {
          setUpgradeError({ code: "TRIAL_EXPIRED", data: error?.response?.data?.data });
          return;
        }
        if (errorCode === "TRIAL_REQUIRED" || backendKey === "practitioner.trial_required") {
          setUpgradeError({ code: "TRIAL_REQUIRED" });
          return;
        }
        if (errorCode === "SUBSCRIPTION_CANCELLED" || backendKey === "practitioner.subscription_cancelled") {
          toast.error(t("practitioner.subscription_cancelled"), { duration: 5000 });
          intlRouter.push("/practitioner/subscription");
          return;
        }
        toast.error(backendKey || t("practitioner.common.startScreeningFailed"));
      },
    },
  });

  const handleClientAdded = (clientData?: any) => {
    setAddClientOpen(false);
    if (clientData) {
      setSelectedClient({
        id: clientData.id,
        uuid: clientData.uuid,
        name: clientData.name,
        email: clientData.email,
        phone: clientData.phone,
        age: clientData.age,
        gender: clientData.gender,
      });
    }
    refetch();
  };

  const handleSendNow = (client?: Client | null) => {
    const target = client ?? selectedClient;
    if (target?.id) {
      sendScreeningInvitation({ clientId: target.id, data: {} });
    } else {
      toast.error(t("practitioner.common.uuidError"));
      setSendInvitationOpen(false);
    }
  };

  const handleSendLater = (client?: Client | null) => {
    const target = client ?? selectedClient;
    const clientUuid = (target as any)?.uuid;
    if (clientUuid) {
      startScreening({ data: { client_uuid: clientUuid } });
    } else {
      toast.error(t("practitioner.common.uuidError"));
      setSendInvitationOpen(false);
    }
  };

  const handleScreeningInvitationSentClose = () => {
    setScreeningInvitationSentOpen(false);
    if (pendingScreeningUuid && selectedClient?.id) {
      document.body.style.overflow = "";
      intlRouter.push(`/practitioner/screening/${selectedClient.id}?uuid=${pendingScreeningUuid}`);
    }
    setPendingScreeningUuid(null);
  };

  const handleViewReports = (client: Client) => {
    setSelectedClient(client);
    setScreeningReportsOpen(true);
  };

  const handleEditClient = (client: Client) => {
    setSelectedClient(client);
    setEditClientOpen(true);
  };

  const handleDeleteClient = (client: Client) => {
    setSelectedClient(client);
    setDeleteClientOpen(true);
  };


  const handleSortChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    switch (e.target.value) {
      case "newest":   setSortBy("created_at"); setSortOrder("DESC"); break;
      case "oldest":   setSortBy("created_at"); setSortOrder("ASC");  break;
      case "name_asc": setSortBy("name");       setSortOrder("ASC");  break;
      case "name_desc":setSortBy("name");       setSortOrder("DESC"); break;
    }
  };

  const handleOpenFilter = () => {
    // Initialize temp values with current applied filters
    setTempFilterGender(filterGender);
    setTempFilterAgeRange(filterAgeRange);
    setFilterOpen(true);
  };

  const handleApplyFilters = () => {
    // Apply the temp values to actual filters
    setFilterGender(tempFilterGender);
    setFilterAgeRange(tempFilterAgeRange);
    setFilterOpen(false);
  };

  const handleClearFilters = () => {
    // Clear temp values in the dropdown
    setTempFilterGender("");
    setTempFilterAgeRange("");
  };

  const activeFilterCount = [filterGender, filterAgeRange].filter(Boolean).length;

  const ViewIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M2.036 12.322a1.012 1.012 0 010-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178z" />
      <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
    </svg>
  );

  const EditIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
    </svg>
  );

  const DeleteIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0" />
    </svg>
  );


  const SendIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M6 12L3.269 3.126A59.768 59.768 0 0121.485 12 59.77 59.77 0 013.27 20.876L5.999 12zm0 0h7.5" />
    </svg>
  );

  const SearchIcon = () => (
    <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
    </svg>
  );

  const FilterIcon = () => (
    <svg className="w-5 h-5" 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>
  );


  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <div className="flex items-center gap-2">
              <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
              <span className="text-xl font-bold text-gray-900">MBHS</span>
            </div>

            {/* Navigation */}
            <nav className="hidden md:flex items-center gap-8">
              <Link href="/practitioner" className="text-sm font-medium text-gray-600 hover:text-gray-900 cursor-pointer">
                {t("practitioner.nav.dashboard")}
              </Link>
              <Link href="/practitioner/clients" className="text-sm font-medium text-[#3B9EC9] cursor-pointer">
                {t("practitioner.nav.clients")}
              </Link>
              <Link href="/practitioner/subscription" className="text-sm font-medium text-gray-600 hover:text-gray-900 cursor-pointer">
                {t("practitioner.nav.subscription")}
              </Link>
            </nav>

            {/* Right side */}
            <div className="flex items-center gap-4">
              {/* Language Toggle Button */}
              <button
                onClick={() => intlRouter.replace(pathname, { locale: locale === "en" ? "es" : "en" })}
                className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
              <button className="relative p-2 text-gray-400 hover:text-gray-600 cursor-pointer">
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
                </svg>
                <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
              </button>
              <div className="flex items-center gap-2 cursor-pointer">
                <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                  <svg className="w-5 h-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                  </svg>
                </div>
                <span className="text-sm font-medium text-gray-700">{userName}</span>
                <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Welcome Section */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-8">
          <div>
            <h1 className="text-2xl sm:text-3xl font-semibold text-gray-900">
              {getGreeting()}, {userName}
            </h1>
            <p className="mt-1 text-gray-500">
              {t("practitioner.clients.overview")}
            </p>
          </div>
          <button
            onClick={() => setAddClientOpen(true)}
            className="self-start sm:self-auto px-6 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
          >
            {t("practitioner.dashboard.addClient")}
          </button>
        </div>

        {/* Clients Card */}
        <div className="bg-white rounded-2xl border border-gray-300 shadow-sm p-6">
          {/* Card Header */}
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-6">
            <h2 className="text-lg font-semibold text-gray-900">
              {t("practitioner.clients.title")} ({totalClients})
            </h2>
            <div className="flex flex-wrap items-center gap-2">
              {/* Search */}
              <div className="relative flex-1 sm:flex-none">
                <div className="absolute inset-y-0 left-3 flex items-center pointer-events-none">
                  <SearchIcon />
                </div>
                <input
                  type="text"
                  placeholder={t("practitioner.common.searchPlaceholder") || t("practitioner.common.search")}
                  value={searchInput}
                  onChange={(e) => setSearchInput(e.target.value)}
                  className="pl-10 pr-4 py-2.5 w-full sm:w-56 bg-white border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9]"
                />
              </div>
              {/* Sort */}
              <div className="relative">
                <select
                  value={sortValue}
                  onChange={handleSortChange}
                  className="px-4 py-2.5 bg-white border border-gray-200 rounded-full text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9] appearance-none pr-10 cursor-pointer"
                >
                  <option value="newest">{t("practitioner.clients.newest")}</option>
                  <option value="oldest">{t("practitioner.clients.oldest")}</option>
                  <option value="name_asc">{t("practitioner.common.name")} (A–Z)</option>
                  <option value="name_desc">{t("practitioner.common.name")} (Z–A)</option>
                </select>
                <div className="absolute inset-y-0 right-4 flex items-center pointer-events-none">
                  <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>
              </div>
              {/* Filter */}
              <div className="relative filter-dropdown">
                <button
                  onClick={handleOpenFilter}
                  className="flex items-center gap-2 px-4 py-2.5 bg-white border border-gray-200 rounded-full text-sm text-gray-600 hover:bg-gray-50 transition cursor-pointer"
                >
                  <FilterIcon />
                  {t("practitioner.common.filter")}
                  {activeFilterCount > 0 && (
                    <span className="ml-1 px-2 py-0.5 bg-[#3B9EC9] text-white text-xs rounded-full">
                      {activeFilterCount}
                    </span>
                  )}
                </button>

                {/* Filter Dropdown */}
                {filterOpen && (
                  <div className="absolute left-0 sm:left-auto sm:right-0 mt-2 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-50 p-4 filter-dropdown">
                    <div className="flex items-center justify-between mb-3">
                      <h3 className="text-sm font-semibold text-gray-900">{t("practitioner.common.filters")}</h3>
                      <button
                        onClick={() => setFilterOpen(false)}
                        className="text-gray-400 hover:text-gray-600"
                      >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </button>
                    </div>

                    {/* Gender Filter */}
                    <div className="mb-4">
                      <label className="block text-xs font-medium text-gray-700 mb-2">
                        {t("practitioner.clients.gender")}
                      </label>
                      <select
                        value={tempFilterGender}
                        onChange={(e) => setTempFilterGender(e.target.value)}
                        className="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9] cursor-pointer"
                      >
                        <option value="">{t("practitioner.common.all")}</option>
                        <option value="Male">{t("practitioner.clients.male")}</option>
                        <option value="Female">{t("practitioner.clients.female")}</option>
                        <option value="Other">{t("practitioner.clients.other")}</option>
                      </select>
                    </div>

                    {/* Age Range Filter */}
                    <div className="mb-4">
                      <label className="block text-xs font-medium text-gray-700 mb-2">
                        {t("practitioner.clients.ageRange")}
                      </label>
                      <select
                        value={tempFilterAgeRange}
                        onChange={(e) => setTempFilterAgeRange(e.target.value)}
                        className="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9] cursor-pointer"
                      >
                        <option value="">{t("practitioner.common.all")}</option>
                        <option value="0-18">0-18 {t("practitioner.clients.years")}</option>
                        <option value="19-35">19-35 {t("practitioner.clients.years")}</option>
                        <option value="36-50">36-50 {t("practitioner.clients.years")}</option>
                        <option value="51+">51+ {t("practitioner.clients.years")}</option>
                      </select>
                    </div>

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

          {/* Loading State */}
          {isLoading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-[#3B9EC9]"></div>
            </div>
          ) : error ? (
            /* Error State */
            <div className="flex items-center justify-center py-12">
              <div className="text-center">
                <p className="text-[#D12E34] text-sm mb-4">
                  {t("practitioner.clients.errorLoading")}
                </p>
                <button
                  onClick={() => {(refetch as any)();}}
                  className="px-4 py-2 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
                >
                  {t("practitioner.common.retry")}
                </button>
              </div>
            </div>
          ) : clients.length === 0 ? (
            /* Empty State - Matching Figma Design */
            <div className="flex flex-col items-center justify-center py-20">
              {/* Icon - Document with profile and X mark */}
              <div className="mb-6">
                <svg width="80" height="80" viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg">
                  {/* Document outline */}
                  <rect x="16" y="8" width="40" height="52" rx="4" stroke="#1F2937" strokeWidth="2.5" fill="none" />
                  {/* Profile circle */}
                  <circle cx="36" cy="28" r="10" stroke="#1F2937" strokeWidth="2.5" fill="none" />
                  {/* Profile icon inside circle */}
                  <circle cx="36" cy="26" r="4" stroke="#1F2937" strokeWidth="2" fill="none" />
                  <path d="M29 35C29 32 32 30 36 30C40 30 43 32 43 35" stroke="#1F2937" strokeWidth="2" strokeLinecap="round" fill="none" />
                  {/* Lines representing text */}
                  <line x1="24" y1="46" x2="48" y2="46" stroke="#1F2937" strokeWidth="2.5" strokeLinecap="round" />
                  <line x1="24" y1="52" x2="40" y2="52" stroke="#1F2937" strokeWidth="2.5" strokeLinecap="round" />
                  {/* X mark circle */}
                  <circle cx="56" cy="52" r="12" fill="#3B9EC9" />
                  <path d="M51 47L61 57M61 47L51 57" stroke="white" strokeWidth="2.5" strokeLinecap="round" />
                </svg>
              </div>

              {/* Title */}
              <h3 className="text-xl font-bold text-gray-900 mb-2">
                {t("practitioner.clients.noClientFoundTitle")}
              </h3>

              {/* Description */}
              <p className="text-gray-500 text-sm mb-6 text-center max-w-xs">
                {searchInput
                  ? t("practitioner.clients.noResults")
                  : t("practitioner.clients.noClientFoundDescription")}
              </p>

              {/* Add Client Button - Only show when not searching */}
              {!searchInput && (
                <button
                  onClick={() => setAddClientOpen(true)}
                  className="px-8 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-lg hover:bg-[#2D8AB5] transition cursor-pointer"
                >
                  {t("practitioner.clients.addClient")}
                </button>
              )}
            </div>
          ) : (
            /* Table */
            <>
              <div className="overflow-x-auto border border-gray-300 rounded-lg">
                <table className="w-full border-collapse min-w-[700px]">
                  <thead>
                    <tr className="bg-gray-50 border-b border-gray-300">
                      <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-300 min-w-[200px]">{t("practitioner.clients.clientName")}</th>
                      <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-300">{t("practitioner.clients.numberOfScreening")}</th>
                      <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-300">{t("practitioner.clients.reports")}</th>
                      <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-300">{t("practitioner.clients.age")}</th>
                      <th className="text-left py-4 px-4 text-sm font-medium text-gray-500 border-r border-gray-300">{t("practitioner.clients.gender")}</th>
                      <th className="text-center py-4 px-4 text-sm font-medium text-gray-500">{t("practitioner.clients.action")}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {clients.map((client: Client, index: number) => (
                      <tr key={client.id} className={`${index !== clients.length - 1 ? 'border-b border-gray-300' : ''} hover:bg-gray-50/50 transition`}>
                        <td className="py-4 px-4 border-r border-gray-300 min-w-[200px]">
                          <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0">
                              <svg className="w-6 h-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                              </svg>
                            </div>
                            <div>
                              <p className="text-sm font-medium text-gray-900">{client.name}</p>
                              <p className="text-sm text-gray-500">{client.email || client.phone || "-"}</p>
                            </div>
                          </div>
                        </td>
                        <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-300">{screeningCountByClient[client.id] || 0}</td>
                        <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-300">
                          {(screeningCountByClient[client.id] || 0) > 0 ? (
                            <button
                              onClick={() => handleViewReports(client)}
                              className="p-1 text-[#3B9EC9] hover:text-[#2D8AB5] transition cursor-pointer"
                              title={t("practitioner.clients.reports")}
                            >
                              <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.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z" />
                              </svg>
                            </button>
                          ) : (
                            <span className="text-gray-400">-</span>
                          )}
                        </td>
                        <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-300">{client.age || "-"}</td>
                        <td className="py-4 px-4 text-sm text-gray-600 border-r border-gray-300">{client.gender}</td>
                        <td className="py-4 px-4">
                          <div className="flex items-center justify-center gap-3">
                            <button
                              onClick={() => handleViewReports(client)}
                              className="p-2 text-[#3B9EC9] hover:text-[#2D8AB5] transition cursor-pointer"
                              title={t("practitioner.clients.view")}
                            >
                              <ViewIcon />
                            </button>
                            <button
                              onClick={() => { setSelectedClient(client); handleSendLater(client); }}
                              disabled={isStartingScreening && selectedClient?.id === client.id}
                              className="p-2 text-gray-500 hover:text-[#3B9EC9] transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                              title={t("practitioner.modals.sendInvitation.sendLater")}
                            >
                              {isStartingScreening && selectedClient?.id === client.id ? (
                                <svg className="w-5 h-5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                </svg>
                              ) : (
                                <ClipboardList className="w-5 h-5" />
                              )}
                            </button>
                            <button
                              onClick={() => { setSelectedClient(client); handleSendNow(client); }}
                              disabled={isSendingInvitation && selectedClient?.id === client.id}
                              className="p-2 text-[#3B9EC9] hover:text-[#2D8AB5] transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                              title={t("practitioner.clients.sendScreening")}
                            >
                              {isSendingInvitation && selectedClient?.id === client.id ? (
                                <svg className="w-5 h-5 animate-spin" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                </svg>
                              ) : (
                                <SendIcon />
                              )}
                            </button>
                            <button
                              onClick={() => handleEditClient(client)}
                              className="p-2 text-gray-500 hover:text-[#3B9EC9] transition cursor-pointer"
                              title={t("practitioner.clients.edit")}
                            >
                              <EditIcon />
                            </button>
                            <button
                              onClick={() => handleDeleteClient(client)}
                              className="p-2 text-gray-500 hover:text-red-500 transition cursor-pointer"
                              title={t("practitioner.clients.delete")}
                            >
                              <DeleteIcon />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Pagination */}
              <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                totalItems={totalClients}
                pageSize={pageSize}
                onPageChange={setCurrentPage}
              />
            </>
          )}
        </div>
      </main>

      {/* Modals */}
      <AddClientDetailsModal
        isOpen={addClientOpen}
        onClose={() => setAddClientOpen(false)}
        onSuccess={handleClientAdded}
      />
      <SendScreeningInvitationModal
        isOpen={sendInvitationOpen}
        onClose={() => setSendInvitationOpen(false)}
        onSendNow={handleSendNow}
        onSendLater={handleSendLater}
        isLoading={isStartingScreening || isSendingInvitation}
        loadingButton={isSendingInvitation ? "sendNow" : isStartingScreening ? "sendLater" : null}
      />
      <InvitationSentSuccessModal
        isOpen={invitationSentOpen}
        onClose={() => {
          setInvitationSentOpen(false);
          setSelectedClient(null);
        }}
      />
      <ScreeningInvitationSentModal
        isOpen={screeningInvitationSentOpen}
        onClose={handleScreeningInvitationSentClose}
      />
      <ScreeningReportsModal
        isOpen={screeningReportsOpen}
        onClose={() => {
          setScreeningReportsOpen(false);
          setAutoOpenScreeningId(undefined);
          if (searchParams.get("clientId") || searchParams.get("openReport")) {
            window.history.replaceState(null, "", window.location.pathname);
          }
        }}
        clientId={selectedClient?.id}
        clientName={selectedClient?.name}
        clientAge={selectedClient?.age}
        initialScreeningId={autoOpenScreeningId}
      />
      <UpgradeModal
        isOpen={!!upgradeError}
        onClose={() => setUpgradeError(null)}
        errorCode={upgradeError?.code ?? null}
        trialData={upgradeError?.data}
        upgradeHref="/practitioner/subscription"
      />
      <EditClientModal
        isOpen={editClientOpen}
        onClose={() => setEditClientOpen(false)}
        client={selectedClient}
        onSuccess={() => refetch()}
      />
      <DeleteClientModal
        isOpen={deleteClientOpen}
        onClose={() => setDeleteClientOpen(false)}
        client={selectedClient}
        onSuccess={() => refetch()}
      />
    </div>
  );
}

export default function ClientsPage() {
  return (
    <Suspense>
      <ClientsPageInner />
    </Suspense>
  );
}
