"use client";

import { useState, useEffect, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import {
  Users,
  UserPlus,
  Mail,
  Clock,
  Shield,
  Crown,
  User,
  Loader2,
  AlertCircle,
  CheckCircle,
  XCircle,
  RefreshCw,
  Trash2,
  Send,
  MoreVertical,
  Ban,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";
import type { Lang } from "@/lib/config";
import { dashboardEn } from "@/lib/config/translations/modules/dashboard.en";
import { dashboardAr } from "@/lib/config/translations/modules/dashboard.ar";
import type {
  OrganizationMember,
  OrganizationInvitation,
  OrgRole,
  SeatConfiguration,
} from "@/lib/types/organization.types";
import {
  TIER_SEAT_LIMITS,
  ADDITIONAL_SEAT_PRICE_QAR,
} from "@/lib/types/organization.types";
import PurchaseSeatsModal from "./PurchaseSeatsModal";

interface TeamPanelProps {
  lang: Lang;
}

interface TeamData {
  members: OrganizationMember[];
  invitations: OrganizationInvitation[];
  seats: SeatConfiguration;
  userRole: OrgRole;
}

interface ApiResponse {
  success: boolean;
  error?: string;
  organization?: any;
  members?: OrganizationMember[];
  seatConfig?: SeatConfiguration;
  pendingInvitations?: OrganizationInvitation[];
  userRole?: OrgRole | null;
}

const ROLE_COLORS: Record<
  OrgRole,
  { bg: string; text: string; icon: JSX.Element }
> = {
  OWNER: {
    bg: "bg-amber-100",
    text: "text-amber-700",
    icon: <Crown className="w-3 h-3" />,
  },
  ADMIN: {
    bg: "bg-blue-100",
    text: "text-blue-700",
    icon: <Shield className="w-3 h-3" />,
  },
  STAFF: {
    bg: "bg-slate-100",
    text: "text-slate-700",
    icon: <User className="w-3 h-3" />,
  },
};

// Toast helper function
function showToast(
  type: "success" | "error" | "info" | "warning",
  title: string,
  message: string,
) {
  const event = new CustomEvent("showToast", {
    detail: { type, title, message },
  });
  window.dispatchEvent(event);
}

export default function TeamPanel({ lang }: TeamPanelProps) {
  const isAr = lang === "ar";
  const dt = isAr ? dashboardAr : dashboardEn;
  const searchParams = useSearchParams();
  const router = useRouter();

  const [teamData, setTeamData] = useState<TeamData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showInviteModal, setShowInviteModal] = useState(false);
  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteName, setInviteName] = useState("");
  const [inviteRole, setInviteRole] = useState<OrgRole>("STAFF");
  const [inviting, setInviting] = useState(false);
  const [inviteError, setInviteError] = useState<string | null>(null);
  const [inviteSuccess, setInviteSuccess] = useState(false);
  const [showPurchaseModal, setShowPurchaseModal] = useState(false);
  const [actionMenuOpen, setActionMenuOpen] = useState<string | null>(null);
  const [updatingMember, setUpdatingMember] = useState<string | null>(null);

  const t = {
    title: isAr ? "إدارة الفريق" : "Team Management",
    subtitle: isAr
      ? "أضف أعضاء الفريق وأدر صلاحياتهم"
      : "Add team members and manage their permissions",
    members: isAr ? "الأعضاء" : "Members",
    invitations: isAr ? "الدعوات" : "Invitations",
    seats: isAr ? "المقاعد" : "Seats",
    inviteMember: isAr ? "دعوة عضو" : "Invite Member",
    email: isAr ? "البريد الإلكتروني" : "Email",
    name: isAr ? "الاسم" : "Name",
    role: isAr ? "الدور" : "Role",
    send: isAr ? "إرسال الدعوة" : "Send Invitation",
    cancel: isAr ? "إلغاء" : "Cancel",
    pending: isAr ? "قيد الانتظار" : "Pending",
    accepted: isAr ? "مقبول" : "Accepted",
    expired: isAr ? "منتهي الصلاحية" : "Expired",
    revoked: isAr ? "ملغى" : "Revoked",
    owner: isAr ? "المالك" : "Owner",
    admin: isAr ? "مدير" : "Admin",
    staff: isAr ? "موظف" : "Staff",
    joinedOn: isAr ? "انضم في" : "Joined on",
    lastActive: isAr ? "آخر نشاط" : "Last active",
    sentOn: isAr ? "أُرسلت في" : "Sent on",
    expiresOn: isAr ? "تنتهي في" : "Expires on",
    usedSeats: isAr ? "المقاعد المستخدمة" : "Used seats",
    availableSeats: isAr ? "المقاعد المتاحة" : "Available seats",
    includedSeats: isAr ? "المقاعد المشمولة" : "Included seats",
    purchasedSeats: isAr ? "المقاعد المشتراة" : "Purchased seats",
    buyMoreSeats: isAr ? "شراء مقاعد إضافية" : "Buy More Seats",
    perSeatPrice: isAr
      ? `${ADDITIONAL_SEAT_PRICE_QAR} ر.ق/شهر لكل مقعد`
      : `${ADDITIONAL_SEAT_PRICE_QAR} QAR/month per seat`,
    noMembers: isAr ? "لا يوجد أعضاء بعد" : "No members yet",
    noMembersDesc: isAr
      ? "ادعُ أعضاء فريقك للبدء"
      : "Invite your team members to get started",
    noInvitations: isAr ? "لا توجد دعوات" : "No invitations",
    noInvitationsDesc: isAr
      ? "لا توجد دعوات معلقة حالياً"
      : "No pending invitations at the moment",
    inviteSent: isAr ? "تم إرسال الدعوة بنجاح" : "Invitation sent successfully",
    inviteFailed: isAr ? "فشل إرسال الدعوة" : "Failed to send invitation",
    noSeatsAvailable: isAr ? "لا توجد مقاعد متاحة" : "No seats available",
    resend: isAr ? "إعادة إرسال" : "Resend",
    revoke: isAr ? "إلغاء" : "Revoke",
    changeToAdmin: isAr ? "ترقية إلى مدير" : "Make Admin",
    changeToStaff: isAr ? "تخفيض إلى موظف" : "Make Staff",
    removeMember: isAr ? "إزالة العضو" : "Remove Member",
    confirmRemove: isAr
      ? "هل أنت متأكد من إزالة هذا العضو؟"
      : "Are you sure you want to remove this member?",
  };

  // Allow passing false to skip the full-page loading state (for silent background refresh)
  const fetchTeamData = useCallback(
    async (showLoading = true) => {
      try {
        if (showLoading) setLoading(true);
        setError(null);

        const response = await fetch("/api/organization");
        const data: ApiResponse = await response.json().catch(() => ({}));

        // Handle 404 (no organization) gracefully - show empty state instead of error
        if (response.status === 404 || data.hasOrganization === false) {
          // Set default empty team data for users without organization
          setTeamData({
            members: [],
            invitations: [],
            seats: {
              tierId: "tier1",
              includedSeats: 1,
              purchasedSeats: 0,
              usedSeats: 1,
              availableSeats: 0,
            },
            userRole: "OWNER",
          });
          return;
        }

        if (!response.ok) {
          throw new Error(data.error || "Failed to fetch team data");
        }

        if (!data.success) {
          throw new Error(data.error || "Failed to fetch team data");
        }

        // Transform API response to TeamData format
        setTeamData({
          members: data.members || [],
          invitations: data.pendingInvitations || [],
          seats: data.seatConfig || {
            tierId: "tier3",
            includedSeats: 1,
            purchasedSeats: 0,
            usedSeats: 0,
            availableSeats: 1,
          },
          userRole: data.userRole || "OWNER",
        });
      } catch (err) {
        console.error("Failed to fetch team data:", err);
        if (showLoading) {
          setError(
            isAr ? "فشل تحميل بيانات الفريق" : "Failed to load team data",
          );
        }
      } finally {
        if (showLoading) setLoading(false);
      }
    },
    [isAr],
  );

  useEffect(() => {
    fetchTeamData(true); // Show loading spinner on initial mount
  }, [fetchTeamData]);

  // Check for seat purchase success/cancel from URL params
  useEffect(() => {
    const seatsPurchased = searchParams.get("seats_purchased");
    const quantity = searchParams.get("quantity");

    if (seatsPurchased === "success") {
      showToast(
        "success",
        isAr ? "تم الشراء بنجاح!" : "Purchase Successful!",
        isAr
          ? `تم إضافة ${quantity || ""} مقعد/مقاعد جديدة إلى مؤسستك`
          : `${quantity || ""} new seat(s) have been added to your organization`,
      );
      // Silent refresh - update data in background without showing loading spinner
      fetchTeamData(false);
      // Remove the query params from URL
      const params = new URLSearchParams(searchParams.toString());
      params.delete("seats_purchased");
      params.delete("quantity");
      router.replace(
        `?tab=team${params.toString() ? "&" + params.toString() : ""}`,
        { scroll: false },
      );
    } else if (seatsPurchased === "cancelled") {
      showToast(
        "info",
        isAr ? "تم الإلغاء" : "Cancelled",
        isAr ? "تم إلغاء عملية شراء المقاعد" : "Seat purchase was cancelled",
      );
      // Remove the query param from URL
      const params = new URLSearchParams(searchParams.toString());
      params.delete("seats_purchased");
      router.replace(
        `?tab=team${params.toString() ? "&" + params.toString() : ""}`,
        { scroll: false },
      );
    }
  }, [searchParams, router, isAr, fetchTeamData]);

  const handleInvite = async () => {
    if (!inviteEmail.trim()) return;

    try {
      setInviting(true);
      setInviteError(null);

      const response = await fetch("/api/organization/invitations", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: inviteEmail.trim(),
          name: inviteName.trim() || undefined,
          role: inviteRole,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to send invitation");
      }

      setInviteSuccess(true);
      setInviteEmail("");
      setInviteName("");
      setInviteRole("STAFF");

      // Refresh team data
      await fetchTeamData();

      // Close modal after short delay
      setTimeout(() => {
        setShowInviteModal(false);
        setInviteSuccess(false);
      }, 2000);
    } catch (err) {
      setInviteError(err instanceof Error ? err.message : t.inviteFailed);
    } finally {
      setInviting(false);
    }
  };

  const handleChangeRole = async (targetUserId: string, newRole: OrgRole) => {
    try {
      setUpdatingMember(targetUserId);
      setActionMenuOpen(null);
      const res = await fetchWithCSRF("/api/organization/role", {
        method: "PATCH",
        body: JSON.stringify({ targetUserId, newRole }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(
          "success",
          isAr ? "تم التحديث" : "Role Updated",
          isAr ? "تم تغيير دور العضو بنجاح" : `Member role changed to ${newRole}`,
        );
        await fetchTeamData(false);
      } else {
        showToast("error", isAr ? "خطأ" : "Error", data.error || "Failed to update role");
      }
    } catch {
      showToast("error", isAr ? "خطأ" : "Error", isAr ? "فشل تحديث الدور" : "Failed to update role");
    } finally {
      setUpdatingMember(null);
    }
  };

  const handleRemoveMember = async (targetUserId: string) => {
    if (!confirm(t.confirmRemove)) return;
    try {
      setUpdatingMember(targetUserId);
      setActionMenuOpen(null);
      const res = await fetchWithCSRF("/api/organization/role", {
        method: "DELETE",
        body: JSON.stringify({ targetUserId }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(
          "success",
          isAr ? "تمت الإزالة" : "Member Removed",
          isAr ? "تم إزالة العضو من المؤسسة" : "Member has been removed from the organization",
        );
        await fetchTeamData(false);
      } else {
        showToast("error", isAr ? "خطأ" : "Error", data.error || "Failed to remove member");
      }
    } catch {
      showToast("error", isAr ? "خطأ" : "Error", isAr ? "فشل إزالة العضو" : "Failed to remove member");
    } finally {
      setUpdatingMember(null);
    }
  };

  const getRoleLabel = (role: OrgRole) => {
    switch (role) {
      case "OWNER":
        return t.owner;
      case "ADMIN":
        return t.admin;
      case "STAFF":
        return t.staff;
    }
  };

  const getStatusLabel = (status: string) => {
    switch (status) {
      case "PENDING":
        return t.pending;
      case "ACCEPTED":
        return t.accepted;
      case "EXPIRED":
        return t.expired;
      case "REVOKED":
        return t.revoked;
      default:
        return status;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "PENDING":
        return "bg-yellow-100 text-yellow-700";
      case "ACCEPTED":
        return "bg-green-100 text-green-700";
      case "EXPIRED":
        return "bg-slate-100 text-slate-700";
      case "REVOKED":
        return "bg-red-100 text-red-700";
      default:
        return "bg-slate-100 text-slate-700";
    }
  };

  if (loading) {
    return (
      <div className="space-y-6 animate-fadeIn">
        <div className="flex flex-col gap-2">
          <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-slate-600">{t.subtitle}</p>
        </div>
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-8 h-8 text-brand-green animate-spin" />
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-6 animate-fadeIn">
        <div className="flex flex-col gap-2">
          <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-slate-600">{t.subtitle}</p>
        </div>
        <div className="flex flex-col items-center justify-center rounded-2xl bg-red-50 border border-red-200 py-16 px-8 text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mb-4" />
          <p className="text-red-700 mb-4">{error}</p>
          <button
            onClick={fetchTeamData}
            className="flex items-center gap-2 px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 rounded-lg transition-colors"
          >
            <RefreshCw className="w-4 h-4" />
            {isAr ? "إعادة المحاولة" : "Retry"}
          </button>
        </div>
      </div>
    );
  }

  const seats = teamData?.seats || {
    tierId: "tier3",
    includedSeats: 1,
    purchasedSeats: 0,
    usedSeats: 0,
    availableSeats: 1,
  };

  const members = teamData?.members || [];
  const invitations =
    teamData?.invitations?.filter((i) => i.status === "PENDING") || [];

  return (
    <div className="space-y-6 animate-fadeIn">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div className="flex flex-col gap-1">
          <h2 className="text-2xl font-bold text-slate-900">{t.title}</h2>
          <p className="text-slate-600">{t.subtitle}</p>
        </div>
        <button
          onClick={() => setShowInviteModal(true)}
          disabled={seats.availableSeats === 0}
          className="flex items-center justify-center gap-2 px-4 py-2.5 bg-gradient-to-r from-brand-green to-emerald-600 text-white rounded-xl font-medium shadow-lg shadow-brand-green/25 hover:shadow-xl hover:shadow-brand-green/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
        >
          <UserPlus className="w-5 h-5" />
          {t.inviteMember}
        </button>
      </div>

      {/* Seats Overview Card */}
      <div className="rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 border border-slate-200 p-6">
        <h3 className="text-lg font-semibold text-slate-900 mb-4 flex items-center gap-2">
          <Users className="w-5 h-5 text-brand-green" />
          {t.seats}
        </h3>
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          <div className="bg-white rounded-xl p-4 border border-slate-200">
            <p className="text-sm text-slate-500 mb-1">{t.includedSeats}</p>
            <p className="text-2xl font-bold text-slate-900">
              {seats.includedSeats}
            </p>
          </div>
          <div className="bg-white rounded-xl p-4 border border-slate-200">
            <p className="text-sm text-slate-500 mb-1">{t.purchasedSeats}</p>
            <p className="text-2xl font-bold text-slate-900">
              {seats.purchasedSeats}
            </p>
          </div>
          <div className="bg-white rounded-xl p-4 border border-slate-200">
            <p className="text-sm text-slate-500 mb-1">{t.usedSeats}</p>
            <p className="text-2xl font-bold text-blue-600">
              {seats.usedSeats}
            </p>
          </div>
          <div className="bg-white rounded-xl p-4 border border-slate-200">
            <p className="text-sm text-slate-500 mb-1">{t.availableSeats}</p>
            <p
              className={`text-2xl font-bold ${seats.availableSeats > 0 ? "text-green-600" : "text-red-600"}`}
            >
              {seats.availableSeats}
            </p>
          </div>
        </div>
        {/* Buy More Seats - Always visible */}
        <div
          className={`mt-4 flex items-center justify-between rounded-xl p-4 ${
            seats.availableSeats === 0
              ? "bg-amber-50 border border-amber-200"
              : "bg-brand-green/5 border border-brand-green/20"
          }`}
        >
          <div className="flex items-center gap-2">
            {seats.availableSeats === 0 ? (
              <>
                <AlertCircle className="w-5 h-5 text-amber-700" />
                <span className="text-amber-700">{t.noSeatsAvailable}</span>
              </>
            ) : (
              <>
                <UserPlus className="w-5 h-5 text-brand-green" />
                <div>
                  <span className="text-slate-700 font-medium">
                    {isAr ? "تحتاج المزيد من المقاعد؟" : "Need more seats?"}
                  </span>
                  <span className="text-slate-500 text-sm ml-2">
                    {t.perSeatPrice}
                  </span>
                </div>
              </>
            )}
          </div>
          <button
            onClick={() => setShowPurchaseModal(true)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
              seats.availableSeats === 0
                ? "bg-amber-100 hover:bg-amber-200 text-amber-800"
                : "bg-brand-green hover:bg-brand-greenHover text-white shadow-md hover:shadow-lg"
            }`}
          >
            {t.buyMoreSeats}
          </button>
        </div>
      </div>

      {/* Members List */}
      <div className="rounded-2xl bg-white border border-slate-200">
        <div className="px-6 py-4 border-b border-slate-200 bg-slate-50 rounded-t-2xl">
          <h3 className="font-semibold text-slate-900 flex items-center gap-2">
            <Users className="w-5 h-5 text-slate-600" />
            {t.members} ({members.length})
          </h3>
        </div>
        {members.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 px-8 text-center">
            <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
              <Users className="w-8 h-8 text-slate-400" />
            </div>
            <h4 className="text-lg font-medium text-slate-700 mb-2">
              {t.noMembers}
            </h4>
            <p className="text-sm text-slate-500">{t.noMembersDesc}</p>
          </div>
        ) : (
          <div className="divide-y divide-slate-200">
            {members.map((member) => (
              <div
                key={member.id}
                className="px-6 py-4 flex items-center justify-between hover:bg-slate-50 transition-colors"
              >
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-full bg-gradient-to-br from-brand-green to-emerald-600 flex items-center justify-center text-white font-semibold">
                    {(member.name || member.email || "?")
                      .charAt(0)
                      .toUpperCase()}
                  </div>
                  <div>
                    <p className="font-medium text-slate-900">
                      {member.name || member.email}
                    </p>
                    <p className="text-sm text-slate-500">{member.email}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <span
                    className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${ROLE_COLORS[member.role].bg} ${ROLE_COLORS[member.role].text}`}
                  >
                    {ROLE_COLORS[member.role].icon}
                    {getRoleLabel(member.role)}
                  </span>
                  <span className="text-xs text-slate-400">
                    {t.joinedOn}{" "}
                    {new Date(member.joinedAt).toLocaleDateString(
                      isAr ? "ar-SA" : "en-US",
                    )}
                  </span>
                  {/* Action menu for non-OWNER members (only OWNER can manage) */}
                  {teamData?.userRole === "OWNER" &&
                    member.role !== "OWNER" && (
                      <div className="relative">
                        {updatingMember === member.userId ? (
                          <Loader2 className="w-4 h-4 animate-spin text-slate-400" />
                        ) : (
                          <button
                            onClick={() =>
                              setActionMenuOpen(
                                actionMenuOpen === member.userId
                                  ? null
                                  : member.userId,
                              )
                            }
                            className="p-1.5 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
                          >
                            <MoreVertical className="w-4 h-4" />
                          </button>
                        )}
                        {actionMenuOpen === member.userId && (
                          <>
                            <div
                              className="fixed inset-0 z-40"
                              onClick={() => setActionMenuOpen(null)}
                            />
                            <div className="absolute right-0 top-full mt-1 z-50 w-48 bg-white border border-slate-200 rounded-xl shadow-xl py-1 animate-fadeIn">
                              {member.role === "STAFF" ? (
                                <button
                                  onClick={() =>
                                    handleChangeRole(member.userId, "ADMIN")
                                  }
                                  className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-slate-700 hover:bg-blue-50 hover:text-blue-700 transition-colors"
                                >
                                  <Shield className="w-4 h-4" />
                                  {t.changeToAdmin}
                                </button>
                              ) : (
                                <button
                                  onClick={() =>
                                    handleChangeRole(member.userId, "STAFF")
                                  }
                                  className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
                                >
                                  <User className="w-4 h-4" />
                                  {t.changeToStaff}
                                </button>
                              )}
                              <div className="border-t border-slate-100 my-1" />
                              <button
                                onClick={() =>
                                  handleRemoveMember(member.userId)
                                }
                                className="w-full flex items-center gap-2 px-4 py-2.5 text-sm text-red-600 hover:bg-red-50 transition-colors"
                              >
                                <Ban className="w-4 h-4" />
                                {t.removeMember}
                              </button>
                            </div>
                          </>
                        )}
                      </div>
                    )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Pending Invitations */}
      <div className="rounded-2xl bg-white border border-slate-200 overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-200 bg-slate-50">
          <h3 className="font-semibold text-slate-900 flex items-center gap-2">
            <Mail className="w-5 h-5 text-slate-600" />
            {t.invitations} ({invitations.length})
          </h3>
        </div>
        {invitations.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 px-8 text-center">
            <div className="w-16 h-16 rounded-full bg-slate-100 flex items-center justify-center mb-4">
              <Mail className="w-8 h-8 text-slate-400" />
            </div>
            <h4 className="text-lg font-medium text-slate-700 mb-2">
              {t.noInvitations}
            </h4>
            <p className="text-sm text-slate-500">{t.noInvitationsDesc}</p>
          </div>
        ) : (
          <div className="divide-y divide-slate-200">
            {invitations.map((invitation) => (
              <div
                key={invitation.id}
                className="px-6 py-4 flex items-center justify-between hover:bg-slate-50 transition-colors"
              >
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-full bg-slate-200 flex items-center justify-center text-slate-500">
                    <Mail className="w-5 h-5" />
                  </div>
                  <div>
                    <p className="font-medium text-slate-900">
                      {invitation.name || invitation.email}
                    </p>
                    <p className="text-sm text-slate-500">{invitation.email}</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <span
                    className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium ${ROLE_COLORS[invitation.role].bg} ${ROLE_COLORS[invitation.role].text}`}
                  >
                    {ROLE_COLORS[invitation.role].icon}
                    {getRoleLabel(invitation.role)}
                  </span>
                  <span
                    className={`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-xs font-medium ${getStatusColor(invitation.status)}`}
                  >
                    <Clock className="w-3 h-3" />
                    {getStatusLabel(invitation.status)}
                  </span>
                  <div className="flex items-center gap-1">
                    <button
                      className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                      title={t.resend}
                      aria-label={t.resend}
                    >
                      <Send className="w-4 h-4" aria-hidden="true" />
                    </button>
                    <button
                      className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                      title={t.revoke}
                      aria-label={t.revoke}
                    >
                      <Trash2 className="w-4 h-4" aria-hidden="true" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Invite Modal */}
      {showInviteModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
          <div
            className="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4 overflow-hidden"
            dir={isAr ? "rtl" : "ltr"}
          >
            <div className="px-6 py-4 border-b border-slate-200 bg-gradient-to-r from-brand-green/10 to-emerald-50">
              <h3 className="text-lg font-semibold text-slate-900 flex items-center gap-2">
                <UserPlus className="w-5 h-5 text-brand-green" />
                {t.inviteMember}
              </h3>
            </div>
            <div className="p-6 space-y-4 bg-white">
              {inviteSuccess ? (
                <div className="flex flex-col items-center justify-center py-8">
                  <div className="w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mb-4">
                    <CheckCircle className="w-8 h-8 text-green-600" />
                  </div>
                  <p className="text-green-700 font-medium">{t.inviteSent}</p>
                </div>
              ) : (
                <>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1.5">
                      {t.email} *
                    </label>
                    <input
                      type="email"
                      value={inviteEmail}
                      onChange={(e) => setInviteEmail(e.target.value)}
                      placeholder="email@example.com"
                      className="w-full px-4 py-2.5 border border-slate-300 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-brand-green transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1.5">
                      {t.name}
                    </label>
                    <input
                      type="text"
                      value={inviteName}
                      onChange={(e) => setInviteName(e.target.value)}
                      placeholder={isAr ? "الاسم الكامل" : "Full name"}
                      className="w-full px-4 py-2.5 border border-slate-300 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-brand-green transition-all"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1.5">
                      {t.role}
                    </label>
                    <select
                      value={inviteRole}
                      onChange={(e) => setInviteRole(e.target.value as OrgRole)}
                      className="w-full px-4 py-2.5 border border-slate-300 rounded-xl focus:ring-2 focus:ring-brand-green focus:border-brand-green transition-all"
                    >
                      <option value="STAFF">{t.staff}</option>
                      <option value="ADMIN">{t.admin}</option>
                    </select>
                  </div>
                  {inviteError && (
                    <div className="flex items-center gap-2 text-red-600 text-sm bg-red-50 px-4 py-2 rounded-lg">
                      <XCircle className="w-4 h-4" />
                      {inviteError}
                    </div>
                  )}
                </>
              )}
            </div>
            {!inviteSuccess && (
              <div className="px-6 py-4 border-t border-slate-200 bg-slate-50 flex justify-end gap-3">
                <button
                  onClick={() => {
                    setShowInviteModal(false);
                    setInviteError(null);
                    setInviteEmail("");
                    setInviteName("");
                  }}
                  className="px-4 py-2 text-slate-600 hover:text-slate-800 hover:bg-slate-100 rounded-lg transition-colors"
                >
                  {t.cancel}
                </button>
                <button
                  onClick={handleInvite}
                  disabled={!inviteEmail.trim() || inviting}
                  className="flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-brand-green to-emerald-600 text-white rounded-lg font-medium shadow-lg shadow-brand-green/25 hover:shadow-xl hover:shadow-brand-green/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {inviting ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <Send className="w-4 h-4" />
                  )}
                  {t.send}
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Purchase Seats Modal */}
      <PurchaseSeatsModal
        lang={lang}
        isOpen={showPurchaseModal}
        onClose={() => setShowPurchaseModal(false)}
        currentSeats={seats.includedSeats + seats.purchasedSeats}
        onSuccess={() => {
          setShowPurchaseModal(false);
          fetchTeamData(false); // Silent refresh after modal closes
        }}
      />
    </div>
  );
}
