"use client";

import {
  X,
  User,
  Clock,
  FileText,
  CreditCard,
  Shield,
  MapPin,
  Mail,
  Copy,
  Check,
  Link2,
  Plus,
  Trash2,
  Edit3,
  ExternalLink,
  Settings2,
  Zap,
  Phone,
  MessageSquare,
  RefreshCw,
  Users,
  Building2,
  Receipt,
  Download,
  DollarSign,
  Calendar,
  ChevronDown,
  ChevronUp,
} from "lucide-react";
import { useState, useEffect } from "react";
import { UserData } from "./UserTable";

interface LoginHistoryEntry {
  id: string;
  ipAddress: string;
  country: string | null;
  city: string | null;
  timestamp: string;
  logoutAt: string | null;
  userAgent: string | null;
  provider: string;
  success: boolean;
}

interface AdminNote {
  id: string;
  category:
    | "general"
    | "support"
    | "billing"
    | "security"
    | "compliance"
    | "technical"
    | "sales";
  content: string;
  createdBy: string;
  createdAt: string;
}

interface BillingEmail {
  id: string;
  subject: string;
  sentAt: string;
  status: "sent" | "failed" | "paid" | "overdue";
  amount?: number;
}

interface StripeInvoice {
  id: string;
  type: "stripe_invoice";
  number: string | null;
  status: string;
  amount: number;
  currency: string;
  description: string;
  createdAt: string;
  paidAt: string | null;
  hostedInvoiceUrl: string | null;
  invoicePdf: string | null;
  billingReason: string | null;
  periodStart: string | null;
  periodEnd: string | null;
}

interface InvoiceSummary {
  totalPaid: number;
  totalInvoices: number;
  paidInvoices: number;
  openInvoices: number;
  failedPayments: number;
}

const CURRENCY_OPTIONS = [
  { value: "GBP", label: "£ GBP", symbol: "£" },
  { value: "USD", label: "$ USD", symbol: "$" },
  { value: "EUR", label: "€ EUR", symbol: "€" },
  { value: "AED", label: "AED", symbol: "AED " },
  { value: "SAR", label: "SAR", symbol: "SAR " },
  { value: "QAR", label: "QAR", symbol: "QAR " },
];

interface UserLink {
  id: string;
  linkType:
    | "KNOWLEDGE_BASE"
    | "AI_AGENT"
    | "AI_VOICE_AGENT"
    | "WHATSAPP_INTEGRATION"
    | "DASHBOARD"
    | "DOCUMENTATION"
    | "SUPPORT"
    | "APPOINTMENTS"
    | "CUSTOMERS"
    | "WAITLISTS"
    | "ANALYTICS"
    | "BILLING"
    | "SETTINGS"
    | "CALENDAR"
    | "REPORTS"
    | "CUSTOM";
  title: string;
  url: string;
  description: string | null;
  icon: string | null;
  isActive: boolean;
  sortOrder: number;
  createdAt: string;
}

const LINK_TYPE_OPTIONS = [
  { value: "KNOWLEDGE_BASE", label: "Knowledge Base", icon: "📚" },
  { value: "AI_AGENT", label: "AI Agent", icon: "🤖" },
  { value: "AI_VOICE_AGENT", label: "AI Voice Agent", icon: "🎙️" },
  { value: "WHATSAPP_INTEGRATION", label: "WhatsApp", icon: "💬" },
  { value: "APPOINTMENTS", label: "Appointments", icon: "📅" },
  { value: "CUSTOMERS", label: "Customers", icon: "👥" },
  { value: "WAITLISTS", label: "Waitlists", icon: "⏳" },
  { value: "CALENDAR", label: "Calendar", icon: "🗓️" },
  { value: "ANALYTICS", label: "Analytics", icon: "📈" },
  { value: "REPORTS", label: "Reports", icon: "📋" },
  { value: "BILLING", label: "Billing", icon: "💳" },
  { value: "DASHBOARD", label: "Dashboard", icon: "📊" },
  { value: "DOCUMENTATION", label: "Documentation", icon: "📄" },
  { value: "SETTINGS", label: "Settings", icon: "⚙️" },
  { value: "SUPPORT", label: "Support", icon: "🆘" },
  { value: "CUSTOM", label: "Custom", icon: "🔗" },
];

interface UserModalProps {
  user: UserData | null;
  onClose: () => void;
  onSave?: (userId: string, updates: any) => void;
  onSuspend?: (userId: string, reason: string) => void;
  onActivate?: (userId: string) => void;
  isAdmin: boolean;
}

type TabType =
  | "overview"
  | "history"
  | "notes"
  | "billing"
  | "links"
  | "integrations"
  | "actions";

export default function UserModal({
  user,
  onClose,
  onSave,
  onSuspend,
  onActivate,
  isAdmin,
}: UserModalProps) {
  const [activeTab, setActiveTab] = useState<TabType>("overview");
  const [copiedText, setCopiedText] = useState<string | null>(null);
  const [newNote, setNewNote] = useState("");
  const [noteCategory, setNoteCategory] =
    useState<AdminNote["category"]>("general");
  const [billingSubject, setBillingSubject] = useState("");
  const [billingMessage, setBillingMessage] = useState("");
  const [billingAmount, setBillingAmount] = useState("");
  const [billingCurrency, setBillingCurrency] = useState("GBP");
  const [billingDueDate, setBillingDueDate] = useState("");
  const [includePaymentLink, setIncludePaymentLink] = useState(true);
  const [suspendReason, setSuspendReason] = useState("");
  const [trialExtensionWeeks, setTrialExtensionWeeks] = useState(2);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

  // Real data from API
  const [loginHistory, setLoginHistory] = useState<LoginHistoryEntry[]>([]);
  const [adminNotes, setAdminNotes] = useState<AdminNote[]>([]);
  const [billingEmails, setBillingEmails] = useState<BillingEmail[]>([]);
  const [userDetails, setUserDetails] = useState<any>(null);
  const [userLinks, setUserLinks] = useState<UserLink[]>([]);

  // Invoice history state
  const [invoices, setInvoices] = useState<StripeInvoice[]>([]);
  const [invoiceSummary, setInvoiceSummary] = useState<InvoiceSummary | null>(
    null,
  );
  const [loadingInvoices, setLoadingInvoices] = useState(false);
  const [showAllInvoices, setShowAllInvoices] = useState(false);

  // Link form state
  const [showLinkForm, setShowLinkForm] = useState(false);
  const [editingLink, setEditingLink] = useState<UserLink | null>(null);
  const [linkForm, setLinkForm] = useState({
    linkType: "CUSTOM" as UserLink["linkType"],
    title: "",
    url: "",
    description: "",
  });

  // Integrations state
  const [integrations, setIntegrations] = useState({
    n8nWebhookToken: "",
    voiceAgentId: "",
    voiceAgentConfig: {} as Record<string, any>,
  });
  const [generatingToken, setGeneratingToken] = useState(false);

  // Fetch user details on mount
  useEffect(() => {
    if (user) {
      fetchUserDetails();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id]);

  async function fetchUserDetails() {
    try {
      setLoading(true);
      const response = await fetch(`/api/staff/users/${user?.id}`);
      if (response.ok) {
        const data = await response.json();
        setUserDetails(data.user);
        setLoginHistory(
          data.user.login_history?.slice(0, 20).map((l: any) => ({
            id: l.id,
            ipAddress: l.ipAddress,
            country: l.country,
            city: l.city,
            timestamp: l.createdAt,
            logoutAt: l.logoutAt,
            userAgent: l.userAgent,
            provider: l.provider || "credentials",
            success: l.success !== false,
          })) || [],
        );
        setAdminNotes(
          data.user.admin_notes?.map((n: any) => ({
            id: n.id,
            category: n.category.toLowerCase(),
            content: n.content,
            createdBy: n.staffId,
            createdAt: n.createdAt,
          })) || [],
        );
        setBillingEmails(
          data.user.billing_emails?.map((e: any) => ({
            id: e.id,
            subject: e.subject,
            sentAt: e.sentAt,
            status: e.status.toLowerCase(),
          })) || [],
        );
        setUserLinks(
          data.user.user_links?.map((l: any) => ({
            id: l.id,
            linkType: l.linkType,
            title: l.title,
            url: l.url,
            description: l.description,
            icon: l.icon,
            isActive: l.isActive,
            sortOrder: l.sortOrder,
            createdAt: l.createdAt,
          })) || [],
        );

        // Set integrations data
        setIntegrations({
          n8nWebhookToken: data.user.n8nWebhookToken || "",
          voiceAgentId: data.user.voiceAgentId || "",
          voiceAgentConfig: data.user.voiceAgentConfig || {},
        });

        // Fetch invoices for non-team members
        if (!data.user.isTeamMember) {
          fetchInvoices();
        }
      }
    } catch (error) {
      console.error("Failed to fetch user details:", error);
    } finally {
      setLoading(false);
    }
  }

  async function fetchInvoices() {
    if (!user?.id) return;

    try {
      setLoadingInvoices(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/billing/invoices`,
      );
      if (response.ok) {
        const data = await response.json();
        setInvoices(data.invoices || []);
        setInvoiceSummary(data.summary || null);
      }
    } catch (error) {
      console.error("Failed to fetch invoices:", error);
    } finally {
      setLoadingInvoices(false);
    }
  }

  if (!user) return null;

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedText(text);
      setTimeout(() => setCopiedText(null), 2000);
    } catch (err) {
      console.error("Failed to copy:", err);
    }
  };

  const allTabs: { id: TabType; label: string; icon: any }[] = [
    { id: "overview", label: "Overview", icon: User },
    { id: "history", label: "Session Activity", icon: Clock },
    { id: "notes", label: "Admin Notes", icon: FileText },
    { id: "billing", label: "Billing", icon: CreditCard },
    { id: "links", label: "Links", icon: Link2 },
    { id: "integrations", label: "Integrations", icon: Settings2 },
    { id: "actions", label: "Actions", icon: Shield },
  ];

  // Filter out Links and Integrations tabs for team members
  const tabs = userDetails?.isTeamMember
    ? allTabs.filter((tab) => !["links", "integrations"].includes(tab.id))
    : allTabs;

  const handleSendBillingEmail = async () => {
    if (!billingSubject.trim() || !billingMessage.trim()) {
      alert("Please fill in both subject and message");
      return;
    }

    // If payment link is requested, amount is required
    if (
      includePaymentLink &&
      (!billingAmount || parseFloat(billingAmount) <= 0)
    ) {
      alert("Please enter an amount when including a payment link");
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/billing/email`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            subject: billingSubject,
            content: billingMessage,
            amount: billingAmount ? parseFloat(billingAmount) : undefined,
            currency: billingCurrency,
            dueDate: billingDueDate || undefined,
            includePaymentLink,
          }),
        },
      );

      if (response.ok) {
        const data = await response.json();
        const message = data.billingEmail?.paymentUrl
          ? "Billing email with payment link sent successfully!"
          : "Billing email sent successfully";
        alert(message);
        setBillingSubject("");
        setBillingMessage("");
        setBillingAmount("");
        setBillingDueDate("");
        setIncludePaymentLink(true);
        fetchUserDetails(); // Refresh data
        fetchInvoices(); // Refresh invoices
      } else {
        const error = await response.json();
        alert(error.error || "Failed to send email");
      }
    } catch (error) {
      console.error("Failed to send billing email:", error);
      alert("Failed to send email");
    } finally {
      setSubmitting(false);
    }
  };

  const handleAddNote = async () => {
    if (!newNote.trim()) return;

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/notes`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          content: newNote,
          category: noteCategory.toUpperCase(),
        }),
      });

      if (response.ok) {
        setNewNote("");
        fetchUserDetails(); // Refresh notes
      } else {
        const error = await response.json();
        alert(error.error || "Failed to add note");
      }
    } catch (error) {
      console.error("Failed to add note:", error);
      alert("Failed to add note");
    } finally {
      setSubmitting(false);
    }
  };

  const handleSuspend = async () => {
    if (!suspendReason.trim() || suspendReason.length < 5) {
      alert("Please provide a reason (minimum 5 characters)");
      return;
    }

    if (!confirm("Are you sure you want to suspend this account?")) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "suspend",
          reason: suspendReason,
        }),
      });

      if (response.ok) {
        alert("Account suspended successfully");
        setSuspendReason("");
        onSuspend?.(user.id, suspendReason);
        onClose();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to suspend account");
      }
    } catch (error) {
      console.error("Failed to suspend account:", error);
      alert("Failed to suspend account");
    } finally {
      setSubmitting(false);
    }
  };

  const handleActivate = async () => {
    if (!confirm("Are you sure you want to activate this account?")) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "activate",
          reason: "Account reactivated by administrator",
        }),
      });

      if (response.ok) {
        alert("Account activated successfully");
        onActivate?.(user.id);
        onClose();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to activate account");
      }
    } catch (error) {
      console.error("Failed to activate account:", error);
      alert("Failed to activate account");
    } finally {
      setSubmitting(false);
    }
  };

  const handleExtendTrial = async () => {
    if (!confirm(`Extend trial by ${trialExtensionWeeks} weeks?`)) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/extend-trial`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          weeks: trialExtensionWeeks,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        alert(
          `Trial extended successfully! New trial end date: ${new Date(data.newTrialEnd).toLocaleDateString()}`,
        );
        fetchUserDetails(); // Refresh data
      } else {
        const error = await response.json();
        alert(error.error || "Failed to extend trial");
      }
    } catch (error) {
      console.error("Failed to extend trial:", error);
      alert("Failed to extend trial");
    } finally {
      setSubmitting(false);
    }
  };

  const resetLinkForm = () => {
    setLinkForm({
      linkType: "CUSTOM",
      title: "",
      url: "",
      description: "",
    });
    setEditingLink(null);
    setShowLinkForm(false);
  };

  const handleAddLink = async () => {
    if (!linkForm.title.trim() || !linkForm.url.trim()) {
      alert("Please fill in both title and URL");
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/links`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          linkType: linkForm.linkType,
          title: linkForm.title,
          url: linkForm.url,
          description: linkForm.description || null,
        }),
      });

      if (response.ok) {
        resetLinkForm();
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to add link");
      }
    } catch (error) {
      console.error("Failed to add link:", error);
      alert("Failed to add link");
    } finally {
      setSubmitting(false);
    }
  };

  const handleUpdateLink = async () => {
    if (!editingLink || !linkForm.title.trim() || !linkForm.url.trim()) {
      alert("Please fill in both title and URL");
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/links/${editingLink.id}`,
        {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            linkType: linkForm.linkType,
            title: linkForm.title,
            url: linkForm.url,
            description: linkForm.description || null,
          }),
        },
      );

      if (response.ok) {
        resetLinkForm();
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to update link");
      }
    } catch (error) {
      console.error("Failed to update link:", error);
      alert("Failed to update link");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDeleteLink = async (linkId: string) => {
    if (!confirm("Are you sure you want to delete this link?")) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/links/${linkId}`,
        {
          method: "DELETE",
        },
      );

      if (response.ok) {
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to delete link");
      }
    } catch (error) {
      console.error("Failed to delete link:", error);
      alert("Failed to delete link");
    } finally {
      setSubmitting(false);
    }
  };

  const startEditLink = (link: UserLink) => {
    setEditingLink(link);
    setLinkForm({
      linkType: link.linkType,
      title: link.title,
      url: link.url,
      description: link.description || "",
    });
    setShowLinkForm(true);
  };

  const getLinkTypeInfo = (type: string) => {
    return (
      LINK_TYPE_OPTIONS.find((opt) => opt.value === type) || {
        value: type,
        label: type,
        icon: "🔗",
      }
    );
  };

  // Generate N8N Webhook Token
  const handleGenerateToken = async () => {
    if (
      !confirm(
        "Generate a new N8N webhook token? This will invalidate the current token if one exists.",
      )
    ) {
      return;
    }

    try {
      setGeneratingToken(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/integrations/generate-token`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
        },
      );

      if (response.ok) {
        const data = await response.json();
        setIntegrations((prev) => ({ ...prev, n8nWebhookToken: data.token }));
        alert("Token generated successfully!");
      } else {
        const error = await response.json();
        alert(error.error || "Failed to generate token");
      }
    } catch (error) {
      console.error("Failed to generate token:", error);
      alert("Failed to generate token");
    } finally {
      setGeneratingToken(false);
    }
  };

  // Save Integration Settings
  const handleSaveIntegrations = async () => {
    try {
      setSubmitting(true);
      const response = await fetch(`/api/staff/users/${user.id}/integrations`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          voiceAgentId: integrations.voiceAgentId || null,
          voiceAgentConfig: integrations.voiceAgentConfig,
        }),
      });

      if (response.ok) {
        alert("Integration settings saved successfully!");
        fetchUserDetails();
      } else {
        const error = await response.json();
        alert(error.error || "Failed to save integration settings");
      }
    } catch (error) {
      console.error("Failed to save integrations:", error);
      alert("Failed to save integration settings");
    } finally {
      setSubmitting(false);
    }
  };

  // Revoke N8N Token
  const handleRevokeToken = async () => {
    if (
      !confirm(
        "Revoke the N8N webhook token? This will disable all N8N integrations for this user.",
      )
    ) {
      return;
    }

    try {
      setSubmitting(true);
      const response = await fetch(
        `/api/staff/users/${user.id}/integrations/revoke-token`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
        },
      );

      if (response.ok) {
        setIntegrations((prev) => ({ ...prev, n8nWebhookToken: "" }));
        alert("Token revoked successfully!");
      } else {
        const error = await response.json();
        alert(error.error || "Failed to revoke token");
      }
    } catch (error) {
      console.error("Failed to revoke token:", error);
      alert("Failed to revoke token");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div>
            <h2 className="text-2xl font-bold text-brand-ink">{user.name}</h2>
            <p className="text-sm text-gray-600 mt-1">{user.email}</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition"
            aria-label="Close modal"
          >
            <X className="w-6 h-6 text-gray-500" />
          </button>
        </div>

        {/* Tabs */}
        <div className="border-b border-gray-200">
          <div className="flex overflow-x-auto">
            {tabs.map((tab) => {
              const Icon = tab.icon;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className={`flex items-center gap-2 px-6 py-3 text-sm font-medium whitespace-nowrap transition ${
                    activeTab === tab.id
                      ? "text-brand-green border-b-2 border-brand-green"
                      : "text-gray-600 hover:text-gray-900"
                  }`}
                >
                  <Icon className="w-4 h-4" />
                  {tab.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* Tab 1: Overview */}
          {activeTab === "overview" && (
            <div className="space-y-6">
              {/* Account Status Section */}
              <div className="p-4 bg-gray-50 border border-gray-200 rounded-lg">
                <h4 className="font-semibold text-brand-ink mb-3">
                  Account Status
                </h4>
                <div
                  className={`grid ${userDetails?.isTeamMember ? "grid-cols-1" : "grid-cols-3"} gap-4`}
                >
                  <div>
                    <label className="block text-xs text-gray-600 uppercase mb-1">
                      Status
                    </label>
                    <span
                      className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                        user.status === "active"
                          ? "bg-green-100 text-green-800"
                          : user.status === "suspended"
                            ? "bg-orange-100 text-orange-800"
                            : "bg-red-100 text-red-800"
                      }`}
                    >
                      {user.status}
                    </span>
                  </div>
                  {/* Hide Email Verified and Onboarding for team members */}
                  {!userDetails?.isTeamMember && (
                    <>
                      <div>
                        <label className="block text-xs text-gray-600 uppercase mb-1">
                          Email Verified
                        </label>
                        <p className="text-base">
                          {userDetails?.emailVerified ? "✅ Yes" : "❌ No"}
                        </p>
                      </div>
                      <div>
                        <label className="block text-xs text-gray-600 uppercase mb-1">
                          Onboarding
                        </label>
                        <p className="text-base">
                          {userDetails?.onboardingComplete
                            ? "✅ Complete"
                            : "⚠️ Incomplete"}
                        </p>
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* Personal Information */}
              <div>
                <h4 className="font-semibold text-brand-ink mb-3">
                  Personal Information
                </h4>
                <div className="grid grid-cols-2 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Name
                    </label>
                    <p className="text-base text-gray-900">{user.name}</p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Email
                    </label>
                    <div className="flex items-center gap-2">
                      <p className="text-base text-gray-900">{user.email}</p>
                      <button onClick={() => copyToClipboard(user.email)}>
                        {copiedText === user.email ? (
                          <Check className="w-4 h-4 text-green-600" />
                        ) : (
                          <Copy className="w-4 h-4 text-gray-400 hover:text-gray-600" />
                        )}
                      </button>
                    </div>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Phone Number
                    </label>
                    <p className="text-base text-gray-900">
                      {userDetails?.phoneNumber || "-"}
                    </p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Role
                    </label>
                    {userDetails?.isTeamMember &&
                    userDetails?.teamMembership ? (
                      <div>
                        <span className="inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full bg-blue-100 text-blue-800">
                          <Users className="w-3.5 h-3.5" />
                          Staff Member
                        </span>
                        <p className="text-sm text-gray-600 mt-1">
                          at{" "}
                          <span className="font-medium">
                            {userDetails.teamMembership.organizationName}
                          </span>
                        </p>
                      </div>
                    ) : userDetails?.isOrgOwner &&
                      userDetails?.ownedOrganization ? (
                      <div>
                        <span className="inline-flex items-center gap-1.5 px-3 py-1 text-sm font-medium rounded-full bg-emerald-100 text-emerald-800">
                          <Building2 className="w-3.5 h-3.5" />
                          Company Owner
                        </span>
                        <p className="text-sm text-gray-600 mt-1">
                          of{" "}
                          <span className="font-medium">
                            {userDetails.ownedOrganization.name}
                          </span>
                        </p>
                      </div>
                    ) : (
                      <p className="text-base text-gray-900">{user.role}</p>
                    )}
                  </div>
                </div>
              </div>

              {/* Team Membership Section - Only for team members */}
              {userDetails?.isTeamMember && userDetails?.teamMembership && (
                <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-3 mb-4">
                    <div className="p-2 bg-blue-100 rounded-lg">
                      <Users className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <h4 className="font-semibold text-brand-ink">
                        Team Member
                      </h4>
                      <p className="text-sm text-gray-600">
                        This user is part of another organization&apos;s team
                      </p>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Organization
                      </label>
                      <div className="flex items-center gap-2">
                        <Building2 className="w-4 h-4 text-gray-400" />
                        <p className="text-base font-medium text-gray-900">
                          {userDetails.teamMembership.organizationName}
                        </p>
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Team Role
                      </label>
                      <span
                        className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                          userDetails.teamMembership.role === "ADMIN"
                            ? "bg-purple-100 text-purple-800"
                            : userDetails.teamMembership.role === "MEMBER"
                              ? "bg-blue-100 text-blue-800"
                              : "bg-gray-100 text-gray-800"
                        }`}
                      >
                        {userDetails.teamMembership.role}
                      </span>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Organization Owner
                      </label>
                      <div>
                        <p className="text-base text-gray-900">
                          {userDetails.teamMembership.owner?.name || "-"}
                        </p>
                        <p className="text-xs text-gray-500">
                          {userDetails.teamMembership.owner?.email || ""}
                        </p>
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Joined Team
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails.teamMembership.joinedAt
                          ? new Date(
                              userDetails.teamMembership.joinedAt,
                            ).toLocaleDateString()
                          : "-"}
                      </p>
                    </div>
                  </div>
                  <div className="mt-4 p-3 bg-blue-100 border border-blue-200 rounded-lg">
                    <p className="text-sm text-blue-800">
                      <strong>Note:</strong> Team members do not have their own
                      subscription or company profile. They access the platform
                      through their team organization&apos;s subscription.
                    </p>
                  </div>
                </div>
              )}

              {/* Company Owner Section - Only for organization owners */}
              {userDetails?.isOrgOwner && userDetails?.ownedOrganization && (
                <div className="p-4 bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200 rounded-lg">
                  <div className="flex items-center gap-3 mb-4">
                    <div className="p-2 bg-emerald-100 rounded-lg">
                      <Building2 className="w-5 h-5 text-emerald-600" />
                    </div>
                    <div>
                      <h4 className="font-semibold text-brand-ink">
                        Company Owner
                      </h4>
                      <p className="text-sm text-gray-600">
                        This user owns an organization
                      </p>
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Organization
                      </label>
                      <div className="flex items-center gap-2">
                        <Building2 className="w-4 h-4 text-gray-400" />
                        <p className="text-base font-medium text-gray-900">
                          {userDetails.ownedOrganization.name}
                        </p>
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Team Members
                      </label>
                      <div className="flex items-center gap-2">
                        <Users className="w-4 h-4 text-gray-400" />
                        <p className="text-base text-gray-900">
                          {userDetails.ownedOrganization.memberCount} members
                        </p>
                      </div>
                    </div>
                  </div>
                  <div className="mt-4 p-3 bg-emerald-100 border border-emerald-200 rounded-lg">
                    <p className="text-sm text-emerald-800">
                      <strong>Owner Privileges:</strong> Full access to billing,
                      team management, and all organization features.
                    </p>
                  </div>
                </div>
              )}

              {/* Company Information - Only for non-team-members */}
              {!userDetails?.isTeamMember && (
                <div>
                  <h4 className="font-semibold text-brand-ink mb-3">
                    Company Information
                  </h4>
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Company Name
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.companyName || user.companyName || "-"}
                      </p>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Industry
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.industry || user.industry || "-"}
                      </p>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Company Size
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.companySize || "-"}
                      </p>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Website
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.website || "-"}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              {/* Location Information - Only for non-team-members */}
              {!userDetails?.isTeamMember && (
                <div>
                  <h4 className="font-semibold text-brand-ink mb-3">
                    Location
                  </h4>
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Country
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.country || user.country || "-"}
                      </p>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        City
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.city || user.city || "-"}
                      </p>
                    </div>
                    <div className="col-span-2">
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Address
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.address || "-"}
                      </p>
                    </div>
                  </div>
                </div>
              )}

              {/* Account Activity */}
              <div>
                <h4 className="font-semibold text-brand-ink mb-3">
                  Account Activity
                </h4>
                <div className="grid grid-cols-3 gap-6">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      {userDetails?.isTeamMember
                        ? "Added to Team"
                        : "Registered"}
                    </label>
                    <p className="text-base text-gray-900">
                      {new Date(user.createdAt).toLocaleDateString()}
                    </p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Last Login
                    </label>
                    <p className="text-base text-gray-900">
                      {user.lastLoginAt
                        ? new Date(user.lastLoginAt).toLocaleDateString()
                        : "Never"}
                    </p>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Login Count
                    </label>
                    <p className="text-base text-gray-900">{user.loginCount}</p>
                  </div>
                </div>
              </div>

              {/* Session Activity Summary */}
              {loginHistory.length > 0 && (
                <div className="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
                  <h4 className="font-semibold text-brand-ink mb-3 flex items-center gap-2">
                    <Clock className="w-4 h-4" />
                    Session Activity
                  </h4>
                  <div className="grid grid-cols-4 gap-4">
                    <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
                      <div className="text-2xl font-bold text-green-600">
                        {
                          loginHistory.filter((l) => l.success && !l.logoutAt)
                            .length
                        }
                      </div>
                      <div className="text-xs text-gray-600 mt-1">
                        Active Sessions
                      </div>
                    </div>
                    <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
                      <div className="text-2xl font-bold text-blue-600">
                        {loginHistory.filter((l) => l.success).length}
                      </div>
                      <div className="text-xs text-gray-600 mt-1">
                        Successful Logins
                      </div>
                    </div>
                    <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
                      <div className="text-2xl font-bold text-red-600">
                        {loginHistory.filter((l) => !l.success).length}
                      </div>
                      <div className="text-xs text-gray-600 mt-1">
                        Failed Attempts
                      </div>
                    </div>
                    <div className="text-center p-3 bg-white rounded-lg border border-blue-100">
                      <div className="text-2xl font-bold text-gray-600">
                        {
                          new Set(
                            loginHistory.map((l) => l.country).filter(Boolean),
                          ).size
                        }
                      </div>
                      <div className="text-xs text-gray-600 mt-1">
                        Countries
                      </div>
                    </div>
                  </div>
                  <button
                    onClick={() => setActiveTab("history")}
                    className="mt-3 text-sm text-blue-600 hover:text-blue-800 font-medium"
                  >
                    View Full Session History →
                  </button>
                </div>
              )}

              {/* Subscription & Billing - Only for non-team-members */}
              {!userDetails?.isTeamMember && (
                <div>
                  <h4 className="font-semibold text-brand-ink mb-3">
                    Subscription
                  </h4>
                  <div className="grid grid-cols-2 gap-6">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Selected Package
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.selectedPackage || "-"}
                      </p>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">
                        Stripe Customer
                      </label>
                      <p className="text-base text-gray-900">
                        {userDetails?.stripeCustomerId
                          ? "✅ Connected"
                          : "❌ Not connected"}
                      </p>
                    </div>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Tab 2: Login History */}
          {activeTab === "history" && (
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold text-brand-ink">
                  Session Activity
                </h3>
                <div className="flex items-center gap-4 text-sm">
                  <div className="flex items-center gap-2">
                    <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                    <span className="text-gray-600">Active</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="w-2 h-2 bg-gray-400 rounded-full" />
                    <span className="text-gray-600">Ended</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="w-2 h-2 bg-red-500 rounded-full" />
                    <span className="text-gray-600">Failed</span>
                  </div>
                </div>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Status
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Login
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Logout
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Duration
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        Location
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">
                        IP / Provider
                      </th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {loginHistory.map((entry) => {
                      const isActive = entry.success && !entry.logoutAt;
                      const isFailed = !entry.success;
                      const sessionDuration =
                        entry.logoutAt && entry.timestamp
                          ? Math.round(
                              (new Date(entry.logoutAt).getTime() -
                                new Date(entry.timestamp).getTime()) /
                                (1000 * 60),
                            )
                          : null;
                      const formatDuration = (minutes: number | null) => {
                        if (minutes === null) return "-";
                        if (minutes < 60) return `${minutes}m`;
                        const hours = Math.floor(minutes / 60);
                        const mins = minutes % 60;
                        if (hours < 24) return `${hours}h ${mins}m`;
                        const days = Math.floor(hours / 24);
                        const remainingHours = hours % 24;
                        return `${days}d ${remainingHours}h`;
                      };
                      return (
                        <tr
                          key={entry.id}
                          className={isFailed ? "bg-red-50" : ""}
                        >
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2">
                              <span
                                className={`w-2.5 h-2.5 rounded-full ${
                                  isFailed
                                    ? "bg-red-500"
                                    : isActive
                                      ? "bg-green-500 animate-pulse"
                                      : "bg-gray-400"
                                }`}
                              />
                              <span
                                className={`text-xs font-medium px-2 py-0.5 rounded ${
                                  isFailed
                                    ? "bg-red-100 text-red-700"
                                    : isActive
                                      ? "bg-green-100 text-green-700"
                                      : "bg-gray-100 text-gray-600"
                                }`}
                              >
                                {isFailed
                                  ? "Failed"
                                  : isActive
                                    ? "Active"
                                    : "Ended"}
                              </span>
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <div className="text-sm">
                              <div className="font-medium text-gray-900">
                                {new Date(entry.timestamp).toLocaleDateString()}
                              </div>
                              <div className="text-gray-500">
                                {new Date(entry.timestamp).toLocaleTimeString()}
                              </div>
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            {entry.logoutAt ? (
                              <div className="text-sm">
                                <div className="font-medium text-gray-900">
                                  {new Date(
                                    entry.logoutAt,
                                  ).toLocaleDateString()}
                                </div>
                                <div className="text-gray-500">
                                  {new Date(
                                    entry.logoutAt,
                                  ).toLocaleTimeString()}
                                </div>
                              </div>
                            ) : (
                              <span className="text-sm text-gray-400">
                                {isFailed ? "-" : "Still active"}
                              </span>
                            )}
                          </td>
                          <td className="px-4 py-3 text-sm">
                            {isFailed ? (
                              <span className="text-red-600">-</span>
                            ) : isActive ? (
                              <span className="text-green-600 font-medium">
                                Ongoing
                              </span>
                            ) : (
                              <span className="text-gray-600">
                                {formatDuration(sessionDuration)}
                              </span>
                            )}
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-1">
                              <MapPin className="w-3 h-3 text-gray-400" />
                              <span className="text-sm">
                                {entry.city && entry.country
                                  ? `${entry.city}, ${entry.country}`
                                  : entry.country || "-"}
                              </span>
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex flex-col gap-1">
                              <div className="flex items-center gap-2">
                                <code className="text-xs text-gray-600">
                                  {entry.ipAddress}
                                </code>
                                <button
                                  onClick={() =>
                                    copyToClipboard(entry.ipAddress)
                                  }
                                >
                                  {copiedText === entry.ipAddress ? (
                                    <Check className="w-3 h-3 text-green-600" />
                                  ) : (
                                    <Copy className="w-3 h-3 text-gray-400 hover:text-gray-600" />
                                  )}
                                </button>
                              </div>
                              <span
                                className={`text-xs px-1.5 py-0.5 rounded w-fit ${
                                  entry.provider === "google"
                                    ? "bg-blue-100 text-blue-700"
                                    : "bg-gray-100 text-gray-600"
                                }`}
                              >
                                {entry.provider === "google"
                                  ? "Google"
                                  : "Email/OTP"}
                              </span>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
              {loginHistory.length === 0 && (
                <div className="text-center py-8 text-gray-500">
                  No login history available
                </div>
              )}
            </div>
          )}

          {/* Tab 3: Admin Notes */}
          {activeTab === "notes" && (
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-semibold text-brand-ink mb-4">
                  Add New Note
                </h3>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Category
                    </label>
                    <select
                      value={noteCategory}
                      onChange={(e) =>
                        setNoteCategory(e.target.value as AdminNote["category"])
                      }
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                    >
                      <option value="general">General</option>
                      <option value="support">Support</option>
                      <option value="billing">Billing</option>
                      <option value="security">Security</option>
                      <option value="compliance">Compliance</option>
                      <option value="technical">Technical</option>
                      <option value="sales">Sales</option>
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Note
                    </label>
                    <textarea
                      value={newNote}
                      onChange={(e) => setNewNote(e.target.value)}
                      rows={4}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                      placeholder="Enter your note here..."
                    />
                  </div>
                  <button
                    onClick={handleAddNote}
                    disabled={!newNote.trim()}
                    className="px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    Add Note
                  </button>
                </div>
              </div>

              <div>
                <h3 className="text-lg font-semibold text-brand-ink mb-4">
                  Previous Notes
                </h3>
                <div className="space-y-3">
                  {adminNotes.map((note) => (
                    <div key={note.id} className="p-4 bg-gray-50 rounded-lg">
                      <div className="flex items-start justify-between mb-2">
                        <span className="inline-flex px-2 py-1 text-xs font-medium bg-blue-100 text-blue-800 rounded">
                          {note.category}
                        </span>
                        <span className="text-xs text-gray-500">
                          {new Date(note.createdAt).toLocaleString()}
                        </span>
                      </div>
                      <p className="text-sm text-gray-900">{note.content}</p>
                      <p className="text-xs text-gray-500 mt-2">
                        By {note.createdBy}
                      </p>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Tab 4: Billing */}
          {activeTab === "billing" && (
            <div className="space-y-6">
              {/* Team Member Notice */}
              {userDetails?.isTeamMember && (
                <div className="p-6 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-3 mb-3">
                    <div className="p-2 bg-blue-100 rounded-lg">
                      <Users className="w-5 h-5 text-blue-600" />
                    </div>
                    <div>
                      <h3 className="text-lg font-semibold text-brand-ink">
                        Team Member
                      </h3>
                      <p className="text-sm text-gray-600">
                        Billing is managed by the organization owner
                      </p>
                    </div>
                  </div>
                  <div className="p-4 bg-white/50 border border-blue-200 rounded-lg">
                    <p className="text-sm text-gray-700 mb-2">
                      This user is a member of{" "}
                      <strong>
                        {userDetails.teamMembership?.organizationName}
                      </strong>
                      .
                    </p>
                    <p className="text-sm text-gray-600">
                      Subscription and billing are handled by the organization
                      owner:
                      <strong className="ml-1">
                        {userDetails.teamMembership?.owner?.name}
                      </strong>
                      <span className="text-gray-500 ml-1">
                        ({userDetails.teamMembership?.owner?.email})
                      </span>
                    </p>
                  </div>
                </div>
              )}

              {/* Subscription Information - Only for non-team-members */}
              {!userDetails?.isTeamMember &&
                userDetails?.subscriptions &&
                userDetails.subscriptions.length > 0 && (
                  <div className="p-6 bg-gradient-to-r from-green-50 to-blue-50 border border-green-200 rounded-lg">
                    <h3 className="text-lg font-semibold text-brand-ink mb-4">
                      Current Subscription
                    </h3>
                    {userDetails.subscriptions.slice(0, 1).map((sub: any) => (
                      <div key={sub.id} className="space-y-3">
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <p className="text-xs text-gray-600 uppercase">
                              Plan
                            </p>
                            <p className="text-lg font-semibold text-brand-ink">
                              {sub.tierId || "Unknown"}
                            </p>
                          </div>
                          <div>
                            <p className="text-xs text-gray-600 uppercase">
                              Status
                            </p>
                            <span
                              className={`inline-flex px-3 py-1 text-sm font-medium rounded-full ${
                                sub.status === "active"
                                  ? "bg-green-100 text-green-800"
                                  : sub.status === "trialing"
                                    ? "bg-blue-100 text-blue-800"
                                    : sub.status === "past_due"
                                      ? "bg-orange-100 text-orange-800"
                                      : "bg-gray-100 text-gray-800"
                              }`}
                            >
                              {sub.status}
                            </span>
                          </div>
                          <div>
                            <p className="text-xs text-gray-600 uppercase">
                              Billing Period
                            </p>
                            <p className="text-base font-medium">
                              {sub.billingPeriod || "monthly"}
                            </p>
                          </div>
                          <div>
                            <p className="text-xs text-gray-600 uppercase">
                              Next Billing Date
                            </p>
                            <p className="text-base font-medium">
                              {sub.currentPeriodEnd
                                ? new Date(
                                    sub.currentPeriodEnd,
                                  ).toLocaleDateString()
                                : "N/A"}
                            </p>
                          </div>
                          {sub.cardBrand && (
                            <>
                              <div>
                                <p className="text-xs text-gray-600 uppercase">
                                  Payment Method
                                </p>
                                <p className="text-base font-medium">
                                  {sub.cardBrand} •••• {sub.cardLastFour}
                                </p>
                              </div>
                              <div>
                                <p className="text-xs text-gray-600 uppercase">
                                  Last Payment
                                </p>
                                <p className="text-base font-medium">
                                  {sub.lastPaymentDate
                                    ? new Date(
                                        sub.lastPaymentDate,
                                      ).toLocaleDateString()
                                    : "N/A"}
                                </p>
                              </div>
                            </>
                          )}
                          {sub.trialEndsAt && (
                            <div className="col-span-2">
                              <p className="text-xs text-gray-600 uppercase">
                                Trial Ends
                              </p>
                              <p className="text-base font-medium">
                                {new Date(sub.trialEndsAt).toLocaleDateString()}
                              </p>
                            </div>
                          )}
                          {sub.cancelAtPeriodEnd && (
                            <div className="col-span-2 p-3 bg-yellow-100 border border-yellow-300 rounded">
                              <p className="text-sm text-yellow-800">
                                ⚠️ Subscription will cancel at period end
                              </p>
                            </div>
                          )}
                        </div>
                      </div>
                    ))}
                  </div>
                )}

              {/* No subscription message - Only for non-team-members */}
              {!userDetails?.isTeamMember &&
                (!userDetails?.subscriptions ||
                  userDetails.subscriptions.length === 0) && (
                  <div className="p-4 bg-gray-50 border border-gray-200 rounded-lg">
                    <p className="text-sm text-gray-600">
                      No active subscription
                    </p>
                  </div>
                )}

              {/* Invoice History - Only for non-team-members */}
              {!userDetails?.isTeamMember && (
                <div>
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="text-lg font-semibold text-brand-ink flex items-center gap-2">
                      <Receipt className="w-5 h-5" />
                      Invoice History
                    </h3>
                    <button
                      onClick={() => fetchInvoices()}
                      disabled={loadingInvoices}
                      className="flex items-center gap-1 px-3 py-1 text-sm text-gray-600 hover:text-gray-900 border rounded-lg hover:bg-gray-50"
                    >
                      <RefreshCw
                        className={`w-4 h-4 ${loadingInvoices ? "animate-spin" : ""}`}
                      />
                      Refresh
                    </button>
                  </div>

                  {/* Summary Stats */}
                  {invoiceSummary && (
                    <div className="grid grid-cols-4 gap-4 mb-4">
                      <div className="p-3 bg-green-50 border border-green-200 rounded-lg text-center">
                        <p className="text-2xl font-bold text-green-700">
                          £{(invoiceSummary.totalPaid / 100).toFixed(2)}
                        </p>
                        <p className="text-xs text-green-600">Total Paid</p>
                      </div>
                      <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-center">
                        <p className="text-2xl font-bold text-blue-700">
                          {invoiceSummary.paidInvoices}
                        </p>
                        <p className="text-xs text-blue-600">Paid Invoices</p>
                      </div>
                      <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-center">
                        <p className="text-2xl font-bold text-yellow-700">
                          {invoiceSummary.openInvoices}
                        </p>
                        <p className="text-xs text-yellow-600">Open Invoices</p>
                      </div>
                      <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-center">
                        <p className="text-2xl font-bold text-red-700">
                          {invoiceSummary.failedPayments}
                        </p>
                        <p className="text-xs text-red-600">Failed Payments</p>
                      </div>
                    </div>
                  )}

                  {/* Invoice List */}
                  {loadingInvoices ? (
                    <div className="p-8 text-center text-gray-500">
                      <RefreshCw className="w-8 h-8 animate-spin mx-auto mb-2" />
                      Loading invoices...
                    </div>
                  ) : invoices.length === 0 ? (
                    <div className="p-6 bg-gray-50 border border-gray-200 rounded-lg text-center">
                      <Receipt className="w-8 h-8 text-gray-400 mx-auto mb-2" />
                      <p className="text-sm text-gray-600">No invoices found</p>
                    </div>
                  ) : (
                    <div className="space-y-2">
                      {(showAllInvoices ? invoices : invoices.slice(0, 5)).map(
                        (invoice) => (
                          <div
                            key={invoice.id}
                            className="flex items-center justify-between p-4 bg-gray-50 border border-gray-200 rounded-lg hover:bg-gray-100"
                          >
                            <div className="flex-1">
                              <div className="flex items-center gap-3">
                                <span
                                  className={`px-2 py-1 text-xs font-medium rounded ${
                                    invoice.status === "paid"
                                      ? "bg-green-100 text-green-800"
                                      : invoice.status === "open"
                                        ? "bg-yellow-100 text-yellow-800"
                                        : invoice.status === "draft"
                                          ? "bg-gray-100 text-gray-800"
                                          : invoice.status === "void"
                                            ? "bg-red-100 text-red-800"
                                            : "bg-gray-100 text-gray-800"
                                  }`}
                                >
                                  {invoice.status}
                                </span>
                                <span className="text-sm font-medium text-gray-900">
                                  {invoice.number || invoice.id.slice(0, 12)}
                                </span>
                              </div>
                              <p className="text-sm text-gray-600 mt-1">
                                {invoice.description}
                              </p>
                              <div className="flex items-center gap-4 mt-1 text-xs text-gray-500">
                                <span>
                                  Created:{" "}
                                  {new Date(
                                    invoice.createdAt,
                                  ).toLocaleDateString()}
                                </span>
                                {invoice.paidAt && (
                                  <span className="text-green-600">
                                    Paid:{" "}
                                    {new Date(
                                      invoice.paidAt,
                                    ).toLocaleDateString()}
                                  </span>
                                )}
                              </div>
                            </div>
                            <div className="flex items-center gap-4">
                              <div className="text-right">
                                <p className="text-lg font-bold text-gray-900">
                                  {invoice.currency === "GBP"
                                    ? "£"
                                    : invoice.currency === "USD"
                                      ? "$"
                                      : invoice.currency === "EUR"
                                        ? "€"
                                        : invoice.currency + " "}
                                  {(invoice.amount / 100).toFixed(2)}
                                </p>
                              </div>
                              <div className="flex items-center gap-2">
                                {invoice.hostedInvoiceUrl && (
                                  <a
                                    href={invoice.hostedInvoiceUrl}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="p-2 text-gray-500 hover:text-brand-green hover:bg-green-50 rounded"
                                    title="View Invoice"
                                  >
                                    <ExternalLink className="w-4 h-4" />
                                  </a>
                                )}
                                {invoice.invoicePdf && (
                                  <a
                                    href={invoice.invoicePdf}
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="p-2 text-gray-500 hover:text-brand-green hover:bg-green-50 rounded"
                                    title="Download PDF"
                                  >
                                    <Download className="w-4 h-4" />
                                  </a>
                                )}
                              </div>
                            </div>
                          </div>
                        ),
                      )}

                      {invoices.length > 5 && (
                        <button
                          onClick={() => setShowAllInvoices(!showAllInvoices)}
                          className="w-full flex items-center justify-center gap-2 py-2 text-sm text-gray-600 hover:text-gray-900 border border-gray-200 rounded-lg hover:bg-gray-50"
                        >
                          {showAllInvoices ? (
                            <>
                              <ChevronUp className="w-4 h-4" />
                              Show less
                            </>
                          ) : (
                            <>
                              <ChevronDown className="w-4 h-4" />
                              Show all {invoices.length} invoices
                            </>
                          )}
                        </button>
                      )}
                    </div>
                  )}
                </div>
              )}

              {/* Send Billing Email with Payment Link - Only for non-team-members */}
              {!userDetails?.isTeamMember && (
                <div className="border border-gray-200 rounded-lg p-6">
                  <h3 className="text-lg font-semibold text-brand-ink mb-4 flex items-center gap-2">
                    <Mail className="w-5 h-5" />
                    Send Billing Email
                  </h3>
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Subject *
                      </label>
                      <input
                        type="text"
                        value={billingSubject}
                        onChange={(e) => setBillingSubject(e.target.value)}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        placeholder="Invoice for December 2025"
                      />
                    </div>

                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Message *
                      </label>
                      <textarea
                        value={billingMessage}
                        onChange={(e) => setBillingMessage(e.target.value)}
                        rows={4}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        placeholder="Dear customer, please find your invoice attached..."
                      />
                    </div>

                    <div className="grid grid-cols-3 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          <DollarSign className="w-4 h-4 inline mr-1" />
                          Amount {includePaymentLink && "*"}
                        </label>
                        <input
                          type="number"
                          value={billingAmount}
                          onChange={(e) => setBillingAmount(e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                          placeholder="99.99"
                          min="0"
                          step="0.01"
                        />
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Currency
                        </label>
                        <select
                          value={billingCurrency}
                          onChange={(e) => setBillingCurrency(e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        >
                          {CURRENCY_OPTIONS.map((curr) => (
                            <option key={curr.value} value={curr.value}>
                              {curr.label}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          <Calendar className="w-4 h-4 inline mr-1" />
                          Due Date
                        </label>
                        <input
                          type="date"
                          value={billingDueDate}
                          onChange={(e) => setBillingDueDate(e.target.value)}
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                          min={new Date().toISOString().split("T")[0]}
                        />
                      </div>
                    </div>

                    <div className="flex items-center gap-3 p-4 bg-green-50 border border-green-200 rounded-lg">
                      <input
                        type="checkbox"
                        id="includePaymentLink"
                        checked={includePaymentLink}
                        onChange={(e) =>
                          setIncludePaymentLink(e.target.checked)
                        }
                        className="w-5 h-5 text-brand-green rounded focus:ring-brand-green"
                      />
                      <label htmlFor="includePaymentLink" className="flex-1">
                        <span className="font-medium text-gray-900">
                          Include Payment Link
                        </span>
                        <p className="text-sm text-gray-600">
                          Generate a secure Stripe checkout link for the user to
                          pay directly via the email
                        </p>
                      </label>
                      <CreditCard className="w-6 h-6 text-green-600" />
                    </div>

                    <button
                      onClick={handleSendBillingEmail}
                      disabled={
                        submitting ||
                        !billingSubject.trim() ||
                        !billingMessage.trim() ||
                        (includePaymentLink &&
                          (!billingAmount || parseFloat(billingAmount) <= 0))
                      }
                      className="flex items-center justify-center gap-2 w-full px-4 py-3 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium"
                    >
                      {submitting ? (
                        <>
                          <RefreshCw className="w-4 h-4 animate-spin" />
                          Sending...
                        </>
                      ) : (
                        <>
                          <Mail className="w-4 h-4" />
                          {includePaymentLink
                            ? "Send Email with Payment Link"
                            : "Send Billing Email"}
                        </>
                      )}
                    </button>
                  </div>
                </div>
              )}

              {/* Email History - Only for non-team-members */}
              {!userDetails?.isTeamMember && billingEmails.length > 0 && (
                <div>
                  <h3 className="text-lg font-semibold text-brand-ink mb-4">
                    Recent Billing Emails
                  </h3>
                  <div className="space-y-2">
                    {billingEmails.slice(0, 10).map((email) => (
                      <div
                        key={email.id}
                        className="flex items-center justify-between p-4 bg-gray-50 rounded-lg"
                      >
                        <div>
                          <p className="text-sm font-medium text-gray-900">
                            {email.subject}
                          </p>
                          <p className="text-xs text-gray-500 mt-1">
                            {new Date(email.sentAt).toLocaleString()}
                            {email.amount && (
                              <span className="ml-2 text-green-600 font-medium">
                                £{email.amount.toFixed(2)}
                              </span>
                            )}
                          </p>
                        </div>
                        <span
                          className={`px-2 py-1 text-xs font-medium rounded ${
                            email.status === "sent"
                              ? "bg-green-100 text-green-800"
                              : email.status === "paid"
                                ? "bg-blue-100 text-blue-800"
                                : email.status === "overdue"
                                  ? "bg-orange-100 text-orange-800"
                                  : "bg-red-100 text-red-800"
                          }`}
                        >
                          {email.status}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Tab 5: Links */}
          {activeTab === "links" && (
            <div className="space-y-6">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-lg font-semibold text-brand-ink">
                    Integration Links
                  </h3>
                  <p className="text-sm text-gray-600 mt-1">
                    Manage links to knowledge base, AI agents, and other
                    integrations for this user.
                  </p>
                </div>
                {!showLinkForm && (
                  <button
                    onClick={() => setShowLinkForm(true)}
                    className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700"
                  >
                    <Plus className="w-4 h-4" />
                    Add Link
                  </button>
                )}
              </div>

              {/* Add/Edit Link Form */}
              {showLinkForm && (
                <div className="p-6 bg-gray-50 border border-gray-200 rounded-lg">
                  <h4 className="font-semibold text-brand-ink mb-4">
                    {editingLink ? "Edit Link" : "Add New Link"}
                  </h4>
                  <div className="space-y-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Link Type
                        </label>
                        <select
                          value={linkForm.linkType}
                          onChange={(e) =>
                            setLinkForm({
                              ...linkForm,
                              linkType: e.target.value as UserLink["linkType"],
                            })
                          }
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        >
                          {LINK_TYPE_OPTIONS.map((option) => (
                            <option key={option.value} value={option.value}>
                              {option.icon} {option.label}
                            </option>
                          ))}
                        </select>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Title
                        </label>
                        <input
                          type="text"
                          value={linkForm.title}
                          onChange={(e) =>
                            setLinkForm({ ...linkForm, title: e.target.value })
                          }
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                          placeholder="e.g., Knowledge Base Portal"
                        />
                      </div>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        URL
                      </label>
                      <input
                        type="url"
                        value={linkForm.url}
                        onChange={(e) =>
                          setLinkForm({ ...linkForm, url: e.target.value })
                        }
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        placeholder="https://..."
                      />
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Description (Optional)
                      </label>
                      <textarea
                        value={linkForm.description}
                        onChange={(e) =>
                          setLinkForm({
                            ...linkForm,
                            description: e.target.value,
                          })
                        }
                        rows={2}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        placeholder="Brief description of this link..."
                      />
                    </div>
                    <div className="flex items-center gap-3">
                      <button
                        onClick={editingLink ? handleUpdateLink : handleAddLink}
                        disabled={
                          !linkForm.title.trim() ||
                          !linkForm.url.trim() ||
                          submitting
                        }
                        className="px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {submitting
                          ? "Saving..."
                          : editingLink
                            ? "Update Link"
                            : "Add Link"}
                      </button>
                      <button
                        onClick={resetLinkForm}
                        className="px-4 py-2 text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300"
                      >
                        Cancel
                      </button>
                    </div>
                  </div>
                </div>
              )}

              {/* Existing Links */}
              <div>
                <h4 className="font-semibold text-brand-ink mb-4">
                  Configured Links ({userLinks.length})
                </h4>
                {userLinks.length === 0 ? (
                  <div className="p-8 text-center bg-gray-50 border border-dashed border-gray-300 rounded-lg">
                    <Link2 className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                    <p className="text-gray-600">No links configured yet</p>
                    <p className="text-sm text-gray-500 mt-1">
                      Add links to help this user access their integrations
                    </p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {userLinks.map((link) => {
                      const typeInfo = getLinkTypeInfo(link.linkType);
                      return (
                        <div
                          key={link.id}
                          className="flex items-center justify-between p-4 bg-white border border-gray-200 rounded-lg hover:border-gray-300 transition"
                        >
                          <div className="flex items-center gap-4">
                            <span className="text-2xl">{typeInfo.icon}</span>
                            <div>
                              <div className="flex items-center gap-2">
                                <p className="font-medium text-gray-900">
                                  {link.title}
                                </p>
                                <span className="px-2 py-0.5 text-xs font-medium bg-gray-100 text-gray-600 rounded">
                                  {typeInfo.label}
                                </span>
                              </div>
                              <a
                                href={link.url}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="text-sm text-brand-green hover:underline flex items-center gap-1 mt-1"
                              >
                                {link.url.length > 50
                                  ? link.url.substring(0, 50) + "..."
                                  : link.url}
                                <ExternalLink className="w-3 h-3" />
                              </a>
                              {link.description && (
                                <p className="text-xs text-gray-500 mt-1">
                                  {link.description}
                                </p>
                              )}
                            </div>
                          </div>
                          <div className="flex items-center gap-2">
                            <button
                              onClick={() => copyToClipboard(link.url)}
                              className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                              title="Copy URL"
                            >
                              {copiedText === link.url ? (
                                <Check className="w-4 h-4 text-green-600" />
                              ) : (
                                <Copy className="w-4 h-4" />
                              )}
                            </button>
                            <button
                              onClick={() => startEditLink(link)}
                              className="p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition"
                              title="Edit"
                            >
                              <Edit3 className="w-4 h-4" />
                            </button>
                            <button
                              onClick={() => handleDeleteLink(link.id)}
                              className="p-2 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition"
                              title="Delete"
                            >
                              <Trash2 className="w-4 h-4" />
                            </button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Tab 6: Integrations */}
          {activeTab === "integrations" && (
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-semibold text-brand-ink">
                  Integration Settings
                </h3>
                <p className="text-sm text-gray-600 mt-1">
                  Configure N8N workflows, voice agents, and other integrations
                  for this user's dashboard.
                </p>
              </div>

              {/* N8N Webhook Token */}
              <div className="p-6 bg-white border border-gray-200 rounded-lg">
                <div className="flex items-center gap-3 mb-4">
                  <div className="p-2 bg-blue-100 rounded-lg">
                    <Zap className="w-5 h-5 text-blue-600" />
                  </div>
                  <div>
                    <h4 className="font-semibold text-brand-ink">
                      N8N Webhook Integration
                    </h4>
                    <p className="text-sm text-gray-600">
                      Enable AI workflow automation via N8N
                    </p>
                  </div>
                </div>

                {integrations.n8nWebhookToken ? (
                  <div className="space-y-4">
                    <div className="p-3 bg-green-50 border border-green-200 rounded-lg">
                      <div className="flex items-center gap-2 mb-2">
                        <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                        <span className="text-sm font-medium text-green-700">
                          Token Active
                        </span>
                      </div>
                      <div className="flex items-center gap-2">
                        <code className="flex-1 text-xs bg-white px-2 py-1 rounded border border-green-200 overflow-hidden text-ellipsis">
                          {integrations.n8nWebhookToken.substring(0, 20)}...
                        </code>
                        <button
                          onClick={() =>
                            copyToClipboard(integrations.n8nWebhookToken)
                          }
                          className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition"
                        >
                          {copiedText === integrations.n8nWebhookToken ? (
                            <Check className="w-4 h-4 text-green-600" />
                          ) : (
                            <Copy className="w-4 h-4" />
                          )}
                        </button>
                      </div>
                    </div>
                    <div className="flex gap-3">
                      <button
                        onClick={handleGenerateToken}
                        disabled={generatingToken}
                        className="flex items-center gap-2 px-4 py-2 text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 disabled:opacity-50"
                      >
                        <RefreshCw
                          className={`w-4 h-4 ${generatingToken ? "animate-spin" : ""}`}
                        />
                        Regenerate Token
                      </button>
                      <button
                        onClick={handleRevokeToken}
                        disabled={submitting}
                        className="flex items-center gap-2 px-4 py-2 text-red-600 bg-red-50 rounded-lg hover:bg-red-100 disabled:opacity-50"
                      >
                        Revoke Token
                      </button>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-4">
                    <div className="p-3 bg-gray-50 border border-gray-200 rounded-lg">
                      <p className="text-sm text-gray-600">
                        No webhook token configured. Generate one to enable N8N
                        integrations.
                      </p>
                    </div>
                    <button
                      onClick={handleGenerateToken}
                      disabled={generatingToken}
                      className="flex items-center gap-2 px-4 py-2 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
                    >
                      <Zap
                        className={`w-4 h-4 ${generatingToken ? "animate-spin" : ""}`}
                      />
                      {generatingToken ? "Generating..." : "Generate Token"}
                    </button>
                  </div>
                )}
              </div>

              {/* Voice Agent Configuration */}
              <div className="p-6 bg-white border border-gray-200 rounded-lg">
                <div className="flex items-center gap-3 mb-4">
                  <div className="p-2 bg-purple-100 rounded-lg">
                    <Phone className="w-5 h-5 text-purple-600" />
                  </div>
                  <div>
                    <h4 className="font-semibold text-brand-ink">
                      AI Voice Agent
                    </h4>
                    <p className="text-sm text-gray-600">
                      Configure ElevenLabs voice agent for this user
                    </p>
                  </div>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Voice Agent ID
                    </label>
                    <input
                      type="text"
                      value={integrations.voiceAgentId}
                      onChange={(e) =>
                        setIntegrations((prev) => ({
                          ...prev,
                          voiceAgentId: e.target.value,
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                      placeholder="agent_xxxxx"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      The ElevenLabs agent ID for this user
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Agent Phone Number
                    </label>
                    <input
                      type="text"
                      value={integrations.voiceAgentConfig?.phoneNumber || ""}
                      onChange={(e) =>
                        setIntegrations((prev) => ({
                          ...prev,
                          voiceAgentConfig: {
                            ...prev.voiceAgentConfig,
                            phoneNumber: e.target.value,
                          },
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                      placeholder="+1234567890"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      The phone number assigned to this voice agent
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Greeting Message
                    </label>
                    <textarea
                      value={integrations.voiceAgentConfig?.greeting || ""}
                      onChange={(e) =>
                        setIntegrations((prev) => ({
                          ...prev,
                          voiceAgentConfig: {
                            ...prev.voiceAgentConfig,
                            greeting: e.target.value,
                          },
                        }))
                      }
                      rows={2}
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                      placeholder="Hello, this is the AI receptionist for..."
                    />
                  </div>
                </div>
              </div>

              {/* WhatsApp Configuration */}
              <div className="p-6 bg-white border border-gray-200 rounded-lg">
                <div className="flex items-center gap-3 mb-4">
                  <div className="p-2 bg-green-100 rounded-lg">
                    <MessageSquare className="w-5 h-5 text-green-600" />
                  </div>
                  <div>
                    <h4 className="font-semibold text-brand-ink">
                      WhatsApp Integration
                    </h4>
                    <p className="text-sm text-gray-600">
                      Configure WhatsApp Business API settings
                    </p>
                  </div>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      WhatsApp Number
                    </label>
                    <input
                      type="text"
                      value={
                        integrations.voiceAgentConfig?.whatsappNumber || ""
                      }
                      onChange={(e) =>
                        setIntegrations((prev) => ({
                          ...prev,
                          voiceAgentConfig: {
                            ...prev.voiceAgentConfig,
                            whatsappNumber: e.target.value,
                          },
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                      placeholder="+1234567890"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      The WhatsApp Business number for this user
                    </p>
                  </div>

                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-2">
                      Business Hours
                    </label>
                    <input
                      type="text"
                      value={integrations.voiceAgentConfig?.businessHours || ""}
                      onChange={(e) =>
                        setIntegrations((prev) => ({
                          ...prev,
                          voiceAgentConfig: {
                            ...prev.voiceAgentConfig,
                            businessHours: e.target.value,
                          },
                        }))
                      }
                      className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                      placeholder="Mon-Fri 9am-5pm"
                    />
                  </div>
                </div>
              </div>

              {/* Save Button */}
              <div className="flex justify-end">
                <button
                  onClick={handleSaveIntegrations}
                  disabled={submitting}
                  className="flex items-center gap-2 px-6 py-2.5 bg-brand-green text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
                >
                  {submitting ? "Saving..." : "Save Integration Settings"}
                </button>
              </div>
            </div>
          )}

          {/* Tab 7: Actions */}
          {activeTab === "actions" && isAdmin && (
            <div className="space-y-6">
              <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                <p className="text-sm text-yellow-800">
                  ⚠️ These actions will immediately affect the user&apos;s
                  account. Use with caution.
                </p>
              </div>

              {/* Team Member Notice in Actions */}
              {userDetails?.isTeamMember && (
                <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-2 mb-2">
                    <Users className="w-5 h-5 text-blue-600" />
                    <span className="font-medium text-blue-800">
                      Team Member
                    </span>
                  </div>
                  <p className="text-sm text-blue-700">
                    This user is a team member of{" "}
                    <strong>
                      {userDetails.teamMembership?.organizationName}
                    </strong>
                    . Some actions like trial extension are not applicable as
                    billing is managed by the organization owner.
                  </p>
                </div>
              )}

              {/* Trial Extension - Only for non-team-members */}
              {!userDetails?.isTeamMember &&
                userDetails?.subscriptions &&
                userDetails.subscriptions.length > 0 &&
                userDetails.subscriptions[0].status === "trialing" && (
                  <div className="p-6 bg-white border border-blue-200 rounded-lg">
                    <h3 className="text-lg font-semibold text-brand-ink mb-4">
                      Extend Trial Period
                    </h3>
                    <div className="space-y-4">
                      <div className="p-3 bg-blue-50 rounded-lg">
                        <p className="text-sm text-blue-800">
                          Current trial ends:{" "}
                          {new Date(
                            userDetails.subscriptions[0].trialEndsAt ||
                              userDetails.subscriptions[0].currentPeriodEnd,
                          ).toLocaleDateString()}
                        </p>
                      </div>
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                          Extend trial by (weeks)
                        </label>
                        <select
                          value={trialExtensionWeeks}
                          onChange={(e) =>
                            setTrialExtensionWeeks(parseInt(e.target.value))
                          }
                          className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        >
                          <option value="1">1 week</option>
                          <option value="2">2 weeks</option>
                          <option value="3">3 weeks</option>
                          <option value="4">4 weeks (1 month)</option>
                          <option value="8">8 weeks (2 months)</option>
                          <option value="12">12 weeks (3 months)</option>
                        </select>
                      </div>
                      <button
                        onClick={handleExtendTrial}
                        disabled={submitting}
                        className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {submitting
                          ? "Extending..."
                          : `Extend Trial by ${trialExtensionWeeks} ${trialExtensionWeeks === 1 ? "Week" : "Weeks"}`}
                      </button>
                    </div>
                  </div>
                )}

              {user.status === "active" && (
                <div className="p-6 bg-white border border-gray-200 rounded-lg">
                  <h3 className="text-lg font-semibold text-brand-ink mb-4">
                    Suspend Account
                  </h3>
                  <div className="space-y-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">
                        Reason
                      </label>
                      <textarea
                        value={suspendReason}
                        onChange={(e) => setSuspendReason(e.target.value)}
                        rows={4}
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-green"
                        placeholder="Enter reason for suspension..."
                      />
                    </div>
                    <button
                      onClick={handleSuspend}
                      disabled={!suspendReason.trim() || submitting}
                      className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      {submitting ? "Suspending..." : "Suspend Account"}
                    </button>
                  </div>
                </div>
              )}

              {user.status === "suspended" && (
                <div className="p-6 bg-white border border-gray-200 rounded-lg">
                  <h3 className="text-lg font-semibold text-brand-ink mb-4">
                    Activate Account
                  </h3>
                  <p className="text-sm text-gray-600 mb-4">
                    This will restore the user's access to their account.
                  </p>
                  <button
                    onClick={handleActivate}
                    disabled={submitting}
                    className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {submitting ? "Activating..." : "Activate Account"}
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-end gap-3 p-6 border-t border-gray-200">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  );
}
