"use client";

import { useMemo, useState } from "react";
import { useSearchParams } from "next/navigation";
import {
  AlertTriangle,
  Building2,
  Copy,
  CreditCard,
  Gauge,
  LockKeyhole,
  Link2,
  Mail,
  Pencil,
  Plus,
  Shield,
  Trash2,
  Users2,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { EmptyState } from "@/components/ui/empty-state";
import { Input } from "@/components/ui/input";
import { Modal } from "@/components/ui/modal";
import { Badge } from "@/components/ui/badge";
import { Select } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { useOrganizations } from "@/hooks/use-organizations";
import { useTeams } from "@/hooks/use-teams";
import {
  BILLING_CYCLE_OPTIONS,
  BILLING_PLAN_OPTIONS,
  SUBSCRIPTION_STATUS_OPTIONS,
  calculateSeatUsage,
  formatCurrency,
  toDateTimeLocalValue,
} from "@/lib/organization-billing";
import { AUTH_METHOD_OPTIONS, parseDomainList } from "@/lib/organization-auth";
import type {
  AuthMethod,
  BillingCycle,
  BillingPlan,
  OrganizationRole,
  OrganizationWithContext,
  SubscriptionStatus,
} from "@/types";

const MEMBER_ROLES: Array<{ value: Exclude<OrganizationRole, "owner">; label: string }> = [
  { value: "admin", label: "Admin" },
  { value: "member", label: "Member" },
];

interface BillingFormState {
  organizationId: string;
  billing_email: string;
  billing_name: string;
  plan: BillingPlan;
  billing_cycle: BillingCycle;
  subscription_status: SubscriptionStatus;
  included_seats: number;
  purchased_seats: number;
  monthly_price_cents: number;
  trial_ends_at: string;
  renews_at: string;
  cancel_at: string;
}

interface SecurityFormState {
  organizationId: string;
  allowed_auth_methods: AuthMethod[];
  allowed_email_domains: string;
  auto_join_domains: string;
  invite_only: boolean;
  require_domain_match: boolean;
  enforce_sso: boolean;
}

function roleLabel(role: OrganizationRole) {
  if (role === "owner") return "Owner";
  if (role === "admin") return "Admin";
  return "Member";
}

function getPlanDefaults(plan: BillingPlan) {
  return (
    BILLING_PLAN_OPTIONS.find((option) => option.value === plan) || BILLING_PLAN_OPTIONS[0]
  );
}

export default function OrganizationsPage() {
  const searchParams = useSearchParams();
  const {
    organizations,
    loading,
    userId,
    incomingInvitations,
    createOrganization,
    updateOrganization,
    addOrganizationMember,
    updateOrganizationMember,
    updateOrganizationBilling,
    updateOrganizationAuthPolicy,
    removeOrganizationMember,
    linkTeam,
    unlinkTeam,
    inviteOrganizationMember,
    acceptOrganizationInvitation,
    declineOrganizationInvitation,
    revokeOrganizationInvitation,
    requestOrganizationJoin,
    updateOrganizationJoinRequest,
  } = useOrganizations();
  const { teams } = useTeams();

  const [modalOpen, setModalOpen] = useState(false);
  const [editingOrganization, setEditingOrganization] = useState<OrganizationWithContext | null>(null);
  const [billingModalOpen, setBillingModalOpen] = useState(false);
  const [billingForm, setBillingForm] = useState<BillingFormState | null>(null);
  const [securityModalOpen, setSecurityModalOpen] = useState(false);
  const [securityForm, setSecurityForm] = useState<SecurityFormState | null>(null);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [billingSubmitting, setBillingSubmitting] = useState(false);
  const [securitySubmitting, setSecuritySubmitting] = useState(false);
  const [feedback, setFeedback] = useState<string | null>(null);
  const [selectedTeamByOrg, setSelectedTeamByOrg] = useState<Record<string, string>>({});
  const [selectedProfileByOrg, setSelectedProfileByOrg] = useState<Record<string, string>>({});
  const [selectedRoleByOrg, setSelectedRoleByOrg] = useState<
    Record<string, Exclude<OrganizationRole, "owner">>
  >({});
  const [inviteEmailByOrg, setInviteEmailByOrg] = useState<Record<string, string>>({});
  const [inviteRoleByOrg, setInviteRoleByOrg] = useState<
    Record<string, Exclude<OrganizationRole, "owner">>
  >({});
  const [inviteMessageByOrg, setInviteMessageByOrg] = useState<Record<string, string>>({});
  const [inviteSubmittingOrgId, setInviteSubmittingOrgId] = useState<string | null>(null);
  const [inviteSuccessByOrg, setInviteSuccessByOrg] = useState<
    Record<string, { email: string; inviteUrl: string; delivery: "email_sent" | "stored_only" }>
  >({});
  const [joinRequestSlug, setJoinRequestSlug] = useState("");
  const [joinRequestMessage, setJoinRequestMessage] = useState("");
  const [requestingJoin, setRequestingJoin] = useState(false);

  const accessibleTeams = useMemo(() => teams, [teams]);
  const appBaseUrl = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/$/, "") || "";
  const incomingInvitation = useMemo(() => {
    const token = searchParams.get("invite");
    if (!token) return null;
    return incomingInvitations.find((invitation) => invitation.token === token) || null;
  }, [incomingInvitations, searchParams]);

  async function copyText(value: string) {
    try {
      await navigator.clipboard.writeText(value);
      setFeedback("Copied to clipboard.");
    } catch {
      setFeedback("Could not copy to clipboard.");
    }
  }

  function openCreateModal() {
    setEditingOrganization(null);
    setName("");
    setDescription("");
    setModalOpen(true);
  }

  function openEditModal(organization: OrganizationWithContext) {
    setEditingOrganization(organization);
    setName(organization.name);
    setDescription(organization.description || "");
    setModalOpen(true);
  }

  function openBillingModal(organization: OrganizationWithContext) {
    const defaults = getPlanDefaults(organization.billing?.plan || "starter");
    setBillingForm({
      organizationId: organization.id,
      billing_email: organization.billing?.billing_email || "",
      billing_name: organization.billing?.billing_name || organization.name,
      plan: organization.billing?.plan || defaults.value,
      billing_cycle: organization.billing?.billing_cycle || "monthly",
      subscription_status: organization.billing?.subscription_status || "trialing",
      included_seats: organization.billing?.included_seats ?? defaults.includedSeats,
      purchased_seats: organization.billing?.purchased_seats ?? 0,
      monthly_price_cents: organization.billing?.monthly_price_cents ?? defaults.monthlyPriceCents,
      trial_ends_at: toDateTimeLocalValue(organization.billing?.trial_ends_at || null),
      renews_at: toDateTimeLocalValue(organization.billing?.renews_at || null),
      cancel_at: toDateTimeLocalValue(organization.billing?.cancel_at || null),
    });
    setBillingModalOpen(true);
  }

  function openSecurityModal(organization: OrganizationWithContext) {
    setSecurityForm({
      organizationId: organization.id,
      allowed_auth_methods:
        organization.authPolicy?.allowed_auth_methods || AUTH_METHOD_OPTIONS.map((option) => option.value),
      allowed_email_domains: (organization.authPolicy?.allowed_email_domains || []).join(", "),
      auto_join_domains: (organization.authPolicy?.auto_join_domains || []).join(", "),
      invite_only: organization.authPolicy?.invite_only || false,
      require_domain_match: organization.authPolicy?.require_domain_match || false,
      enforce_sso: organization.authPolicy?.enforce_sso || false,
    });
    setSecurityModalOpen(true);
  }

  function handleBillingPlanChange(plan: BillingPlan) {
    const defaults = getPlanDefaults(plan);
    setBillingForm((prev) =>
      prev
        ? {
            ...prev,
            plan,
            included_seats: defaults.includedSeats,
            monthly_price_cents: defaults.monthlyPriceCents,
          }
        : prev
    );
  }

  async function handleSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!name.trim() || submitting) return;

    setSubmitting(true);
    try {
      if (editingOrganization) {
        await updateOrganization(editingOrganization.id, {
          name,
          description,
        });
      } else {
        await createOrganization({
          name,
          description,
        });
      }
      setModalOpen(false);
    } finally {
      setSubmitting(false);
    }
  }

  async function handleBillingSubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!billingForm || billingSubmitting) return;

    setBillingSubmitting(true);
    try {
      await updateOrganizationBilling(billingForm.organizationId, {
        billing_email: billingForm.billing_email,
        billing_name: billingForm.billing_name,
        plan: billingForm.plan,
        billing_cycle: billingForm.billing_cycle,
        subscription_status: billingForm.subscription_status,
        included_seats: billingForm.included_seats,
        purchased_seats: billingForm.purchased_seats,
        monthly_price_cents: billingForm.monthly_price_cents,
        trial_ends_at: billingForm.trial_ends_at
          ? new Date(billingForm.trial_ends_at).toISOString()
          : null,
        renews_at: billingForm.renews_at
          ? new Date(billingForm.renews_at).toISOString()
          : null,
        cancel_at: billingForm.cancel_at
          ? new Date(billingForm.cancel_at).toISOString()
          : null,
      });
      setBillingModalOpen(false);
      setBillingForm(null);
    } finally {
      setBillingSubmitting(false);
    }
  }

  function toggleSecurityMethod(method: AuthMethod) {
    setSecurityForm((prev) => {
      if (!prev) return prev;
      const hasMethod = prev.allowed_auth_methods.includes(method);
      const nextMethods = hasMethod
        ? prev.allowed_auth_methods.filter((item) => item !== method)
        : [...prev.allowed_auth_methods, method];

      return {
        ...prev,
        allowed_auth_methods: nextMethods.length > 0 ? nextMethods : prev.allowed_auth_methods,
      };
    });
  }

  async function handleSecuritySubmit(event: React.FormEvent) {
    event.preventDefault();
    if (!securityForm || securitySubmitting) return;

    setSecuritySubmitting(true);
    try {
      await updateOrganizationAuthPolicy(securityForm.organizationId, {
        allowed_auth_methods: securityForm.allowed_auth_methods,
        allowed_email_domains: parseDomainList(securityForm.allowed_email_domains),
        auto_join_domains: parseDomainList(securityForm.auto_join_domains),
        invite_only: securityForm.invite_only,
        require_domain_match: securityForm.require_domain_match,
        enforce_sso: securityForm.enforce_sso,
      });
      setSecurityModalOpen(false);
      setSecurityForm(null);
    } finally {
      setSecuritySubmitting(false);
    }
  }

  async function handleInviteOrganization(organizationId: string) {
    const email = inviteEmailByOrg[organizationId]?.trim() || "";
    const role = inviteRoleByOrg[organizationId] || "member";
    const message = inviteMessageByOrg[organizationId] || "";
    if (!email || inviteSubmittingOrgId === organizationId) return;

    setInviteSubmittingOrgId(organizationId);
    setFeedback(null);

    try {
      const result = await inviteOrganizationMember(organizationId, {
        email,
        role,
        message,
      });
      setInviteSuccessByOrg((prev) => ({
        ...prev,
        [organizationId]: {
          email,
          inviteUrl: result.inviteUrl,
          delivery: result.delivery,
        },
      }));
      setInviteEmailByOrg((prev) => ({ ...prev, [organizationId]: "" }));
      setInviteMessageByOrg((prev) => ({ ...prev, [organizationId]: "" }));
      setFeedback(
        result.delivery === "email_sent"
          ? `Invitation sent to ${email}.`
          : `Invitation created for ${email}. Copy the link below to share it manually.`
      );
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Invitation could not be sent.");
    } finally {
      setInviteSubmittingOrgId(null);
    }
  }

  async function handleCreateJoinRequest() {
    if (!joinRequestSlug.trim() || requestingJoin) return;

    setRequestingJoin(true);
    setFeedback(null);
    try {
      const result = await requestOrganizationJoin({
        slug: joinRequestSlug,
        message: joinRequestMessage,
      });
      setJoinRequestSlug("");
      setJoinRequestMessage("");
      setFeedback(`Join request sent to ${result.organization.name}.`);
    } catch (error) {
      setFeedback(error instanceof Error ? error.message : "Join request could not be created.");
    } finally {
      setRequestingJoin(false);
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-3">
            <Building2 className="h-5 w-5 text-muted-foreground" />
            <h1 className="text-2xl font-bold tracking-tight">Organizations</h1>
          </div>
          <p className="text-sm text-muted-foreground">
            Group multiple teams under one operating layer, control seats, and keep billing readiness visible across the org.
          </p>
        </div>
        <Button onClick={openCreateModal}>
          <Plus className="h-4 w-4" />
          New organization
        </Button>
      </div>

      {feedback && (
        <div className="rounded-xl border border-border/60 bg-muted/40 px-4 py-3 text-sm">
          {feedback}
        </div>
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-4 w-4 text-primary" />
            Request organization access
          </CardTitle>
          <CardDescription>
            If you know an organization slug, you can request access without waiting for an invite.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="grid gap-3 md:grid-cols-2">
            <Input
              value={joinRequestSlug}
              onChange={(event) => setJoinRequestSlug(event.target.value)}
              placeholder="organization-slug"
            />
            <Button onClick={() => void handleCreateJoinRequest()} disabled={!joinRequestSlug.trim() || requestingJoin}>
              {requestingJoin ? "Sending..." : "Request access"}
            </Button>
          </div>
          <Textarea
            value={joinRequestMessage}
            onChange={(event) => setJoinRequestMessage(event.target.value)}
            placeholder="Optional message to explain why you want to join..."
            className="min-h-[92px]"
          />
        </CardContent>
      </Card>

      {incomingInvitation && (
        <Card className="border-primary/30 bg-primary/5">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Mail className="h-4 w-4 text-primary" />
              Organization invitation
            </CardTitle>
            <CardDescription>
              You were invited to join{" "}
              <span className="font-medium">
                {organizations.find((organization) => organization.id === incomingInvitation.organization_id)?.name ||
                  "this organization"}
              </span>{" "}
              as <span className="font-medium">{roleLabel(incomingInvitation.role)}</span>.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {incomingInvitation.message ? (
              <div className="rounded-xl border border-border/60 bg-background/80 p-3 text-sm">
                {incomingInvitation.message}
              </div>
            ) : null}
            <div className="flex flex-wrap gap-2">
              <Button onClick={() => void acceptOrganizationInvitation(incomingInvitation.id)}>
                Accept invitation
              </Button>
              <Button
                variant="outline"
                onClick={() => void declineOrganizationInvitation(incomingInvitation.id)}
              >
                Decline
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {loading ? (
        <div className="grid gap-4 xl:grid-cols-2">
          {Array.from({ length: 2 }).map((_, index) => (
            <Card key={index}>
              <CardContent className="h-64 animate-pulse rounded-xl bg-muted/40" />
            </Card>
          ))}
        </div>
      ) : organizations.length === 0 ? (
        <EmptyState
          icon={<Building2 className="h-10 w-10" />}
          title="No organizations yet"
          description="Create an organization when multiple teams should roll up into one shared admin layer."
          action={
            <Button onClick={openCreateModal}>
              <Plus className="h-4 w-4" />
              Create organization
            </Button>
          }
        />
      ) : (
        <div className="grid gap-6 xl:grid-cols-2">
          {organizations.map((organization) => {
            const linkedTeams = organization.teams || [];
            const members = organization.members || [];
            const assignableProfiles = organization.assignableProfiles || [];
            const availableTeams = accessibleTeams.filter(
              (team) => !linkedTeams.some((linkedTeam) => linkedTeam.team_id === team.id)
            );
            const currentRole =
              members.find((member) => member.user_id === userId)?.role || "member";
            const canManage = currentRole === "owner" || currentRole === "admin";
            const selectedTeamId = selectedTeamByOrg[organization.id] || "";
            const selectedProfileId = selectedProfileByOrg[organization.id] || "";
            const selectedRole = selectedRoleByOrg[organization.id] || "member";
            const inviteEmail = inviteEmailByOrg[organization.id] || "";
            const inviteRole = inviteRoleByOrg[organization.id] || "member";
            const inviteMessage = inviteMessageByOrg[organization.id] || "";
            const inviteSuccess = inviteSuccessByOrg[organization.id] || null;
            const pendingInvitations = organization.invitations.filter(
              (invitation) => invitation.status === "pending"
            );
            const pendingJoinRequests = organization.joinRequests.filter(
              (request) => request.status === "pending"
            );
            const seatUsage = calculateSeatUsage(members, organization.billing);
            const isOverLimit = seatUsage.overage > 0;
            const planLabel =
              BILLING_PLAN_OPTIONS.find((option) => option.value === organization.billing?.plan)
                ?.label || "Starter";

            return (
              <Card key={organization.id}>
                <CardHeader>
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        <Building2 className="h-4 w-4 text-primary" />
                        {organization.name}
                      </CardTitle>
                      <CardDescription className="mt-1">
                        {organization.description || "No description yet."}
                      </CardDescription>
                    </div>
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">{linkedTeams.length} teams</Badge>
                      <Badge variant="outline">{members.length} members</Badge>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => openEditModal(organization)}
                        disabled={!canManage}
                      >
                        <Pencil className="h-4 w-4" />
                        Edit
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      <Link2 className="h-4 w-4 text-primary" />
                      <p className="text-sm font-medium">Linked teams</p>
                    </div>
                    {linkedTeams.length === 0 ? (
                      <div className="rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground">
                        No teams linked yet.
                      </div>
                    ) : (
                      linkedTeams.map((linkedTeam) => (
                        <div
                          key={linkedTeam.team_id}
                          className="flex items-center justify-between gap-3 rounded-xl border border-border/60 bg-background/60 p-3"
                        >
                          <div>
                            <p className="font-medium">{linkedTeam.team?.name || "Linked team"}</p>
                            <p className="text-sm text-muted-foreground">
                              {linkedTeam.team?.description || "Shared team workspace"}
                            </p>
                          </div>
                          {canManage && (
                            <Button
                              size="sm"
                              variant="ghost"
                              onClick={() => void unlinkTeam(organization.id, linkedTeam.team_id)}
                            >
                              <Trash2 className="h-4 w-4 text-destructive" />
                            </Button>
                          )}
                        </div>
                      ))
                    )}
                    {canManage && availableTeams.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        <Select
                          value={selectedTeamId}
                          onChange={(event) =>
                            setSelectedTeamByOrg((prev) => ({
                              ...prev,
                              [organization.id]: event.target.value,
                            }))
                          }
                        >
                          <option value="">Link a team...</option>
                          {availableTeams.map((team) => (
                            <option key={team.id} value={team.id}>
                              {team.name}
                            </option>
                          ))}
                        </Select>
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => void linkTeam(organization.id, selectedTeamId)}
                          disabled={!selectedTeamId}
                        >
                          Link team
                        </Button>
                      </div>
                    )}
                  </div>

                  <div className="space-y-4 rounded-2xl border border-border/60 bg-muted/20 p-4">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          <CreditCard className="h-4 w-4 text-primary" />
                          <p className="text-sm font-medium">Billing & seats</p>
                          {isOverLimit ? (
                            <Badge variant="outline" className="text-destructive">
                              Over limit
                            </Badge>
                          ) : null}
                        </div>
                        <p className="text-sm text-muted-foreground">
                          {planLabel} · {organization.billing?.subscription_status || "trialing"} ·{" "}
                          {formatCurrency(
                            organization.billing?.monthly_price_cents || getPlanDefaults("starter").monthlyPriceCents,
                            organization.billing?.billing_cycle || "monthly"
                          )}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          Billing contact: {organization.billing?.billing_email || "Not set"}
                        </p>
                      </div>
                      {canManage ? (
                        <Button size="sm" variant="outline" onClick={() => openBillingModal(organization)}>
                          <Gauge className="h-4 w-4" />
                          Manage billing
                        </Button>
                      ) : null}
                    </div>

                    <div className="space-y-2">
                      <div className="flex items-center justify-between text-xs text-muted-foreground">
                        <span>
                          {seatUsage.activeBillableSeats} of {seatUsage.seatCapacity} seats in use
                        </span>
                        <span>{seatUsage.availableSeats} available</span>
                      </div>
                      <div className="h-2 overflow-hidden rounded-full bg-border/60">
                        <div
                          className={`h-full rounded-full transition-all ${
                            isOverLimit ? "bg-destructive" : "bg-primary"
                          }`}
                          style={{
                            width: `${Math.max(seatUsage.usageRatio * 100, seatUsage.activeBillableSeats > 0 ? 8 : 0)}%`,
                          }}
                        />
                      </div>
                    </div>

                    <div className="grid gap-3 sm:grid-cols-4">
                      <div className="rounded-xl border border-border/60 bg-background/70 p-3">
                        <p className="text-xs text-muted-foreground">Billable seats</p>
                        <p className="mt-1 text-lg font-semibold">{seatUsage.activeBillableSeats}</p>
                      </div>
                      <div className="rounded-xl border border-border/60 bg-background/70 p-3">
                        <p className="text-xs text-muted-foreground">Seat capacity</p>
                        <p className="mt-1 text-lg font-semibold">{seatUsage.seatCapacity}</p>
                      </div>
                      <div className="rounded-xl border border-border/60 bg-background/70 p-3">
                        <p className="text-xs text-muted-foreground">Suspended</p>
                        <p className="mt-1 text-lg font-semibold">{seatUsage.suspendedSeats}</p>
                      </div>
                      <div className="rounded-xl border border-border/60 bg-background/70 p-3">
                        <p className="text-xs text-muted-foreground">Excluded</p>
                        <p className="mt-1 text-lg font-semibold">{seatUsage.excludedSeats}</p>
                      </div>
                    </div>

                    {isOverLimit ? (
                      <div className="flex items-start gap-2 rounded-xl border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
                        <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
                        <div>
                          This organization is using {seatUsage.overage} more seat
                          {seatUsage.overage === 1 ? "" : "s"} than currently available. Increase purchased seats or exclude inactive members from billing.
                        </div>
                      </div>
                    ) : null}
                  </div>

                  <div className="space-y-4 rounded-2xl border border-border/60 bg-muted/20 p-4">
                    <div className="flex flex-wrap items-start justify-between gap-3">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          <LockKeyhole className="h-4 w-4 text-primary" />
                          <p className="text-sm font-medium">Auth & domain policy</p>
                        </div>
                        <p className="text-sm text-muted-foreground">
                          {organization.authPolicy?.enforce_sso ? "SSO enforced" : "Flexible sign-in"} ·{" "}
                          {organization.authPolicy?.require_domain_match ? "Domain match required" : "Domain match optional"} ·{" "}
                          {organization.authPolicy?.invite_only ? "Invite only" : "Open membership"}
                        </p>
                      </div>
                      {canManage ? (
                        <Button size="sm" variant="outline" onClick={() => openSecurityModal(organization)}>
                          <Shield className="h-4 w-4" />
                          Manage security
                        </Button>
                      ) : null}
                    </div>

                    <div className="space-y-2">
                      <p className="text-xs text-muted-foreground">Allowed auth methods</p>
                      <div className="flex flex-wrap gap-2">
                        {(organization.authPolicy?.allowed_auth_methods ||
                          AUTH_METHOD_OPTIONS.map((option) => option.value)).map((method) => (
                          <Badge key={method} variant="outline">
                            {AUTH_METHOD_OPTIONS.find((option) => option.value === method)?.label || method}
                          </Badge>
                        ))}
                      </div>
                    </div>

                    <div className="grid gap-3 sm:grid-cols-2">
                      <div className="rounded-xl border border-border/60 bg-background/70 p-3">
                        <p className="text-xs text-muted-foreground">Allowed domains</p>
                        <p className="mt-1 text-sm">
                          {(organization.authPolicy?.allowed_email_domains || []).length > 0
                            ? organization.authPolicy?.allowed_email_domains.join(", ")
                            : "Any domain"}
                        </p>
                      </div>
                      <div className="rounded-xl border border-border/60 bg-background/70 p-3">
                        <p className="text-xs text-muted-foreground">Auto-join domains</p>
                        <p className="mt-1 text-sm">
                          {(organization.authPolicy?.auto_join_domains || []).length > 0
                            ? organization.authPolicy?.auto_join_domains.join(", ")
                            : "No auto-join"}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className="space-y-3">
                    <div className="flex items-center gap-2">
                      <Users2 className="h-4 w-4 text-primary" />
                      <p className="text-sm font-medium">Organization members</p>
                    </div>
                    {members.map((member) => {
                      const isOwner = member.role === "owner";
                      return (
                        <div
                          key={member.user_id}
                          className="rounded-xl border border-border/60 bg-background/60 p-3"
                        >
                          <div className="flex flex-wrap items-center justify-between gap-3">
                            <div>
                              <p className="font-medium">
                                {member.profile?.full_name || member.profile?.email || "Member"}
                              </p>
                              <p className="text-sm text-muted-foreground">
                                {member.profile?.email || member.title || "No metadata"}
                              </p>
                            </div>
                            <div className="flex items-center gap-2">
                              {canManage && !isOwner ? (
                                <Select
                                  value={member.role}
                                  onChange={(event) =>
                                    void updateOrganizationMember(organization.id, member.user_id, {
                                      role: event.target.value as Exclude<OrganizationRole, "owner">,
                                    })
                                  }
                                >
                                  {MEMBER_ROLES.map((role) => (
                                    <option key={role.value} value={role.value}>
                                      {role.label}
                                    </option>
                                  ))}
                                </Select>
                              ) : (
                                <Badge variant="outline" className="inline-flex items-center gap-1">
                                  <Shield className="h-3 w-3" />
                                  {roleLabel(member.role)}
                                </Badge>
                              )}
                              {canManage && !isOwner ? (
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => void removeOrganizationMember(organization.id, member.user_id)}
                                >
                                  <Trash2 className="h-4 w-4 text-destructive" />
                                </Button>
                              ) : null}
                            </div>
                          </div>

                          <div className="mt-3 flex flex-wrap items-center gap-2">
                            <Badge variant="outline">
                              {member.counts_toward_seat ? "Counts toward seat" : "Excluded from billing"}
                            </Badge>
                            <Badge variant="outline">
                              {member.seat_status === "active" ? "Seat active" : "Seat suspended"}
                            </Badge>
                            {canManage && !isOwner ? (
                              <>
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() =>
                                    void updateOrganizationMember(organization.id, member.user_id, {
                                      counts_toward_seat: !member.counts_toward_seat,
                                    })
                                  }
                                >
                                  {member.counts_toward_seat ? "Exclude seat" : "Count seat"}
                                </Button>
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() =>
                                    void updateOrganizationMember(organization.id, member.user_id, {
                                      seat_status:
                                        member.seat_status === "active" ? "suspended" : "active",
                                    })
                                  }
                                >
                                  {member.seat_status === "active" ? "Suspend seat" : "Activate seat"}
                                </Button>
                              </>
                            ) : null}
                          </div>
                        </div>
                      );
                    })}

                    {canManage && assignableProfiles.length > 0 && (
                      <div className="grid gap-2 md:grid-cols-[1fr_140px_auto]">
                        <Select
                          value={selectedProfileId}
                          onChange={(event) =>
                            setSelectedProfileByOrg((prev) => ({
                              ...prev,
                              [organization.id]: event.target.value,
                            }))
                          }
                        >
                          <option value="">Add member from linked teams...</option>
                          {assignableProfiles
                            .filter(
                              (profile) => !members.some((member) => member.user_id === profile.id)
                            )
                            .map((profile) => (
                              <option key={profile.id} value={profile.id}>
                                {profile.full_name || profile.email}
                              </option>
                            ))}
                        </Select>
                        <Select
                          value={selectedRole}
                          onChange={(event) =>
                            setSelectedRoleByOrg((prev) => ({
                              ...prev,
                              [organization.id]: event.target.value as Exclude<
                                OrganizationRole,
                                "owner"
                              >,
                            }))
                          }
                        >
                          {MEMBER_ROLES.map((role) => (
                            <option key={role.value} value={role.value}>
                              {role.label}
                            </option>
                          ))}
                        </Select>
                        <Button
                          variant="outline"
                          onClick={() =>
                            void addOrganizationMember(
                              organization.id,
                              selectedProfileId,
                              selectedRole
                            )
                          }
                          disabled={!selectedProfileId}
                        >
                          Add member
                        </Button>
                      </div>
                    )}
                  </div>

                  <div className="space-y-4 rounded-2xl border border-border/60 bg-muted/20 p-4">
                    <div className="flex items-center gap-2">
                      <Mail className="h-4 w-4 text-primary" />
                      <p className="text-sm font-medium">Organization invites</p>
                    </div>

                    {canManage ? (
                      <div className="space-y-3">
                        <div className="grid gap-3 md:grid-cols-2">
                          <Input
                            value={inviteEmail}
                            onChange={(event) =>
                              setInviteEmailByOrg((prev) => ({
                                ...prev,
                                [organization.id]: event.target.value,
                              }))
                            }
                            placeholder="name@example.com"
                          />
                          <Select
                            value={inviteRole}
                            onChange={(event) =>
                              setInviteRoleByOrg((prev) => ({
                                ...prev,
                                [organization.id]: event.target.value as Exclude<
                                  OrganizationRole,
                                  "owner"
                                >,
                              }))
                            }
                          >
                            {MEMBER_ROLES.map((role) => (
                              <option key={role.value} value={role.value}>
                                {role.label}
                              </option>
                            ))}
                          </Select>
                        </div>
                        <Textarea
                          value={inviteMessage}
                          onChange={(event) =>
                            setInviteMessageByOrg((prev) => ({
                              ...prev,
                              [organization.id]: event.target.value,
                            }))
                          }
                          placeholder="Optional message for the invite email or shared invite card..."
                          className="min-h-[100px]"
                        />
                        <div className="flex flex-wrap items-center gap-2">
                          <Button
                            onClick={() => void handleInviteOrganization(organization.id)}
                            disabled={!inviteEmail.trim() || inviteSubmittingOrgId === organization.id}
                          >
                            {inviteSubmittingOrgId === organization.id ? "Sending..." : "Send invitation"}
                          </Button>
                          <p className="text-xs text-muted-foreground">
                            Works with email delivery if configured, or with a manual invite link.
                          </p>
                        </div>
                        {inviteSuccess && (
                          <div className="rounded-xl border border-border/60 bg-background/80 p-3">
                            <div className="flex flex-wrap items-start justify-between gap-3">
                              <div className="space-y-1">
                                <p className="text-sm font-medium">
                                  Invite ready for {inviteSuccess.email}
                                </p>
                                <p className="text-xs text-muted-foreground">
                                  {inviteSuccess.delivery === "email_sent"
                                    ? "The invitation email was sent successfully."
                                    : "Email delivery is not configured, but the invite link is ready to share."}
                                </p>
                              </div>
                              <div className="flex flex-wrap gap-2">
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() => void copyText(inviteSuccess.inviteUrl)}
                                >
                                  <Copy className="h-4 w-4" />
                                  Copy invite link
                                </Button>
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() =>
                                    window.open(inviteSuccess.inviteUrl, "_blank", "noopener,noreferrer")
                                  }
                                >
                                  Open invite
                                </Button>
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    ) : (
                      <p className="text-sm text-muted-foreground">
                        Only owners and admins can invite people into this organization.
                      </p>
                    )}

                    {pendingInvitations.length === 0 ? (
                      <div className="rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground">
                        No pending organization invites right now.
                      </div>
                    ) : (
                      <div className="space-y-3">
                        {pendingInvitations.map((invitation) => {
                          const inviteUrl = appBaseUrl
                            ? `${appBaseUrl}/organizations?invite=${encodeURIComponent(invitation.token)}`
                            : `/organizations?invite=${encodeURIComponent(invitation.token)}`;

                          return (
                            <div
                              key={invitation.id}
                              className="rounded-xl border border-border/60 bg-background/70 p-3"
                            >
                              <div className="flex flex-wrap items-start justify-between gap-3">
                                <div className="space-y-1">
                                  <p className="font-medium">{invitation.email}</p>
                                  <p className="text-xs text-muted-foreground">
                                    {roleLabel(invitation.role)} • Expires{" "}
                                    {new Intl.DateTimeFormat(undefined, {
                                      dateStyle: "medium",
                                      timeStyle: "short",
                                    }).format(new Date(invitation.expires_at))}
                                  </p>
                                  {invitation.message ? (
                                    <p className="text-xs text-muted-foreground">{invitation.message}</p>
                                  ) : null}
                                </div>
                                <div className="flex flex-wrap gap-2">
                                  <Button
                                    size="sm"
                                    variant="outline"
                                    onClick={() => void copyText(inviteUrl)}
                                  >
                                    <Copy className="h-4 w-4" />
                                    Copy link
                                  </Button>
                                  {canManage ? (
                                    <Button
                                      size="sm"
                                      variant="ghost"
                                      onClick={() => void revokeOrganizationInvitation(invitation.id)}
                                    >
                                      <Trash2 className="h-4 w-4 text-destructive" />
                                    </Button>
                                  ) : null}
                                </div>
                              </div>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>

                  <div className="space-y-4 rounded-2xl border border-border/60 bg-muted/20 p-4">
                    <div className="flex items-center gap-2">
                      <Users2 className="h-4 w-4 text-primary" />
                      <p className="text-sm font-medium">Join requests</p>
                      <Badge variant="outline">{pendingJoinRequests.length} pending</Badge>
                    </div>

                    {!canManage ? (
                      <div className="rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground">
                        Only owners and admins can review organization join requests.
                      </div>
                    ) : pendingJoinRequests.length === 0 ? (
                      <div className="rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground">
                        No pending join requests right now.
                      </div>
                    ) : (
                      <div className="space-y-3">
                        {pendingJoinRequests.map((request) => (
                          <div
                            key={request.id}
                            className="rounded-xl border border-border/60 bg-background/70 p-3"
                          >
                            <div className="flex flex-wrap items-start justify-between gap-3">
                              <div className="space-y-1">
                                <p className="font-medium">{request.email}</p>
                                <p className="text-xs text-muted-foreground">
                                  Requested{" "}
                                  {new Intl.DateTimeFormat(undefined, {
                                    dateStyle: "medium",
                                    timeStyle: "short",
                                  }).format(new Date(request.requested_at))}
                                </p>
                                {request.message ? (
                                  <p className="text-xs text-muted-foreground">{request.message}</p>
                                ) : null}
                              </div>
                              <div className="flex flex-wrap gap-2">
                                <Button
                                  size="sm"
                                  onClick={() =>
                                    void updateOrganizationJoinRequest(request.id, "approved")
                                  }
                                >
                                  Approve
                                </Button>
                                <Button
                                  size="sm"
                                  variant="outline"
                                  onClick={() =>
                                    void updateOrganizationJoinRequest(request.id, "declined")
                                  }
                                >
                                  Decline
                                </Button>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}

      {modalOpen && (
        <Modal
          open={modalOpen}
          onClose={() => {
            setModalOpen(false);
            setEditingOrganization(null);
          }}
          title={editingOrganization ? "Edit organization" : "New organization"}
          className="max-w-lg"
        >
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-1.5">
              <label className="text-sm font-medium">Name</label>
              <Input
                value={name}
                onChange={(event) => setName(event.target.value)}
                placeholder="Acme Group"
                autoFocus
                required
              />
            </div>
            <div className="space-y-1.5">
              <label className="text-sm font-medium">Description</label>
              <Textarea
                value={description}
                onChange={(event) => setDescription(event.target.value)}
                placeholder="Describe what this organization spans and how teams work together."
                className="min-h-[110px]"
              />
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button type="button" variant="ghost" onClick={() => setModalOpen(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={!name.trim() || submitting}>
                {submitting
                  ? editingOrganization
                    ? "Saving..."
                    : "Creating..."
                  : editingOrganization
                    ? "Save changes"
                    : "Create organization"}
              </Button>
            </div>
          </form>
        </Modal>
      )}

      {billingModalOpen && billingForm && (
        <Modal
          open={billingModalOpen}
          onClose={() => {
            setBillingModalOpen(false);
            setBillingForm(null);
          }}
          title="Manage billing"
          className="max-w-2xl"
        >
          <form onSubmit={handleBillingSubmit} className="space-y-4">
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Billing contact</label>
                <Input
                  value={billingForm.billing_name}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev ? { ...prev, billing_name: event.target.value } : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Billing email</label>
                <Input
                  type="email"
                  value={billingForm.billing_email}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev ? { ...prev, billing_email: event.target.value } : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Plan</label>
                <Select
                  value={billingForm.plan}
                  onChange={(event) => handleBillingPlanChange(event.target.value as BillingPlan)}
                >
                  {BILLING_PLAN_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Billing cycle</label>
                <Select
                  value={billingForm.billing_cycle}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev
                        ? { ...prev, billing_cycle: event.target.value as BillingCycle }
                        : prev
                    )
                  }
                >
                  {BILLING_CYCLE_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Subscription status</label>
                <Select
                  value={billingForm.subscription_status}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev
                        ? {
                            ...prev,
                            subscription_status: event.target.value as SubscriptionStatus,
                          }
                        : prev
                    )
                  }
                >
                  {SUBSCRIPTION_STATUS_OPTIONS.map((option) => (
                    <option key={option.value} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </Select>
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Monthly price (USD cents)</label>
                <Input
                  type="number"
                  min={0}
                  value={billingForm.monthly_price_cents}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev
                        ? {
                            ...prev,
                            monthly_price_cents: Number(event.target.value || 0),
                          }
                        : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Included seats</label>
                <Input
                  type="number"
                  min={0}
                  value={billingForm.included_seats}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev
                        ? { ...prev, included_seats: Number(event.target.value || 0) }
                        : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Purchased seats</label>
                <Input
                  type="number"
                  min={0}
                  value={billingForm.purchased_seats}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev
                        ? { ...prev, purchased_seats: Number(event.target.value || 0) }
                        : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Trial ends</label>
                <Input
                  type="datetime-local"
                  value={billingForm.trial_ends_at}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev ? { ...prev, trial_ends_at: event.target.value } : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Renews at</label>
                <Input
                  type="datetime-local"
                  value={billingForm.renews_at}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev ? { ...prev, renews_at: event.target.value } : prev
                    )
                  }
                />
              </div>
              <div className="space-y-1.5 md:col-span-2">
                <label className="text-sm font-medium">Cancel at</label>
                <Input
                  type="datetime-local"
                  value={billingForm.cancel_at}
                  onChange={(event) =>
                    setBillingForm((prev) =>
                      prev ? { ...prev, cancel_at: event.target.value } : prev
                    )
                  }
                />
              </div>
            </div>
            <div className="flex justify-end gap-2 pt-2">
              <Button
                type="button"
                variant="ghost"
                onClick={() => {
                  setBillingModalOpen(false);
                  setBillingForm(null);
                }}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={billingSubmitting}>
                {billingSubmitting ? "Saving..." : "Save billing"}
              </Button>
            </div>
          </form>
        </Modal>
      )}

      {securityModalOpen && securityForm && (
        <Modal
          open={securityModalOpen}
          onClose={() => {
            setSecurityModalOpen(false);
            setSecurityForm(null);
          }}
          title="Manage auth policy"
          className="max-w-2xl"
        >
          <form onSubmit={handleSecuritySubmit} className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">Allowed auth methods</label>
              <div className="flex flex-wrap gap-2">
                {AUTH_METHOD_OPTIONS.map((option) => {
                  const active = securityForm.allowed_auth_methods.includes(option.value);
                  return (
                    <button
                      key={option.value}
                      type="button"
                      onClick={() => toggleSecurityMethod(option.value)}
                      className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium transition-colors ${
                        active
                          ? "border-primary bg-primary/10 text-primary"
                          : "border-border bg-background text-muted-foreground hover:bg-accent"
                      }`}
                    >
                      {option.label}
                    </button>
                  );
                })}
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Allowed email domains</label>
                <Textarea
                  value={securityForm.allowed_email_domains}
                  onChange={(event) =>
                    setSecurityForm((prev) =>
                      prev ? { ...prev, allowed_email_domains: event.target.value } : prev
                    )
                  }
                  placeholder="acme.com, client.acme.com"
                  className="min-h-[110px]"
                />
              </div>
              <div className="space-y-1.5">
                <label className="text-sm font-medium">Auto-join domains</label>
                <Textarea
                  value={securityForm.auto_join_domains}
                  onChange={(event) =>
                    setSecurityForm((prev) =>
                      prev ? { ...prev, auto_join_domains: event.target.value } : prev
                    )
                  }
                  placeholder="team.acme.com"
                  className="min-h-[110px]"
                />
              </div>
            </div>

            <div className="grid gap-3 md:grid-cols-3">
              <button
                type="button"
                onClick={() =>
                  setSecurityForm((prev) =>
                    prev ? { ...prev, require_domain_match: !prev.require_domain_match } : prev
                  )
                }
                className={`rounded-xl border p-3 text-left transition-colors ${
                  securityForm.require_domain_match
                    ? "border-primary bg-primary/5"
                    : "border-border bg-background"
                }`}
              >
                <p className="text-sm font-medium">Require domain match</p>
                <p className="mt-1 text-xs text-muted-foreground">
                  Only matched domains are treated as valid org identities.
                </p>
              </button>
              <button
                type="button"
                onClick={() =>
                  setSecurityForm((prev) =>
                    prev ? { ...prev, invite_only: !prev.invite_only } : prev
                  )
                }
                className={`rounded-xl border p-3 text-left transition-colors ${
                  securityForm.invite_only
                    ? "border-primary bg-primary/5"
                    : "border-border bg-background"
                }`}
              >
                <p className="text-sm font-medium">Invite only</p>
                <p className="mt-1 text-xs text-muted-foreground">
                  Prevent open access expectations for matching domains.
                </p>
              </button>
              <button
                type="button"
                onClick={() =>
                  setSecurityForm((prev) =>
                    prev ? { ...prev, enforce_sso: !prev.enforce_sso } : prev
                  )
                }
                className={`rounded-xl border p-3 text-left transition-colors ${
                  securityForm.enforce_sso
                    ? "border-primary bg-primary/5"
                    : "border-border bg-background"
                }`}
              >
                <p className="text-sm font-medium">Enforce SSO</p>
                <p className="mt-1 text-xs text-muted-foreground">
                  Signal and enforce org-approved sign-in methods for matching emails.
                </p>
              </button>
            </div>

            <div className="flex justify-end gap-2 pt-2">
              <Button
                type="button"
                variant="ghost"
                onClick={() => {
                  setSecurityModalOpen(false);
                  setSecurityForm(null);
                }}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={securitySubmitting}>
                {securitySubmitting ? "Saving..." : "Save security"}
              </Button>
            </div>
          </form>
        </Modal>
      )}
    </div>
  );
}
