"use client";

import { useState, useEffect, Suspense } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Linkedin, Twitter, Facebook, Instagram, Plus, Trash2, Copy, Eye, EyeOff, RefreshCw, type LucideIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import type { UserRole, ContentTrack } from "@/lib/types";

const ALLOWED_EMAIL_DOMAIN = process.env.NEXT_PUBLIC_ALLOWED_EMAIL_DOMAIN || "example.com";

interface SocialAccountData {
  id: string;
  network: string;
  accountName: string;
  accountId: string;
  createdAt: string;
  expiresAt?: string | null;
  profileImageUrl?: string | null;
  tokenStatus?: "valid" | "mock" | "expired" | "missing" | "invalid";
}

function getTokenHealth(expiresAt: string | null | undefined): { label: string; color: string; daysLeft: number | null } {
  if (!expiresAt) return { label: "Unknown", color: "bg-gray-100 text-gray-600", daysLeft: null };
  const days = (new Date(expiresAt).getTime() - Date.now()) / (1000 * 60 * 60 * 24);
  if (days <= 0) return { label: "Expired", color: "bg-red-100 text-red-700", daysLeft: 0 };
  if (days < 7) return { label: `${Math.ceil(days)}d left`, color: "bg-red-100 text-red-700", daysLeft: Math.ceil(days) };
  if (days < 14) return { label: `${Math.ceil(days)}d left`, color: "bg-amber-100 text-amber-700", daysLeft: Math.ceil(days) };
  return { label: `${Math.ceil(days)}d left`, color: "bg-green-100 text-green-700", daysLeft: Math.ceil(days) };
}

const NETWORKS: { network: string; icon: LucideIcon; color: string }[] = [
  { network: "LINKEDIN", icon: Linkedin, color: "text-[#0A66C2]" },
  { network: "TWITTER", icon: Twitter, color: "text-[#1DA1F2]" },
  { network: "FACEBOOK", icon: Facebook, color: "text-[#1877F2]" },
  { network: "INSTAGRAM", icon: Instagram, color: "text-[#E4405F]" },
];

const NETWORK_CONNECT_ROUTES: Record<string, string> = {
  TWITTER: "/api/v1/social-accounts/twitter/connect",
  LINKEDIN: "/api/v1/social-accounts/linkedin/connect",
  FACEBOOK: "/api/v1/social-accounts/facebook/connect",
  INSTAGRAM: "/api/v1/social-accounts/instagram/connect",
};

const API_KEYS = [
  { id: "1", name: "Production", scopes: ["posts:read", "posts:write"], lastUsed: "2026-03-15", createdAt: "2026-01-10" },
  { id: "2", name: "CI/CD Pipeline", scopes: ["posts:read", "analytics:read"], lastUsed: "2026-03-16", createdAt: "2026-02-20" },
];

const ROLE_COLORS: Record<UserRole, string> = {
  ADMIN: "bg-pink-100 text-pink-600",
  EDITOR: "bg-blue-50 text-blue-600",
  VIEWER: "bg-gray-100 text-gray-600",
};

const TRACK_LABELS: Record<ContentTrack, string> = {
  ENTERPRISE: "Enterprise",
  PRODUCT: "Product",
  DEVELOPER: "Developer",
  THOUGHT_LEADERSHIP: "Thought Leadership",
  EVENT: "Event",
  TI_CULTURAL: "Ti-Cultural",
};

interface TrackConfigData {
  track: ContentTrack;
  weeklySlotCap: number;
  requiresApproval: boolean;
  isActive: boolean;
  staggerDelayMinutes: number;
}

interface TeamMemberData {
  id: string;
  name: string | null;
  email: string;
  role: UserRole;
  createdAt: string;
}

interface PendingInviteData {
  id: string;
  email: string;
  role: UserRole;
  status: "PENDING";
  createdAt: string;
  invitedBy: {
    id: string;
    email: string;
    name: string | null;
  };
}

export default function SettingsPage() {
  return (
    <Suspense>
      <SettingsPageContent />
    </Suspense>
  );
}

function SettingsPageContent() {
  const { data: session } = useSession();
  const router = useRouter();
  const role = (session?.user as { role?: UserRole })?.role;

  useEffect(() => {
    if (role && role !== "ADMIN") {
      router.replace("/dashboard");
    }
  }, [role, router]);

  const [inviteEmail, setInviteEmail] = useState("");
  const [inviteRole, setInviteRole] = useState<UserRole>("EDITOR");
  const [pendingInvites, setPendingInvites] = useState<PendingInviteData[]>([]);
  const [invitesLoading, setInvitesLoading] = useState(true);
  const [inviteSaving, setInviteSaving] = useState(false);
  const [inviteError, setInviteError] = useState<string | null>(null);
  const [revokingInviteId, setRevokingInviteId] = useState<string | null>(null);
  const [newKeyName, setNewKeyName] = useState("");
  const [createdKey, setCreatedKey] = useState<string | null>(null);
  const [showKey, setShowKey] = useState(false);
  const [connectedAccounts, setConnectedAccounts] = useState<SocialAccountData[]>([]);
  const [accountsLoading, setAccountsLoading] = useState(true);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [accountsError, setAccountsError] = useState<string | null>(null);
  const [teamMembers, setTeamMembers] = useState<TeamMemberData[]>([]);
  const [teamLoading, setTeamLoading] = useState(true);
  const [teamError, setTeamError] = useState<string | null>(null);
  const [savingMemberId, setSavingMemberId] = useState<string | null>(null);
  const [tracks, setTracks] = useState<TrackConfigData[]>([]);
  const [trackEdits, setTrackEdits] = useState<Record<string, Partial<TrackConfigData>>>({});
  const [trackSaving, setTrackSaving] = useState<string | null>(null);
  const [disconnecting, setDisconnecting] = useState<string | null>(null);
  const [refreshingToken, setRefreshingToken] = useState<string | null>(null);
  const searchParams = useSearchParams();

  useEffect(() => {
    fetch("/api/v1/social-accounts")
      .then(async (res) => {
        if (!res.ok) {
          const payload = await res.json().catch(() => ({}));
          throw new Error(payload?.error || "Failed to load connected accounts");
        }
        return res.json();
      })
      .then((data: SocialAccountData[]) => {
        setConnectedAccounts(data);
        setAccountsError(null);
      })
      .catch((err: unknown) => {
        const message = err instanceof Error ? err.message : "Failed to load connected accounts";
        setConnectedAccounts([]);
        setAccountsError(message);
      })
      .finally(() => setAccountsLoading(false));
  }, []);

  useEffect(() => {
    fetch("/api/v1/tracks")
      .then((res) => (res.ok ? res.json() : []))
      .then((data: TrackConfigData[]) => setTracks(data))
      .catch(() => setTracks([]));
  }, []);

  useEffect(() => {
    fetch("/api/v1/users")
      .then(async (res) => {
        if (!res.ok) {
          const payload = await res.json().catch(() => ({}));
          throw new Error(payload?.error?.message || "Failed to load team members");
        }
        return res.json();
      })
      .then((data: TeamMemberData[]) => {
        setTeamMembers(data);
        setTeamError(null);
      })
      .catch((err: unknown) => {
        const message = err instanceof Error ? err.message : "Failed to load team members";
        setTeamMembers([]);
        setTeamError(message);
      })
      .finally(() => setTeamLoading(false));
  }, []);

  useEffect(() => {
    fetch("/api/v1/invites")
      .then(async (res) => {
        if (!res.ok) {
          const payload = await res.json().catch(() => ({}));
          throw new Error(payload?.error?.message || "Failed to load invites");
        }
        return res.json();
      })
      .then((data: PendingInviteData[]) => {
        setPendingInvites(data);
        setInviteError(null);
      })
      .catch((err: unknown) => {
        const message = err instanceof Error ? err.message : "Failed to load invites";
        setPendingInvites([]);
        setInviteError(message);
      })
      .finally(() => setInvitesLoading(false));
  }, []);

  const handleTrackSave = async (track: ContentTrack) => {
    const edits = trackEdits[track];
    if (!edits) return;
    setTrackSaving(track);
    try {
      const res = await fetch(`/api/v1/tracks/${track}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(edits),
      });
      if (res.ok) {
        const updated = await res.json();
        setTracks((prev) => prev.map((t) => (t.track === track ? { ...t, ...updated } : t)));
        setTrackEdits((prev) => {
          const next = { ...prev };
          delete next[track];
          return next;
        });
      }
    } catch {
      // ignore
    } finally {
      setTrackSaving(null);
    }
  };

  useEffect(() => {
    const connected = searchParams.get("connected");
    if (connected) {
      setSuccessMessage(`Successfully connected ${connected.charAt(0).toUpperCase() + connected.slice(1)}!`);
      const timer = setTimeout(() => setSuccessMessage(null), 5000);
      return () => clearTimeout(timer);
    }
  }, [searchParams]);

  useEffect(() => {
    const error = searchParams.get("error");
    if (!error) return;

    const errorMessages: Record<string, string> = {
      facebook_auth_failed: "Facebook authorization failed. Please retry the connection flow.",
      facebook_not_configured: "Facebook OAuth is not configured on this environment.",
      facebook_token_exchange_failed: "Facebook returned an access token error. Please reconnect and try again.",
      facebook_pages_failed: "Facebook login succeeded, but no manageable Page could be fetched for this account.",
      facebook_oauth_failed: "Facebook connection failed before the account could be saved.",
      instagram_auth_failed: "Instagram authorization failed. Please retry the connection flow.",
      instagram_not_configured: "Instagram OAuth is not configured on this environment.",
      instagram_token_exchange_failed: "Instagram returned an access token error. Please reconnect and try again.",
      instagram_profile_failed: "Instagram login succeeded, but the Instagram account profile could not be fetched.",
      instagram_pages_failed: "Instagram login succeeded, but no linked Instagram professional account could be fetched from your Facebook Pages.",
      instagram_oauth_failed: "Instagram connection failed before the account could be saved.",
      linkedin_auth_failed: "LinkedIn authorization failed. Please retry the connection flow.",
      linkedin_token_exchange_failed: "LinkedIn returned an access token error. Please reconnect and try again.",
      linkedin_profile_failed: "LinkedIn login succeeded, but profile retrieval failed.",
      linkedin_oauth_failed: "LinkedIn connection failed before the account could be saved.",
      twitter_auth_failed: "Twitter authorization failed. Please retry the connection flow.",
      twitter_token_mismatch: "Twitter authorization state did not match. Please try connecting again.",
      twitter_oauth_failed: "Twitter connection failed before the account could be saved.",
    };

    setAccountsError(errorMessages[error] ?? `Social account connection failed: ${error}`);
  }, [searchParams]);

  if (role && role !== "ADMIN") return null;

  const handleRoleChange = async (memberId: string, nextRole: UserRole) => {
    setSavingMemberId(memberId);
    setTeamError(null);
    try {
      const res = await fetch(`/api/v1/users/${memberId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ role: nextRole }),
      });

      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload?.error?.message || "Failed to update role");
      }

      const updatedMember = await res.json() as TeamMemberData;
      setTeamMembers((prev) => prev.map((member) => (
        member.id === updatedMember.id ? updatedMember : member
      )));

      setSuccessMessage(`Updated ${updatedMember.email} to ${updatedMember.role}.`);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Failed to update role";
      setTeamError(message);
    } finally {
      setSavingMemberId(null);
    }
  };

  const handleCreateKey = () => {
    // TODO: POST to /api/v1/api-keys
    setCreatedKey("psh_" + Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2));
    setNewKeyName("");
  };

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

    setInviteSaving(true);
    setInviteError(null);
    try {
      const res = await fetch("/api/v1/invites", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ email, role: inviteRole }),
      });

      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload?.error?.message || "Failed to create invite");
      }

      const invite = await res.json() as PendingInviteData;
      setPendingInvites((prev) => [invite, ...prev.filter((item) => item.id !== invite.id)]);
      setInviteEmail("");
      setSuccessMessage(`Invited ${invite.email} as ${invite.role}.`);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Failed to create invite";
      setInviteError(message);
    } finally {
      setInviteSaving(false);
    }
  };

  const handleRevokeInvite = async (inviteId: string) => {
    setRevokingInviteId(inviteId);
    setInviteError(null);
    try {
      const res = await fetch(`/api/v1/invites/${inviteId}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "REVOKED" }),
      });

      if (!res.ok) {
        const payload = await res.json().catch(() => ({}));
        throw new Error(payload?.error?.message || "Failed to revoke invite");
      }

      setPendingInvites((prev) => prev.filter((invite) => invite.id !== inviteId));
      setSuccessMessage("Invite revoked.");
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : "Failed to revoke invite";
      setInviteError(message);
    } finally {
      setRevokingInviteId(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="border-b border-gray-100 -mx-4 md:-mx-6 -mt-4 md:-mt-6 px-4 sm:px-8 py-4 sm:py-5 mb-4 sm:mb-6">
        <h1 className="text-2xl font-semibold text-gray-900">Settings</h1>
        <p className="text-sm text-gray-500">Manage your account, team, and integrations</p>
      </div>

      <Tabs defaultValue="accounts">
        <TabsList>
          <TabsTrigger value="accounts">Connected Accounts</TabsTrigger>
          <TabsTrigger value="team">Team</TabsTrigger>
          <TabsTrigger value="api-keys">API Keys</TabsTrigger>
          <TabsTrigger value="notifications">Notifications</TabsTrigger>
          <TabsTrigger value="tracks">Tracks</TabsTrigger>
        </TabsList>

        {/* Connected Accounts */}
        <TabsContent value="accounts" className="space-y-4 mt-4">
          {successMessage && (
            <div className="rounded-lg bg-green-50 border border-green-200 px-4 py-3 text-sm text-green-800">
              {successMessage}
            </div>
          )}
          {accountsError && (
            <div className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
              {accountsError}
            </div>
          )}
          <div className="grid gap-4 sm:grid-cols-2">
            {NETWORKS.map((net) => {
              const account = connectedAccounts.find((a) => a.network === net.network);
              const Icon = net.icon;
              const isConnected = !!account;

              const tokenHealth = isConnected && account!.network === "LINKEDIN"
                ? getTokenHealth(account!.expiresAt)
                : null;
              const acct = account!;
              const needsReconnect = isConnected && account!.tokenStatus !== undefined && account!.tokenStatus !== "valid";

              return (
                <Card key={net.network} className="bg-white border border-gray-200 rounded-xl shadow-none">
                  <CardContent className="p-4">
                    <div className="flex items-center gap-4">
                      {account?.profileImageUrl ? (
                        <img src={account.profileImageUrl} alt="" className="h-8 w-8 rounded-full" />
                      ) : (
                        <Icon className={`h-8 w-8 ${net.color}`} />
                      )}
                      <div className="flex-1">
                        <p className="text-sm font-medium text-gray-900">{net.network}</p>
                        {isConnected ? (
                          <div className="flex items-center gap-2">
                            <p className="text-xs text-gray-500">{account.accountName}</p>
                            {needsReconnect ? (
                              <Badge className="bg-amber-100 text-amber-700 text-[10px] rounded-full">Needs Reconnection</Badge>
                            ) : (
                              <Badge className="bg-green-100 text-green-700 text-[10px] rounded-full">Connected</Badge>
                            )}
                          </div>
                        ) : (
                          <p className="text-xs text-gray-500">Not connected</p>
                        )}
                      </div>
                      {isConnected ? (
                        <div className="flex items-center gap-2">
                          {needsReconnect && NETWORK_CONNECT_ROUTES[net.network] && (
                            <Link href={NETWORK_CONNECT_ROUTES[net.network]}>
                              <Button size="sm" className="bg-amber-600 hover:bg-amber-700 text-white">Reconnect</Button>
                            </Link>
                          )}
                          <Button
                            variant="outline"
                            size="sm"
                            className="border-gray-200 text-gray-700 hover:bg-gray-50"
                            disabled={disconnecting === account.id}
                            onClick={async () => {
                              if (disconnecting === account.id) return;
                              if (!confirm(`Disconnect ${account.accountName}?`)) return;
                              setDisconnecting(account.id);
                              try {
                                const res = await fetch(`/api/v1/social-accounts/${account.id}`, { method: "DELETE" });
                                if (!res.ok) {
                                  const err = await res.json().catch(() => ({}));
                                  alert(`Disconnect failed: ${err.error || res.statusText}`);
                                  return;
                                }
                                window.location.reload();
                              } catch (err) {
                                console.error("Disconnect failed:", err);
                                alert("Disconnect failed. Please try again.");
                              } finally {
                                setDisconnecting(null);
                              }
                            }}
                          >
                            {disconnecting === account.id ? "Disconnecting..." : "Disconnect"}
                          </Button>
                        </div>
                      ) : NETWORK_CONNECT_ROUTES[net.network] ? (
                        <Link href={NETWORK_CONNECT_ROUTES[net.network]}>
                          <Button size="sm" className="bg-gray-900 hover:bg-gray-800 text-white">Connect</Button>
                        </Link>
                      ) : (
                        <Button size="sm" className="bg-gray-900 hover:bg-gray-800 text-white">
                          Connect
                        </Button>
                      )}
                    </div>
                    {/* LinkedIn token health indicator */}
                    {tokenHealth && isConnected && (
                      <div className="flex items-center gap-2 mt-3 pt-3 border-t border-gray-100">
                        <Badge className={`text-[10px] rounded-full ${tokenHealth.color}`}>
                          {tokenHealth.label}
                        </Badge>
                        {acct.expiresAt && (
                          <span className="text-[10px] text-gray-400">
                            Expires {new Date(acct.expiresAt).toLocaleDateString()}
                          </span>
                        )}
                        <Button
                          variant="ghost"
                          size="sm"
                          className="ml-auto text-xs text-blue-600 hover:text-blue-700 h-7 px-2"
                          disabled={refreshingToken === acct.id}
                          onClick={async () => {
                            setRefreshingToken(acct.id);
                            try {
                              const res = await fetch(`/api/v1/social-accounts/${acct.id}/refresh`, { method: "POST" });
                              if (res.ok) {
                                const updated = await res.json();
                                setConnectedAccounts((prev) =>
                                  prev.map((a) => a.id === acct.id ? { ...a, expiresAt: updated.expiresAt } : a)
                                );
                                setSuccessMessage("LinkedIn token refreshed successfully!");
                              }
                            } catch {
                              // ignore
                            } finally {
                              setRefreshingToken(null);
                            }
                          }}
                        >
                          <RefreshCw className={`h-3 w-3 mr-1 ${refreshingToken === acct.id ? "animate-spin" : ""}`} />
                          {refreshingToken === acct.id ? "Refreshing..." : "Refresh Token"}
                        </Button>
                      </div>
                    )}
                  </CardContent>
                </Card>
              );
            })}
          </div>
          {accountsLoading && (
            <p className="text-sm text-gray-400 text-center">Loading accounts...</p>
          )}
        </TabsContent>

        {/* Team */}
        <TabsContent value="team" className="space-y-4 mt-4">
          <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
            <CardHeader>
              <CardTitle className="text-base font-semibold text-gray-900">Invite Team Member</CardTitle>
              <CardDescription className="text-gray-500">Invite a not-yet-registered @{ALLOWED_EMAIL_DOMAIN} user and pre-assign their role</CardDescription>
            </CardHeader>
            <CardContent>
              {inviteError && (
                <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                  {inviteError}
                </div>
              )}

              <div className="flex gap-2">
                <Input
                  value={inviteEmail}
                  onChange={(e) => setInviteEmail(e.target.value)}
                  placeholder={`name@${ALLOWED_EMAIL_DOMAIN}`}
                  type="email"
                />
                <Select value={inviteRole} onValueChange={(value) => setInviteRole(value as UserRole)}>
                  <SelectTrigger className="h-10 w-[120px] border-gray-200">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="ADMIN">Admin</SelectItem>
                    <SelectItem value="EDITOR">Editor</SelectItem>
                    <SelectItem value="VIEWER">Viewer</SelectItem>
                  </SelectContent>
                </Select>
                <Button
                  disabled={!inviteEmail.trim().toLowerCase().endsWith(`@${ALLOWED_EMAIL_DOMAIN}`) || inviteSaving}
                  onClick={() => void handleInvite()}
                  className="bg-gray-900 hover:bg-gray-800 text-white"
                >
                  <Plus className="h-4 w-4 mr-1" /> {inviteSaving ? "Inviting..." : "Invite"}
                </Button>
              </div>
            </CardContent>
          </Card>

          <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
            <CardHeader>
              <CardTitle className="text-base font-semibold text-gray-900">Pending Invites</CardTitle>
              <CardDescription className="text-gray-500">These roles activate automatically when the invited email signs in for the first time</CardDescription>
            </CardHeader>
            <CardContent>
              {invitesLoading ? (
                <p className="text-sm text-gray-400">Loading invites...</p>
              ) : pendingInvites.length === 0 ? (
                <p className="text-sm text-gray-400">No pending invites.</p>
              ) : (
                <div className="space-y-3">
                  {pendingInvites.map((invite) => (
                    <div key={invite.id} className="flex items-center gap-3">
                      <div className="flex-1">
                        <p className="text-sm font-medium text-gray-900">{invite.email}</p>
                        <p className="text-xs text-gray-500">
                          Invited by {invite.invitedBy.name || invite.invitedBy.email} on {new Date(invite.createdAt).toLocaleDateString()}
                        </p>
                      </div>
                      <Badge className={`text-[10px] rounded-full ${ROLE_COLORS[invite.role]}`}>
                        {invite.role}
                      </Badge>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-red-600 hover:text-red-700"
                        disabled={revokingInviteId === invite.id}
                        onClick={() => void handleRevokeInvite(invite.id)}
                      >
                        <Trash2 className="h-3.5 w-3.5 mr-1" />
                        {revokingInviteId === invite.id ? "Revoking..." : "Revoke"}
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </CardContent>
          </Card>

          <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
            <CardHeader>
              <CardTitle className="text-base font-semibold text-gray-900">Team Members</CardTitle>
            </CardHeader>
            <CardContent>
              {teamError && (
                <div className="mb-4 rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
                  {teamError}
                </div>
              )}

              {teamLoading ? (
                <p className="text-sm text-gray-400">Loading team members...</p>
              ) : (
                <div className="space-y-3">
                  {teamMembers.map((member) => (
                    <div key={member.id} className="flex items-center gap-3">
                      <div className="flex-1">
                        <p className="text-sm font-medium text-gray-900">{member.name || member.email.split("@")[0]}</p>
                        <p className="text-xs text-gray-500">{member.email}</p>
                      </div>
                      <Select
                        value={member.role}
                        disabled={savingMemberId === member.id}
                        onValueChange={(value) => void handleRoleChange(member.id, value as UserRole)}
                      >
                        <SelectTrigger className="h-8 w-[110px] border-gray-200 text-xs text-gray-700">
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="ADMIN">Admin</SelectItem>
                          <SelectItem value="EDITOR">Editor</SelectItem>
                          <SelectItem value="VIEWER">Viewer</SelectItem>
                        </SelectContent>
                      </Select>
                      <Badge className={`text-[10px] rounded-full ${ROLE_COLORS[member.role]}`}>
                        {savingMemberId === member.id ? "Saving..." : member.role}
                      </Badge>
                    </div>
                  ))}
                  {teamMembers.length === 0 && (
                    <p className="text-sm text-gray-400">No team members found.</p>
                  )}
                </div>
              )}
            </CardContent>
          </Card>
        </TabsContent>

        {/* API Keys */}
        <TabsContent value="api-keys" className="space-y-4 mt-4">
          <Dialog>
            <DialogTrigger
              render={<Button className="bg-gray-900 hover:bg-gray-800 text-white rounded-lg px-4 py-2 text-sm font-medium"><Plus className="h-4 w-4 mr-1" /> Create API Key</Button>}
            />
            <DialogContent>
              <DialogHeader>
                <DialogTitle className="text-gray-900">Create API Key</DialogTitle>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label className="text-xs">Key Name</Label>
                  <Input
                    value={newKeyName}
                    onChange={(e) => setNewKeyName(e.target.value)}
                    placeholder="e.g. Production"
                  />
                </div>
                {createdKey ? (
                  <div className="space-y-2">
                    <p className="text-xs text-gray-500">
                      Copy this key now. You won&apos;t be able to see it again.
                    </p>
                    <div className="flex items-center gap-2">
                      <code className="flex-1 rounded-lg bg-gray-100 px-3 py-2 text-xs font-mono text-gray-900">
                        {showKey ? createdKey : "•".repeat(40)}
                      </code>
                      <Button variant="ghost" size="icon" onClick={() => setShowKey(!showKey)}>
                        {showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                      </Button>
                      <Button variant="ghost" size="icon" onClick={() => navigator.clipboard.writeText(createdKey)}>
                        <Copy className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                ) : (
                  <Button onClick={handleCreateKey} disabled={!newKeyName.trim()} className="bg-gray-900 hover:bg-gray-800 text-white">
                    Generate Key
                  </Button>
                )}
              </div>
            </DialogContent>
          </Dialog>

          <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
            <CardContent className="p-0 overflow-x-auto">
              <table className="w-full text-sm min-w-[500px]">
                <thead>
                  <tr className="border-b text-left">
                    <th className="p-3 font-medium text-gray-500">Name</th>
                    <th className="p-3 font-medium text-gray-500">Scopes</th>
                    <th className="p-3 font-medium text-gray-500">Last Used</th>
                    <th className="p-3 font-medium text-gray-500">Created</th>
                    <th className="p-3"></th>
                  </tr>
                </thead>
                <tbody>
                  {API_KEYS.map((key) => (
                    <tr key={key.id} className="border-b last:border-0">
                      <td className="p-3 font-medium text-gray-900">{key.name}</td>
                      <td className="p-3">
                        <div className="flex gap-1">
                          {key.scopes.map((s) => (
                            <Badge key={s} variant="outline" className="text-[10px] border-gray-200">{s}</Badge>
                          ))}
                        </div>
                      </td>
                      <td className="p-3 text-gray-500">{key.lastUsed}</td>
                      <td className="p-3 text-gray-500">{key.createdAt}</td>
                      <td className="p-3">
                        <Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700">
                          <Trash2 className="h-3.5 w-3.5 mr-1" /> Revoke
                        </Button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Notifications */}
        <TabsContent value="notifications" className="space-y-4 mt-4">
          <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
            <CardHeader>
              <CardTitle className="text-base font-semibold text-gray-900">Notification Preferences</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {[
                { label: "New engagement items", description: "Get notified when someone comments, mentions, or DMs" },
                { label: "Post published", description: "Notification when a scheduled post goes live" },
                { label: "Post failed", description: "Alert when a post fails to publish" },
                { label: "Weekly analytics digest", description: "Summary of your social media performance" },
                { label: "New team member", description: "When someone joins the workspace" },
              ].map((item) => (
                <div key={item.label} className="flex items-center justify-between">
                  <div>
                    <p className="text-sm font-medium text-gray-900">{item.label}</p>
                    <p className="text-xs text-gray-500">{item.description}</p>
                  </div>
                  <label className="relative inline-flex cursor-pointer items-center">
                    <input type="checkbox" defaultChecked className="peer sr-only" />
                    <div className="h-6 w-11 sm:h-5 sm:w-9 rounded-full bg-gray-200 peer-checked:bg-gray-900 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 sm:after:h-4 sm:after:w-4 after:rounded-full after:bg-white after:transition-all peer-checked:after:translate-x-full" />
                  </label>
                </div>
              ))}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Tracks */}
        <TabsContent value="tracks" className="space-y-4 mt-4">
          <Card className="bg-white border border-gray-200 rounded-xl shadow-none">
            <CardHeader>
              <CardTitle className="text-base font-semibold text-gray-900">Content Tracks</CardTitle>
              <CardDescription className="text-gray-500">Configure slot caps, approval requirements, and active status for each track</CardDescription>
            </CardHeader>
            <CardContent className="p-0 overflow-x-auto">
              <table className="w-full text-sm min-w-[600px]">
                <thead>
                  <tr className="border-b text-left">
                    <th className="p-3 font-medium text-gray-500">Track</th>
                    <th className="p-3 font-medium text-gray-500">Weekly Slot Cap</th>
                    <th className="p-3 font-medium text-gray-500">Stagger Delay (min)</th>
                    <th className="p-3 font-medium text-gray-500">Requires Approval</th>
                    <th className="p-3 font-medium text-gray-500">Active</th>
                    <th className="p-3"></th>
                  </tr>
                </thead>
                <tbody>
                  {tracks.map((t) => {
                    const edits = trackEdits[t.track] ?? {};
                    const currentCap = edits.weeklySlotCap ?? t.weeklySlotCap;
                    const currentStagger = edits.staggerDelayMinutes ?? t.staggerDelayMinutes ?? 15;
                    const currentApproval = edits.requiresApproval ?? t.requiresApproval;
                    const currentActive = edits.isActive ?? t.isActive;
                    const hasEdits = Object.keys(edits).length > 0;

                    return (
                      <tr key={t.track} className="border-b last:border-0">
                        <td className="p-3 font-medium text-gray-900">
                          {TRACK_LABELS[t.track] ?? t.track}
                        </td>
                        <td className="p-3">
                          <Input
                            type="number"
                            min={0}
                            value={currentCap}
                            onChange={(e) =>
                              setTrackEdits((prev) => ({
                                ...prev,
                                [t.track]: { ...prev[t.track], weeklySlotCap: parseInt(e.target.value) || 0 },
                              }))
                            }
                            className="w-full sm:w-20 h-8 text-sm"
                          />
                        </td>
                        <td className="p-3">
                          <Input
                            type="number"
                            min={1}
                            max={120}
                            value={currentStagger}
                            onChange={(e) =>
                              setTrackEdits((prev) => ({
                                ...prev,
                                [t.track]: { ...prev[t.track], staggerDelayMinutes: parseInt(e.target.value) || 15 },
                              }))
                            }
                            className="w-full sm:w-20 h-8 text-sm"
                            data-testid={`stagger-delay-${t.track}`}
                          />
                        </td>
                        <td className="p-3">
                          <label className="relative inline-flex cursor-pointer items-center">
                            <input
                              type="checkbox"
                              checked={currentApproval}
                              onChange={(e) =>
                                setTrackEdits((prev) => ({
                                  ...prev,
                                  [t.track]: { ...prev[t.track], requiresApproval: e.target.checked },
                                }))
                              }
                              className="peer sr-only"
                            />
                            <div className="h-6 w-11 sm:h-5 sm:w-9 rounded-full bg-gray-200 peer-checked:bg-gray-900 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 sm:after:h-4 sm:after:w-4 after:rounded-full after:bg-white after:transition-all peer-checked:after:translate-x-full" />
                          </label>
                        </td>
                        <td className="p-3">
                          <label className="relative inline-flex cursor-pointer items-center">
                            <input
                              type="checkbox"
                              checked={currentActive}
                              onChange={(e) =>
                                setTrackEdits((prev) => ({
                                  ...prev,
                                  [t.track]: { ...prev[t.track], isActive: e.target.checked },
                                }))
                              }
                              className="peer sr-only"
                            />
                            <div className="h-6 w-11 sm:h-5 sm:w-9 rounded-full bg-gray-200 peer-checked:bg-gray-900 after:absolute after:left-[2px] after:top-[2px] after:h-5 after:w-5 sm:after:h-4 sm:after:w-4 after:rounded-full after:bg-white after:transition-all peer-checked:after:translate-x-full" />
                          </label>
                        </td>
                        <td className="p-3">
                          <Button
                            size="sm"
                            disabled={!hasEdits || trackSaving === t.track}
                            onClick={() => handleTrackSave(t.track)}
                            className="bg-gray-900 hover:bg-gray-800 text-white disabled:opacity-50"
                          >
                            {trackSaving === t.track ? "Saving..." : "Save"}
                          </Button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
              {tracks.length === 0 && (
                <p className="text-sm text-gray-400 text-center py-6">No track configurations found</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
