"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { ClientForm } from "@/components/clients/client-form";
import { ClientDetailDialog } from "@/components/clients/client-detail-dialog";
import { AssignMembershipDialog } from "@/components/memberships/assign-membership-dialog";
import { StatCardSkeleton } from "@/components/dashboard/stat-card";
import { cn, formatDate } from "@/lib/utils";
import {
  Users,
  CreditCard,
  AlertTriangle,
  UserX,
  Search,
  Eye,
  Phone,
  Mail,
  Calendar,
  Plus,
  ChevronLeft,
  ChevronRight,
  X,
} from "lucide-react";

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

interface Client {
  id: string;
  firstName: string;
  lastName: string;
  email: string | null;
  phone: string | null;
  avatar?: string | null;
  level: string | null;
  notes: string | null;
  isActive: boolean;
  createdAt: string;
  memberships?: Array<{
    id: string;
    status: string;
    startDate: string;
    endDate: string;
    remainingHours: number | null;
    plan: {
      id: string;
      name: string;
      price: number | string;
      durationMonths: number;
      courtHours: number | null;
      discountPercent: number | string | null;
    };
  }>;
  _count?: {
    bookings: number;
  };
  stats?: {
    totalBookings: number;
    totalSpent: number;
    balance: number;
  };
  lastBookingDate?: string | null;
}

interface ClientsResponse {
  data: Client[];
  pagination: {
    total: number;
    limit: number;
    offset: number;
    hasMore: boolean;
  };
}

interface MembershipPlan {
  id: string;
  name: string;
  price: number | string;
  durationMonths: number;
  courtHours: number | null;
  discountPercent: number | string | null;
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

type MembershipStatus = "active" | "expiring" | "expired" | "none";

function getMembershipStatus(client: Client): MembershipStatus {
  const membership = client.memberships?.[0];
  if (!membership) return "none";

  if (membership.status !== "ACTIVE") {
    // Check if it truly expired vs just inactive
    const end = new Date(membership.endDate);
    if (end < new Date()) return "expired";
    return "none";
  }

  const end = new Date(membership.endDate);
  const now = new Date();
  if (end < now) return "expired";

  const daysUntilExpiry = Math.ceil(
    (end.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)
  );
  if (daysUntilExpiry <= 30) return "expiring";

  return "active";
}

function getStatusBadge(status: MembershipStatus) {
  switch (status) {
    case "active":
      return {
        label: "Active",
        className: "bg-green-100 text-green-700 border-green-300",
      };
    case "expiring":
      return {
        label: "Expiring Soon",
        className: "bg-amber-100 text-amber-700 border-amber-300",
      };
    case "expired":
      return {
        label: "Expired",
        className: "bg-red-100 text-red-700 border-red-300",
      };
    case "none":
    default:
      return {
        label: "None",
        className: "bg-gray-100 text-gray-600 border-gray-200",
      };
  }
}

function getInitials(firstName: string, lastName: string) {
  return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
}

function formatShortDate(dateStr: string): string {
  const d = new Date(dateStr);
  return d.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

// ---------------------------------------------------------------------------
// Filter options
// ---------------------------------------------------------------------------

const FILTER_OPTIONS = [
  { value: "all", label: "All" },
  { value: "active", label: "Active Members" },
  { value: "expiring", label: "Expiring Soon" },
  { value: "expired", label: "Expired" },
  { value: "none", label: "No Membership" },
] as const;

type FilterValue = (typeof FILTER_OPTIONS)[number]["value"];

const ITEMS_PER_PAGE = 10;

// ---------------------------------------------------------------------------
// Page Component
// ---------------------------------------------------------------------------

export default function ClientsPage() {
  // Data state
  const [clients, setClients] = useState<Client[]>([]);
  const [loadingClients, setLoadingClients] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterValue, setFilterValue] = useState<FilterValue>("all");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalClients, setTotalClients] = useState(0);

  // Stats state
  const [allClientsForStats, setAllClientsForStats] = useState<Client[]>([]);
  const [loadingStats, setLoadingStats] = useState(true);

  // Modal state
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [editingClient, setEditingClient] = useState<Client | null>(null);
  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [showAssignMembership, setShowAssignMembership] = useState(false);
  const [formLoading, setFormLoading] = useState(false);

  // Membership plans for assignment dialog
  const [membershipPlans, setMembershipPlans] = useState<MembershipPlan[]>([]);

  const [error, setError] = useState<string | null>(null);

  // ---------------------------------------------------------------------------
  // Derived stats
  // ---------------------------------------------------------------------------

  const stats = useMemo(() => {
    const total = allClientsForStats.length;

    let activeMemberships = 0;
    let expiringThisMonth = 0;
    let noMembership = 0;

    for (const c of allClientsForStats) {
      const status = getMembershipStatus(c);
      if (status === "active") activeMemberships++;
      if (status === "expiring") expiringThisMonth++;
      if (status === "none") noMembership++;
    }

    return { total, activeMemberships, expiringThisMonth, noMembership };
  }, [allClientsForStats]);

  // ---------------------------------------------------------------------------
  // Fetchers
  // ---------------------------------------------------------------------------

  const fetchClients = useCallback(async () => {
    setLoadingClients(true);
    try {
      const params = new URLSearchParams();
      if (searchQuery) params.append("search", searchQuery);
      params.append("limit", ITEMS_PER_PAGE.toString());
      params.append("offset", ((currentPage - 1) * ITEMS_PER_PAGE).toString());

      const response = await fetch(`/api/clients?${params.toString()}`);
      if (!response.ok) throw new Error("Error loading clients");

      const data: ClientsResponse = await response.json();

      // Apply membership filter client-side
      let filtered = data.data;
      if (filterValue !== "all") {
        filtered = data.data.filter(
          (c) => getMembershipStatus(c) === filterValue
        );
      }

      setClients(filtered);
      setTotalClients(data.pagination.total);
    } catch (err) {
      console.error("Error fetching clients:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoadingClients(false);
    }
  }, [searchQuery, currentPage, filterValue]);

  const fetchStats = useCallback(async () => {
    setLoadingStats(true);
    try {
      const response = await fetch("/api/clients?limit=1000");
      if (!response.ok) throw new Error("Error loading statistics");
      const data: ClientsResponse = await response.json();
      setAllClientsForStats(data.data);
    } catch (err) {
      console.error("Error fetching stats:", err);
    } finally {
      setLoadingStats(false);
    }
  }, []);

  const fetchMembershipPlans = useCallback(async () => {
    try {
      const response = await fetch("/api/membership-plans");
      if (!response.ok) throw new Error("Error loading plans");
      const data = await response.json();
      setMembershipPlans(
        data.filter(
          (p: MembershipPlan & { isActive?: boolean }) => p.isActive !== false
        )
      );
    } catch (err) {
      console.error("Error fetching membership plans:", err);
    }
  }, []);

  const fetchClientDetails = async (clientId: string) => {
    try {
      const response = await fetch(`/api/clients/${clientId}`);
      if (!response.ok) throw new Error("Error loading client details");
      const data = await response.json();
      setSelectedClient(data);
    } catch (err) {
      console.error("Error fetching client details:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  // ---------------------------------------------------------------------------
  // Effects
  // ---------------------------------------------------------------------------

  useEffect(() => {
    fetchClients();
    fetchStats();
    fetchMembershipPlans();
  }, [fetchClients, fetchStats, fetchMembershipPlans]);

  // Debounce search
  const [debouncedSearch, setDebouncedSearch] = useState(searchQuery);
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearch(searchQuery);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchQuery]);

  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearch, filterValue]);

  // ---------------------------------------------------------------------------
  // Handlers
  // ---------------------------------------------------------------------------

  const handleCreateClient = async (data: {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    avatar?: string;
  }) => {
    setFormLoading(true);
    try {
      const response = await fetch("/api/clients", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error creating client");
      }
      setShowCreateForm(false);
      await Promise.all([fetchClients(), fetchStats()]);
    } catch (err) {
      throw err;
    } finally {
      setFormLoading(false);
    }
  };

  const handleUpdateClient = async (data: {
    firstName: string;
    lastName: string;
    email: string;
    phone: string;
    avatar?: string;
  }) => {
    if (!editingClient) return;
    setFormLoading(true);
    try {
      const response = await fetch(`/api/clients/${editingClient.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error updating client");
      }
      setEditingClient(null);
      await fetchClients();
      if (selectedClient?.id === editingClient.id) {
        await fetchClientDetails(editingClient.id);
      }
    } catch (err) {
      throw err;
    } finally {
      setFormLoading(false);
    }
  };

  const handleDeleteClient = async (client: Client) => {
    if (
      !confirm(
        `Are you sure you want to deactivate ${client.firstName} ${client.lastName}?`
      )
    ) {
      return;
    }
    try {
      const response = await fetch(`/api/clients/${client.id}`, {
        method: "DELETE",
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error deactivating client");
      }
      await Promise.all([fetchClients(), fetchStats()]);
    } catch (err) {
      console.error("Error deleting client:", err);
      setError(err instanceof Error ? err.message : "Unknown error");
    }
  };

  const handleAssignMembership = async (data: {
    clientId: string;
    planId: string;
    startDate: string;
    endDate: string;
  }) => {
    setFormLoading(true);
    try {
      const response = await fetch("/api/memberships", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
      });
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Error assigning membership");
      }
      setShowAssignMembership(false);
      await Promise.all([fetchClients(), fetchStats()]);
      if (selectedClient) {
        await fetchClientDetails(selectedClient.id);
      }
    } catch (err) {
      throw err;
    } finally {
      setFormLoading(false);
    }
  };

  const handleRowClick = (client: Client) => {
    fetchClientDetails(client.id);
  };

  // Pagination
  const totalPages = Math.ceil(totalClients / ITEMS_PER_PAGE);

  // ---------------------------------------------------------------------------
  // Render: Stat Card (inline for CRM style)
  // ---------------------------------------------------------------------------

  function CRMStatCard({
    title,
    value,
    icon,
    iconBg,
    iconColor,
  }: {
    title: string;
    value: number;
    icon: React.ReactNode;
    iconBg: string;
    iconColor: string;
  }) {
    return (
      <Card className="hover:shadow-md transition-shadow">
        <CardContent className="p-5">
          <div className="flex items-center gap-4">
            <div
              className={cn(
                "flex-shrink-0 w-12 h-12 rounded-lg flex items-center justify-center",
                iconBg,
                iconColor
              )}
            >
              {icon}
            </div>
            <div>
              <p className="text-sm font-medium text-primary-500">{title}</p>
              <p className="text-2xl font-bold text-primary-800">{value}</p>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  // ---------------------------------------------------------------------------
  // Render: Table skeleton
  // ---------------------------------------------------------------------------

  function TableSkeleton() {
    return (
      <>
        {[...Array(5)].map((_, i) => (
          <tr key={i} className="animate-pulse">
            <td className="px-4 py-4">
              <div className="flex items-center gap-3">
                <div className="h-9 w-9 rounded-full bg-primary-100" />
                <div className="h-4 w-28 bg-primary-100 rounded" />
              </div>
            </td>
            <td className="px-4 py-4">
              <div className="space-y-1.5">
                <div className="h-3 w-28 bg-primary-100 rounded" />
                <div className="h-3 w-36 bg-primary-100 rounded" />
              </div>
            </td>
            <td className="px-4 py-4">
              <div className="h-4 w-20 bg-primary-100 rounded" />
            </td>
            <td className="px-4 py-4">
              <div className="h-6 w-24 bg-primary-100 rounded-full" />
            </td>
            <td className="px-4 py-4">
              <div className="h-4 w-24 bg-primary-100 rounded" />
            </td>
            <td className="px-4 py-4">
              <div className="h-4 w-16 bg-primary-100 rounded" />
            </td>
            <td className="px-4 py-4">
              <div className="h-8 w-16 bg-primary-100 rounded" />
            </td>
          </tr>
        ))}
      </>
    );
  }

  // ---------------------------------------------------------------------------
  // Render
  // ---------------------------------------------------------------------------

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold text-primary-800">Clients</h1>
          <p className="mt-1 text-primary-600">
            Manage your club members and memberships
          </p>
        </div>
        <Button onClick={() => setShowCreateForm(true)}>
          <Plus className="w-5 h-5 mr-2" />
          New Client
        </Button>
      </div>

      {/* Error Message */}
      {error && (
        <div className="rounded-md bg-red-50 border border-red-200 p-4">
          <div className="flex items-center">
            <AlertTriangle className="h-5 w-5 text-red-400" />
            <p className="ml-3 text-sm text-red-700">{error}</p>
            <button
              onClick={() => setError(null)}
              className="ml-auto text-red-500 hover:text-red-700"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
        </div>
      )}

      {/* Stats Row */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {loadingStats ? (
          <>
            <StatCardSkeleton />
            <StatCardSkeleton />
            <StatCardSkeleton />
            <StatCardSkeleton />
          </>
        ) : (
          <>
            <CRMStatCard
              title="Total Clients"
              value={stats.total}
              icon={<Users className="w-6 h-6" />}
              iconBg="bg-primary-100"
              iconColor="text-primary-600"
            />
            <CRMStatCard
              title="Active Memberships"
              value={stats.activeMemberships}
              icon={<CreditCard className="w-6 h-6" />}
              iconBg="bg-green-100"
              iconColor="text-green-600"
            />
            <CRMStatCard
              title="Expiring This Month"
              value={stats.expiringThisMonth}
              icon={<AlertTriangle className="w-6 h-6" />}
              iconBg="bg-amber-100"
              iconColor="text-amber-600"
            />
            <CRMStatCard
              title="No Membership"
              value={stats.noMembership}
              icon={<UserX className="w-6 h-6" />}
              iconBg="bg-gray-100"
              iconColor="text-gray-500"
            />
          </>
        )}
      </div>

      {/* Filters */}
      <Card>
        <CardContent className="pt-4">
          <div className="flex flex-col sm:flex-row gap-4">
            {/* Search */}
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-primary-400" />
              <Input
                type="text"
                placeholder="Search by name, email or phone..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9 w-full"
              />
            </div>

            {/* Membership Filter Dropdown */}
            <select
              value={filterValue}
              onChange={(e) => setFilterValue(e.target.value as FilterValue)}
              className="flex h-10 rounded-md border border-primary-200 bg-white px-3 py-2 text-sm ring-offset-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:ring-offset-2 min-w-[180px]"
            >
              {FILTER_OPTIONS.map((opt) => (
                <option key={opt.value} value={opt.value}>
                  {opt.label}
                </option>
              ))}
            </select>
          </div>
        </CardContent>
      </Card>

      {/* Clients Table */}
      <Card>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b border-primary-200 bg-primary-50">
                <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Name
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Contact
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Membership
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Expires
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Last Visit
                </th>
                <th className="px-4 py-3 text-right text-xs font-semibold text-primary-600 uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-primary-100">
              {loadingClients ? (
                <TableSkeleton />
              ) : clients.length === 0 ? (
                <tr>
                  <td colSpan={7}>
                    <div className="flex flex-col items-center justify-center py-16 text-primary-500">
                      <Users className="w-12 h-12 mb-3 text-primary-300" />
                      <p className="font-medium">No clients found</p>
                      <p className="text-sm mt-1">
                        {searchQuery || filterValue !== "all"
                          ? "Try adjusting your search or filters"
                          : "Add your first client to get started"}
                      </p>
                    </div>
                  </td>
                </tr>
              ) : (
                clients.map((client) => {
                  const membership = client.memberships?.[0];
                  const mStatus = getMembershipStatus(client);
                  const badge = getStatusBadge(mStatus);

                  // Determine last visit from lastBookingDate or fallback
                  const lastVisit = client.lastBookingDate || null;

                  return (
                    <tr
                      key={client.id}
                      className="hover:bg-primary-50 transition-colors cursor-pointer"
                      onClick={() => handleRowClick(client)}
                    >
                      {/* Name */}
                      <td className="px-4 py-3">
                        <div className="flex items-center gap-3">
                          {client.avatar ? (
                            <img
                              src={client.avatar}
                              alt={`${client.firstName} ${client.lastName}`}
                              className="h-9 w-9 rounded-full object-cover flex-shrink-0"
                            />
                          ) : (
                            <div className="h-9 w-9 rounded-full bg-primary-100 flex items-center justify-center flex-shrink-0">
                              <span className="text-sm font-semibold text-primary-600">
                                {getInitials(client.firstName, client.lastName)}
                              </span>
                            </div>
                          )}
                          <span className="font-medium text-primary-800 whitespace-nowrap">
                            {client.firstName} {client.lastName}
                          </span>
                        </div>
                      </td>

                      {/* Contact */}
                      <td className="px-4 py-3">
                        <div className="space-y-0.5">
                          {client.phone && (
                            <div className="flex items-center gap-1.5 text-sm text-primary-600">
                              <Phone className="w-3.5 h-3.5 text-primary-400" />
                              {client.phone}
                            </div>
                          )}
                          {client.email && (
                            <div className="flex items-center gap-1.5 text-sm text-primary-500">
                              <Mail className="w-3.5 h-3.5 text-primary-400" />
                              <span className="truncate max-w-[180px]">
                                {client.email}
                              </span>
                            </div>
                          )}
                          {!client.phone && !client.email && (
                            <span className="text-sm text-primary-400">
                              —
                            </span>
                          )}
                        </div>
                      </td>

                      {/* Membership Plan */}
                      <td className="px-4 py-3 text-sm text-primary-700">
                        {membership && membership.status === "ACTIVE"
                          ? membership.plan.name
                          : membership && mStatus === "expired"
                          ? membership.plan.name
                          : "None"}
                      </td>

                      {/* Status Badge */}
                      <td className="px-4 py-3">
                        <span
                          className={cn(
                            "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium border",
                            badge.className
                          )}
                        >
                          {badge.label}
                        </span>
                      </td>

                      {/* Expires */}
                      <td className="px-4 py-3 text-sm text-primary-600">
                        {membership &&
                        (membership.status === "ACTIVE" ||
                          mStatus === "expired") ? (
                          <div className="flex items-center gap-1.5">
                            <Calendar className="w-3.5 h-3.5 text-primary-400" />
                            {formatShortDate(membership.endDate)}
                          </div>
                        ) : (
                          <span className="text-primary-400">—</span>
                        )}
                      </td>

                      {/* Last Visit */}
                      <td className="px-4 py-3 text-sm text-primary-600">
                        {lastVisit ? (
                          formatShortDate(lastVisit)
                        ) : (
                          <span className="text-primary-400">Never</span>
                        )}
                      </td>

                      {/* Actions */}
                      <td className="px-4 py-3 text-right">
                        <div
                          className="flex items-center justify-end gap-2"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() => handleRowClick(client)}
                          >
                            <Eye className="w-4 h-4 mr-1" />
                            View
                          </Button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t border-primary-200 bg-primary-50">
            <div className="text-sm text-primary-600">
              Page {currentPage} of {totalPages}
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(currentPage - 1)}
                disabled={currentPage <= 1}
              >
                <ChevronLeft className="w-4 h-4 mr-1" />
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(currentPage + 1)}
                disabled={currentPage >= totalPages}
              >
                Next
                <ChevronRight className="w-4 h-4 ml-1" />
              </Button>
            </div>
          </div>
        )}
      </Card>

      {/* Create Client Form Modal */}
      {showCreateForm && (
        <ClientForm
          onSubmit={handleCreateClient}
          onCancel={() => setShowCreateForm(false)}
          isLoading={formLoading}
          mode="create"
        />
      )}

      {/* Edit Client Form Modal */}
      {editingClient && (
        <ClientForm
          initialData={{
            firstName: editingClient.firstName,
            lastName: editingClient.lastName,
            email: editingClient.email || "",
            phone: editingClient.phone || "",
            avatar: editingClient.avatar || "",
          }}
          onSubmit={handleUpdateClient}
          onCancel={() => setEditingClient(null)}
          isLoading={formLoading}
          mode="edit"
        />
      )}

      {/* Client Detail Dialog */}
      {selectedClient && !editingClient && (
        <ClientDetailDialog
          client={selectedClient}
          onClose={() => setSelectedClient(null)}
          onEdit={() => {
            setEditingClient(selectedClient);
          }}
          onAssignMembership={() => {
            setShowAssignMembership(true);
          }}
        />
      )}

      {/* Assign Membership Dialog */}
      {showAssignMembership && selectedClient && (
        <AssignMembershipDialog
          plans={membershipPlans}
          preselectedClient={{
            id: selectedClient.id,
            firstName: selectedClient.firstName,
            lastName: selectedClient.lastName,
            email: selectedClient.email,
            phone: selectedClient.phone,
          }}
          onClose={() => setShowAssignMembership(false)}
          onAssign={handleAssignMembership}
          isLoading={formLoading}
        />
      )}
    </div>
  );
}
