"use client";

import { useRouter } from "next/navigation";
import { useState, useEffect, useMemo } from "react";
import { ClipboardList } from "lucide-react";
import { useTranslations, useLocale } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import { getUserDataCookie } from "@/lib/cookies";
import toast from "react-hot-toast";
import ScreeningReportsModal from "@/components/practice-manager/modals/ScreeningReportsModal";
import SendScreeningInvitationModal from "@/components/practice-manager/modals/SendScreeningInvitationModal";
import InvitationSentSuccessModal from "@/components/practice-manager/modals/InvitationSentSuccessModal";
import ScreeningInvitationSentModal from "@/components/practice-manager/modals/ScreeningInvitationSentModal";
import AddPatientDetailsModal from "@/components/practice-manager/modals/AddPatientDetailsModal";
import ViewReportModal from "@/components/practice-manager/modals/ViewReportModal";
import {
  usePMClientsControllerListClientsV1,
  usePMClientsControllerSendInvitationV1,
  usePMClientsControllerGetClientScreeningsV1,
} from "@/api/user/practice-manager-clients/practice-manager-clients";
import { useTherapistsControllerListTherapistsV1 } from "@/api/user/practice-manager-therapists/practice-manager-therapists";
import type {
  PMClientsControllerListClientsV1SortBy,
  PMClientsControllerListClientsV1SortOrder,
} from "@/api/user/generated.schemas";

export default function PracticeManagerPatients() {
  const t = useTranslations();
  const locale = useLocale();
  const router = useRouter();
  const queryClient = useQueryClient();
  const currentUserUuid = getUserDataCookie()?.id ?? "";
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("");
  const [filterOpen, setFilterOpen] = useState(false);
  const [tempFilterTherapist, setTempFilterTherapist] = useState("");
  const [filterTherapist, setFilterTherapist] = useState("");
  const [tempFilterGender, setTempFilterGender] = useState("");
  const [filterGender, setFilterGender] = useState("");
  const [tempFilterAgeRange, setTempFilterAgeRange] = useState("");
  const [filterAgeRange, setFilterAgeRange] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [credentialsSentOpen, setCredentialsSentOpen] = useState(false);
  const [showInvitationModal, setShowInvitationModal] = useState(false);
  const [showSuccessModal, setShowSuccessModal] = useState(false);
  const [addPatientOpen, setAddPatientOpen] = useState(false);
  const [selectedClientUuid, setSelectedClientUuid] = useState<string>("");
  const [invitingClientUuid, setInvitingClientUuid] = useState<string>("");
  const [sendLaterClientUuid, setSendLaterClientUuid] = useState<string>("");
  const [newlyCreatedClientUuid, setNewlyCreatedClientUuid] = useState<string>("");
  const [showReportsModal, setShowReportsModal] = useState(false);
  const [selectedReportsClientUuid, setSelectedReportsClientUuid] = useState<string>("");
  const [selectedReportsClientName, setSelectedReportsClientName] = useState<string>("");
  const [viewClientUuid, setViewClientUuid] = useState<string>("");
  const [viewClientName, setViewClientName] = useState<string>("");
  const [viewClientEmail, setViewClientEmail] = useState<string>("");
  const [viewReportUuid, setViewReportUuid] = useState<string | null>(null);

  // --- Fetch screenings for direct report view ---
  const { data: viewScreeningsData } = usePMClientsControllerGetClientScreeningsV1(
    viewClientUuid,
    { page: 1, limit: 10 },
    { query: { enabled: !!viewClientUuid } }
  );
  useEffect(() => {
    if (!viewClientUuid || !viewScreeningsData) return;
    const screenings: any[] = (viewScreeningsData as any)?.data || [];
    const completed = screenings.filter((s: any) => s.status?.toLowerCase() === "completed");
    if (completed.length > 0) {
      setViewReportUuid(completed[0].uuid);
    }
    setViewClientUuid("");
  }, [viewScreeningsData, viewClientUuid]);

  // --- Therapists list for filter ---
  const { data: therapistsData } = useTherapistsControllerListTherapistsV1({ limit: 100 });
  const therapists: any[] = (therapistsData as any)?.data || [];

  // --- Clients List API (fetch all, filter client-side) ---
  const clientParams = {
    page: 1,
    limit: 100,
    ...(searchQuery ? { search: searchQuery } : {}),
    ...(sortBy ? { sort_by: sortBy as PMClientsControllerListClientsV1SortBy, sort_order: "DESC" as PMClientsControllerListClientsV1SortOrder } : {}),
  };
  const { data: clientsData, isLoading: isLoadingClients } = usePMClientsControllerListClientsV1(clientParams);

  const pageSize = 10;

  const filteredClients = useMemo(() => {
    let list: any[] = (clientsData as any)?.data || [];
    if (filterTherapist) list = list.filter((c: any) => c.therapist_uuid === filterTherapist);
    if (filterGender) list = list.filter((c: any) => c.gender?.toLowerCase() === filterGender.toLowerCase());
    if (filterAgeRange) list = list.filter((c: any) => {
      const age = c.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;
      }
    });
    return list;
  }, [(clientsData as any)?.data, filterTherapist, filterGender, filterAgeRange]);

  const totalClients = filteredClients.length;
  const totalPages = Math.max(1, Math.ceil(totalClients / pageSize));
  const clients = filteredClients.slice((currentPage - 1) * pageSize, currentPage * pageSize);

  // Reset page to 1 when search, sort, or filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [searchQuery, sortBy, filterTherapist, filterGender, filterAgeRange]);

  // Close filter dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      if (filterOpen && !(e.target as HTMLElement).closest(".filter-dropdown-pm")) {
        setFilterOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [filterOpen]);

  const handleOpenFilter = () => {
    setTempFilterTherapist(filterTherapist);
    setTempFilterGender(filterGender);
    setTempFilterAgeRange(filterAgeRange);
    setFilterOpen(true);
  };

  const handleApplyFilters = () => {
    setFilterTherapist(tempFilterTherapist);
    setFilterGender(tempFilterGender);
    setFilterAgeRange(tempFilterAgeRange);
    setFilterOpen(false);
  };

  const handleClearFilters = () => {
    setTempFilterTherapist("");
    setTempFilterGender("");
    setTempFilterAgeRange("");
  };

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

  // Helper to invalidate clients queries
  const invalidateQueries = () => {
    queryClient.invalidateQueries({ queryKey: ["/v1/practice-manager/clients"] });
  };

  // --- Send Invitation Mutation ---
  const inviteMutation = usePMClientsControllerSendInvitationV1({
    mutation: {
      onSuccess: () => {
        invalidateQueries();
        setInvitingClientUuid("");
        setShowSuccessModal(true);
      },
      onError: () => {
        setInvitingClientUuid("");
        toast.error(t("practiceManager.clients.invitationFailed"));
      },
    },
  });

  const handleDirectInvite = (clientUuid: string) => {
    setInvitingClientUuid(clientUuid);
    inviteMutation.mutate({ uuid: clientUuid });
  };

  const handleDirectSendLaterWithLoading = (clientUuid: string) => {
    setSendLaterClientUuid(clientUuid);
    setTimeout(() => {
      setSendLaterClientUuid("");
      handleDirectSendLater(clientUuid);
    }, 300);
  };

  const handleDirectSendLater = (clientUuid: string) => {
    document.body.style.overflow = "";
    router.push(`/${locale}/practice-manager/screening/${clientUuid}`);
  };

  const handleViewReport = (clientUuid: string, clientName: string, clientEmail?: string) => {
    setViewClientName(clientName);
    setViewClientEmail(clientEmail || "");
    setViewClientUuid(clientUuid);
  };

  // Generate pagination page numbers
  const getPageNumbers = () => {
    const pages: (number | string)[] = [];
    if (totalPages <= 7) {
      for (let i = 1; i <= totalPages; i++) pages.push(i);
    } else {
      if (currentPage <= 3) {
        pages.push(1, 2, 3, "...", totalPages);
      } else if (currentPage >= totalPages - 2) {
        pages.push(1, "...", totalPages - 2, totalPages - 1, totalPages);
      } else {
        pages.push(1, "...", currentPage - 1, currentPage, currentPage + 1, "...", totalPages);
      }
    }
    return pages;
  };

  // Table row loading skeleton
  const TableRowSkeleton = () => (
    <tr className="border-b border-gray-200 animate-pulse">
      <td className="px-5 py-4 border-r border-gray-200">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-full bg-gray-200" />
          <div>
            <div className="h-4 w-28 bg-gray-200 rounded mb-1" />
            <div className="h-3 w-36 bg-gray-200 rounded" />
          </div>
        </div>
      </td>
      <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-24 bg-gray-200 rounded" /></td>
      <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-12 bg-gray-200 rounded" /></td>
      <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-8 bg-gray-200 rounded" /></td>
      <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-12 bg-gray-200 rounded" /></td>
      <td className="px-5 py-4 border-r border-gray-200"><div className="h-4 w-16 bg-gray-200 rounded" /></td>
      <td className="px-5 py-4"><div className="h-4 w-20 bg-gray-200 rounded" /></td>
    </tr>
  );

  return (
    <>
      {/* Main Content */}
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 pt-24">
        {/* Clients Table Card */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
          {/* Table Header */}
          <div className="p-5 border-b border-gray-200">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
              <h3 className="text-lg font-semibold text-gray-900">
                {t("practiceManager.clients.title")} ({totalClients})
              </h3>
              <div className="flex flex-wrap items-center gap-2">
                {/* Add Client Button */}
                <button
                  onClick={() => setAddPatientOpen(true)}
                  className="px-5 py-2 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#2D8AB5] transition"
                >
                  {t("practiceManager.nav.screening")}
                </button>

                {/* Search */}
                <div className="relative flex-1 sm:flex-none">
                  <svg className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                  </svg>
                  <input
                    type="text"
                    placeholder={t("practiceManager.common.search")}
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9 pr-4 py-2 w-full sm:w-48 border border-gray-200 rounded-full text-sm focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]"
                  />
                </div>

                {/* Sort By */}
                <div className="relative">
                  <select
                    value={sortBy}
                    onChange={(e) => setSortBy(e.target.value)}
                    className="appearance-none bg-white pl-4 pr-10 py-2 border border-gray-200 rounded-full text-base sm:text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                  >
                    <option value="">{t("practiceManager.common.sortBy")}</option>
                    <option value="name">{t("practiceManager.common.name")}</option>
                    <option value="email">{t("practiceManager.common.email")}</option>
                    <option value="age">{t("practiceManager.clients.age")}</option>
                    <option value="created_at">{t("practiceManager.common.dateAdded")}</option>
                  </select>
                  <svg className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                </div>

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

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

                      {/* Therapist */}
                      <div className="mb-3">
                        <label className="block text-xs font-medium text-gray-700 mb-1">{t("practiceManager.clients.therapist")}</label>
                        <div className="relative">
                          <select
                            value={tempFilterTherapist}
                            onChange={(e) => setTempFilterTherapist(e.target.value)}
                            className="appearance-none w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                          >
                            <option value="">{t("practiceManager.common.all")}</option>
                            {therapists.map((th: any) => (
                              <option key={th.uuid} value={th.uuid}>{th.name}</option>
                            ))}
                          </select>
                          <svg className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                          </svg>
                        </div>
                      </div>

                      {/* Gender */}
                      <div className="mb-3">
                        <label className="block text-xs font-medium text-gray-700 mb-1">{t("practiceManager.clients.gender")}</label>
                        <div className="relative">
                          <select
                            value={tempFilterGender}
                            onChange={(e) => setTempFilterGender(e.target.value)}
                            className="appearance-none w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                          >
                            <option value="">{t("practiceManager.common.all")}</option>
                            <option value="Male">{t("practiceManager.clients.male")}</option>
                            <option value="Female">{t("practiceManager.clients.female")}</option>
                            <option value="Other">{t("practiceManager.clients.other")}</option>
                          </select>
                          <svg className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                          </svg>
                        </div>
                      </div>

                      {/* Age Range */}
                      <div className="mb-4">
                        <label className="block text-xs font-medium text-gray-700 mb-1">{t("practiceManager.clients.ageRange")}</label>
                        <div className="relative">
                          <select
                            value={tempFilterAgeRange}
                            onChange={(e) => setTempFilterAgeRange(e.target.value)}
                            className="appearance-none w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                          >
                            <option value="">{t("practiceManager.common.all")}</option>
                            <option value="0-18">0–18 {t("practiceManager.common.years")}</option>
                            <option value="19-35">19–35 {t("practiceManager.common.years")}</option>
                            <option value="36-50">36–50 {t("practiceManager.common.years")}</option>
                            <option value="51+">51+ {t("practiceManager.common.years")}</option>
                          </select>
                          <svg className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                          </svg>
                        </div>
                      </div>

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

          {/* Table */}
          <div className="mx-5 my-5 border border-gray-200 rounded-xl overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full border-collapse min-w-[750px]">
              <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-200">{t("practiceManager.clients.clientsName")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("practiceManager.clients.therapist")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("practiceManager.clients.numberOfScreening")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("practiceManager.clients.reports")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("practiceManager.clients.age")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-r border-gray-200">{t("practiceManager.clients.gender")}</th>
                  <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-b border-gray-200">{t("practiceManager.clients.action")}</th>
                </tr>
              </thead>
              <tbody>
                {isLoadingClients ? (
                  <>
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                    <TableRowSkeleton />
                  </>
                ) : clients.length === 0 ? (
                  <tr>
                    <td colSpan={7} className="px-5 py-12 text-center text-gray-500">
                      {t("practiceManager.clients.noClientsFound")}
                    </td>
                  </tr>
                ) : (
                  clients.map((client) => (
                    <tr key={client.uuid} className="border-b border-gray-200 hover:bg-gray-50/50 transition">
                      <td className="px-5 py-4 border-r border-gray-200">
                        <div className="flex items-center gap-3">
                          <div className="w-10 h-10 rounded-full bg-[#E8F4F8] flex items-center justify-center text-[#3B9EC9] font-semibold text-sm">
                            {client.name.charAt(0).toUpperCase()}
                          </div>
                          <div>
                            <p className="text-sm font-medium text-gray-900">{client.name}</p>
                            <p className="text-xs text-gray-500">{client.email}</p>
                          </div>
                        </div>
                      </td>
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{client.therapist || "-"}</td>
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{client.screening_count ?? 0}</td>
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">
                        {(client.screening_count ?? 0) > 0 ? (
                          <button
                            onClick={() => { setSelectedReportsClientUuid(client.uuid); setSelectedReportsClientName(client.name); setShowReportsModal(true); }}
                            className="p-1 text-[#3B9EC9] hover:text-[#2D8AB5] transition cursor-pointer"
                            title="View screening 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="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{client.age ?? "-"}</td>
                      <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{client.gender || "-"}</td>
                      <td className="px-5 py-4">
                        <div className="flex items-center gap-3">
                          {/* Send Later + Invite Buttons — only for clients added by the manager directly */}
                          {(!client.therapist_uuid || client.therapist_uuid === currentUserUuid) && (
                            <>
                              <button
                                onClick={() => handleDirectSendLaterWithLoading(client.uuid)}
                                disabled={sendLaterClientUuid === client.uuid}
                                className="flex items-center gap-1.5 px-3 py-1.5 border border-gray-300 text-gray-600 bg-white text-xs font-medium rounded-full hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                {sendLaterClientUuid === client.uuid ? (
                                  <svg className="w-3.5 h-3.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-3.5 h-3.5" />
                                )}
                                {t("practiceManager.modals.sendInvitation.sendLater")}
                              </button>
                              <button
                                onClick={() => handleDirectInvite(client.uuid)}
                                disabled={invitingClientUuid === client.uuid}
                                className="flex items-center gap-1.5 px-3 py-1.5 border border-[#3B9EC9] text-[#3B9EC9] bg-white text-xs font-medium rounded-full hover:bg-[#3B9EC9]/5 transition disabled:opacity-50 disabled:cursor-not-allowed"
                              >
                                {invitingClientUuid === client.uuid ? (
                                  <svg className="w-3.5 h-3.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>
                                ) : (
                                  <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
                                    <path d="M22 2L11 13" />
                                    <path d="M22 2L15 22L11 13L2 9L22 2Z" />
                                  </svg>
                                )}
                                {t("practiceManager.clients.invite")}
                              </button>
                            </>
                          )}
                          {/* View Report Button */}
                          <button
                            onClick={() => handleViewReport(client.uuid, client.name, client.email)}
                            className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer"
                            title="View Report"
                          >
                            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                              <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                              <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>
          </div>

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

            <div className="flex items-center gap-1">
              {getPageNumbers().map((page, idx) =>
                typeof page === "string" ? (
                  <span key={`ellipsis-${idx}`} className="px-2 text-gray-400">...</span>
                ) : (
                  <button
                    key={page}
                    onClick={() => setCurrentPage(page)}
                    className={`w-8 h-8 rounded-lg text-sm font-medium ${
                      currentPage === page
                        ? "bg-gray-100 text-gray-900"
                        : "text-gray-600 hover:bg-gray-50"
                    }`}
                  >
                    {page}
                  </button>
                )
              )}
            </div>

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

      {/* Add Patient Modal */}
      <AddPatientDetailsModal
        isOpen={addPatientOpen}
        onClose={() => setAddPatientOpen(false)}
        onSuccess={(clientData) => {
          invalidateQueries();
          const clientUuid = clientData?.uuid || "";
          setNewlyCreatedClientUuid(clientUuid);
          // Only show credentials modal if a temp_password was generated (new client).
          // If client already self-registered, temp_password is null — skip the modal.
          if (clientData?.temp_password) {
            setCredentialsSentOpen(true);
          }
        }}
        onSuccessAndScan={(clientData) => {
          invalidateQueries();
          const clientUuid = clientData?.uuid || "";
          if (clientUuid) {
            document.body.style.overflow = "";
            router.push(`/${locale}/practice-manager/screening/${clientUuid}`);
          }
        }}
      />

      {/* Step 1: Credentials sent modal (temp password + verify email) */}
      <InvitationSentSuccessModal
        isOpen={credentialsSentOpen}
        onClose={() => {
          setCredentialsSentOpen(false);
          setNewlyCreatedClientUuid("");
        }}
        title={t("practiceManager.modals.credentialsSent.title")}
        description={t("practiceManager.modals.credentialsSent.description")}
      />

      {/* Step 2: Send screening invitation (Send Now / Send Later) */}
      <SendScreeningInvitationModal
        isOpen={showInvitationModal}
        onClose={() => {
          setShowInvitationModal(false);
          setNewlyCreatedClientUuid("");
          setSelectedClientUuid("");
        }}
        onSendLater={() => {
          const clientUuid = newlyCreatedClientUuid || selectedClientUuid;
          setShowInvitationModal(false);
          setNewlyCreatedClientUuid("");
          setSelectedClientUuid("");
          if (clientUuid) {
            // Reset body overflow before navigation (Modal sets it to hidden)
            document.body.style.overflow = "";
            router.push(`/${locale}/practice-manager/screening/${clientUuid}`);
          }
        }}
        onSendNow={() => {
          const clientUuid = newlyCreatedClientUuid || selectedClientUuid;
          if (clientUuid) {
            inviteMutation.mutate(
              { uuid: clientUuid },
              {
                onSuccess: () => {
                  setShowInvitationModal(false);
                  setShowSuccessModal(true);
                  setNewlyCreatedClientUuid("");
                  setSelectedClientUuid("");
                },
              }
            );
          } else {
            setShowInvitationModal(false);
          }
        }}
        isLoading={inviteMutation.isPending}
        loadingButton="sendNow"
      />

      {/* Step 3: Screening invitation sent success */}
      <ScreeningInvitationSentModal
        isOpen={showSuccessModal}
        onClose={() => {
          setShowSuccessModal(false);
          document.body.style.overflow = "";
        }}
      />

      {/* Direct Report View */}
      <ViewReportModal
        isOpen={!!viewReportUuid}
        onClose={() => { setViewReportUuid(null); setViewClientName(""); setViewClientEmail(""); }}
        screeningUuid={viewReportUuid}
        clientName={viewClientName}
        clientEmail={viewClientEmail}
      />

      {/* Screening Reports Modal */}
      <ScreeningReportsModal
        isOpen={showReportsModal}
        onClose={() => { setShowReportsModal(false); setSelectedReportsClientUuid(""); setSelectedReportsClientName(""); }}
        patientName={selectedReportsClientName}
        clientUuid={selectedReportsClientUuid}
      />

    </>
  );
}
