import { useCallback, useEffect, useMemo, useState } from "react"
import {
  Building,
  Crown,
  Mail,
  RefreshCw,
  Settings as SettingsIcon,
  Trash2,
  UserCog,
  UserPlus,
  Users as UsersIcon,
} from "lucide-react"

import { useArcadiaClient } from "@crema/arcadia-core-client"
import { useToast } from "@crema/notification-ui"
import {
  ActionsCell,
  BadgeCell,
  DataTable,
  DateCell,
  Pagination,
  useTable,
  type ActionItem,
  type BadgeTone,
  type Column,
} from "@crema/table-ui"
import { SearchInput } from "@crema/search-ui"
import { ConfirmDialog, EmptyState } from "@crema/feedback-ui"

import { AppShell } from "~/components/layout/app-shell"
import { DataState, DialogError } from "~/components/data-state"
import { errorMessage } from "~/lib/errors"
import { Badge } from "~/components/ui/badge"
import { Button } from "~/components/ui/button"
import { Card, CardContent, CardHeader } from "~/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "~/components/ui/dialog"
import { Input } from "~/components/ui/input"
import { Label } from "~/components/ui/label"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "~/components/ui/select"
import {
  addRestrictedMember,
  changeMemberRole,
  inviteMember,
  listAllOrganizations,
  listMembers,
  removeMember,
  transferOwnership,
  updateOrganization,
  type OnOwnerRemoval,
  type OrgMembership,
  type OrgRole,
  type OrgStatus,
  type Organization,
} from "~/lib/arcadia/organizations"
import { pageTitle } from "~/lib/page-meta"
import { useSession } from "~/lib/session"

export const meta = () => pageTitle("Organizations")

type MembersDialogState = { org: Organization } | null
type SettingsDialogState = { org: Organization } | null

const ON_OWNER_REMOVAL_LABEL: Record<OnOwnerRemoval, string> = {
  delete: "Delete org",
  require_transfer: "Require transfer",
  freeze_until_new_owner: "Freeze until new owner",
}

/** Members are keyed by user_id only; show the short form consistently. */
function memberLabel(m: OrgMembership): string {
  return `${m.user_id.slice(0, 8)}…`
}

export default function OrganizationsRoute() {
  const session = useSession()
  const arcadia = useArcadiaClient()
  const toast = useToast()

  const [orgs, setOrgs] = useState<Organization[]>([])
  const [loading, setLoading] = useState(true)
  // Raw thrown value: the status code is what makes the message useful.
  const [error, setError] = useState<unknown>(null)
  const [search, setSearch] = useState("")
  const [statusFilter, setStatusFilter] = useState<"all" | OrgStatus>("all")

  const [membersDialog, setMembersDialog] = useState<MembersDialogState>(null)
  const [settingsDialog, setSettingsDialog] = useState<SettingsDialogState>(null)

  const refresh = useCallback(async () => {
    setError(null)
    setLoading(true)
    try {
      setOrgs(await listAllOrganizations(arcadia))
    } catch (err) {
      setError(err)
    } finally {
      setLoading(false)
    }
  }, [arcadia])

  useEffect(() => {
    if (session) refresh()
  }, [session, refresh])

  const filtered = useMemo(
    () => (statusFilter === "all" ? orgs : orgs.filter((o) => o.status === statusFilter)),
    [orgs, statusFilter],
  )

  const columns = useMemo<Column<Organization>[]>(
    () => [
      {
        id: "name",
        header: "Organization",
        accessor: "name",
        sortable: true,
        cell: (o) => (
          <div className="flex flex-col">
            <span className="text-sm font-medium">{o.name}</span>
            <code className="rounded bg-muted px-1 font-mono text-[10px] text-muted-foreground">
              {o.slug}
            </code>
          </div>
        ),
      },
      {
        id: "status",
        header: "Status",
        accessor: "status",
        sortable: true,
        cell: (o) => <BadgeCell label={o.status} tone={statusTone(o.status)} />,
      },
      {
        id: "on_owner_removal",
        header: "Owner-removal policy",
        accessor: "on_owner_removal",
        sortable: true,
        cell: (o) => (
          <span className="text-xs text-muted-foreground">
            {ON_OWNER_REMOVAL_LABEL[o.on_owner_removal] ?? o.on_owner_removal}
          </span>
        ),
      },
      {
        id: "updated_at",
        header: "Updated",
        accessor: "updated_at",
        sortable: true,
        cell: (o) => <DateCell value={o.updated_at} format="short" />,
      },
      {
        id: "actions",
        header: "",
        align: "right",
        cell: (o) => {
          const items: ActionItem[] = [
            {
              id: "members",
              label: "Manage members",
              icon: <UsersIcon className="size-4" />,
              dataAction: `org-${o.id}-members`,
              onSelect: () => setMembersDialog({ org: o }),
            },
            {
              id: "settings",
              label: "Settings",
              icon: <SettingsIcon className="size-4" />,
              dataAction: `org-${o.id}-settings`,
              onSelect: () => setSettingsDialog({ org: o }),
            },
          ]
          return <ActionsCell items={items} triggerDataAction={`org-${o.id}-actions`} />
        },
      },
    ],
    [],
  )

  const table = useTable<Organization>({
    data: filtered,
    columns,
    getRowId: (o) => o.id,
    initialPageSize: 25,
    initialSearch: search,
  })
  useEffect(() => {
    table.setSearch(search)
  }, [search, table])

  return (
    <AppShell>
      <div className="flex flex-col gap-4">
        <header className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <h1 className="text-2xl font-semibold tracking-tight">Organizations</h1>
            <p className="text-sm text-muted-foreground">
              End-user workspaces inside this tenant. Each one is owned by a regular user; admins
              here can manage members, change ownership policy, or freeze a workspace.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={refresh}
              disabled={loading}
              data-action="organizations-refresh"
            >
              <RefreshCw className={`size-4 ${loading ? "animate-spin" : ""}`} />
              Refresh
            </Button>
          </div>
        </header>

        <Card>
          <CardHeader className="flex flex-row items-center gap-3">
            <SearchInput
              value={search}
              onValueChange={setSearch}
              placeholder="Search by name or slug"
              data-action="organizations-search"
              className="max-w-sm flex-1"
            />
            <Select
              value={statusFilter}
              onValueChange={(v) => setStatusFilter(v as typeof statusFilter)}
            >
              <SelectTrigger className="w-44" data-action="organizations-status-filter">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All statuses</SelectItem>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="frozen">Frozen</SelectItem>
                <SelectItem value="pending_deletion">Pending deletion</SelectItem>
              </SelectContent>
            </Select>
            <div className="ml-auto text-xs text-muted-foreground">
              {table.total} of {orgs.length}
            </div>
          </CardHeader>

          <CardContent className="relative p-0">
            <DataState
              loading={loading}
              error={error}
              isEmpty={table.total === 0}
              onRetry={refresh}
              loadingLabel="Loading organizations…"
              empty={
                <EmptyState
                  icon={<Building className="size-6" />}
                  title={
                    search || statusFilter !== "all"
                      ? "No organizations match those filters."
                      : "No organizations yet."
                  }
                  description={
                    search || statusFilter !== "all"
                      ? "Loosen the filter set."
                      : "End-users create these from inside the app; nothing to do here yet."
                  }
                  className="py-12"
                />
              }
            >
              <DataTable
                columns={columns}
                rows={table.pageRows}
                getRowId={(o) => o.id}
                sort={table.sort}
                onSortToggle={table.toggleSort}
                loading={loading && orgs.length > 0}
                stickyHeader
              />
              <Pagination
                page={table.page}
                pageSize={table.pageSize}
                total={table.total}
                onPageChange={table.setPage}
                onPageSizeChange={table.setPageSize}
              />
            </DataState>
          </CardContent>
        </Card>
      </div>

      <MembersDialog state={membersDialog} onClose={() => setMembersDialog(null)} />
      <SettingsDialog
        state={settingsDialog}
        onClose={() => setSettingsDialog(null)}
        onSaved={async (message) => {
          setSettingsDialog(null)
          await refresh()
          toast.success(message)
        }}
      />
    </AppShell>
  )
}

function statusTone(s: OrgStatus): BadgeTone {
  if (s === "active") return "success"
  if (s === "frozen") return "warning"
  if (s === "pending_deletion") return "danger"
  return "default"
}

function roleBadgeVariant(r: OrgRole): "default" | "secondary" | "destructive" | "outline" {
  if (r === "owner") return "default"
  if (r === "admin") return "secondary"
  return "outline"
}

// ============================================================================
// Members dialog
// ============================================================================

type InvitePane = "none" | "invite_existing" | "add_restricted"

function MembersDialog({
  state,
  onClose,
}: {
  state: MembersDialogState
  onClose: () => void
}) {
  const arcadia = useArcadiaClient()
  const toast = useToast()
  const open = state !== null
  const org = state?.org

  const [members, setMembers] = useState<OrgMembership[]>([])
  const [loading, setLoading] = useState(false)
  // The member list has its own load error — a failed fetch inside this dialog
  // must not read as "no members yet".
  const [error, setError] = useState<unknown>(null)
  const [pendingRemove, setPendingRemove] = useState<OrgMembership | null>(null)
  const [transferTarget, setTransferTarget] = useState<OrgMembership | null>(null)
  const [pane, setPane] = useState<InvitePane>("none")

  const refresh = useCallback(async () => {
    if (!org) return
    setError(null)
    setLoading(true)
    try {
      setMembers(await listMembers(arcadia, org.id))
    } catch (err) {
      setError(err)
    } finally {
      setLoading(false)
    }
  }, [arcadia, org])

  useEffect(() => {
    if (open) {
      setPane("none")
      refresh()
    }
  }, [open, refresh])

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-3xl">
        <DialogHeader>
          <DialogTitle>{org ? `Members — ${org.name}` : "Members"}</DialogTitle>
          <DialogDescription>
            {org
              ? `Manage who can act inside ${org.name}. The owner can be changed via transfer; one active owner at a time.`
              : ""}
          </DialogDescription>
        </DialogHeader>

        {pane === "none" ? (
          <div className="flex items-center justify-end gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setPane("invite_existing")}
              data-action={`org-${org?.id}-invite-existing`}
            >
              <Mail className="size-4" />
              Invite by email
            </Button>
            <Button
              size="sm"
              onClick={() => setPane("add_restricted")}
              data-action={`org-${org?.id}-add-restricted`}
            >
              <UserPlus className="size-4" />
              Add restricted user
            </Button>
          </div>
        ) : pane === "invite_existing" ? (
          <InviteByEmailForm
            orgId={org!.id}
            onCancel={() => setPane("none")}
            onSaved={async (message) => {
              setPane("none")
              await refresh()
              toast.success(message)
            }}
          />
        ) : (
          <AddRestrictedForm
            orgId={org!.id}
            onCancel={() => setPane("none")}
            onSaved={async (message) => {
              setPane("none")
              await refresh()
              toast.success(message)
            }}
          />
        )}

        <div className="relative">
          <DataState
            loading={loading}
            error={error}
            isEmpty={members.length === 0}
            onRetry={refresh}
            loadingLabel="Loading members…"
            empty={
              <EmptyState
                icon={<UsersIcon className="size-6" />}
                title="No members yet."
                description="Invite someone or add a restricted sub-user to get started."
                className="py-8"
              />
            }
          >
            <div className="rounded-md border border-border">
              <table className="w-full text-sm">
                <thead className="bg-muted/40 text-left text-xs text-muted-foreground">
                  <tr>
                    <th className="px-3 py-2 font-medium">User</th>
                    <th className="px-3 py-2 font-medium">Role</th>
                    <th className="px-3 py-2 font-medium">Status</th>
                    <th className="px-3 py-2 font-medium">Joined</th>
                    <th className="px-3 py-2 text-right font-medium" />
                  </tr>
                </thead>
                <tbody>
                  {members.map((m) => (
                    <tr key={m.id} className="border-t border-border">
                      <td className="px-3 py-2 font-mono text-xs">{memberLabel(m)}</td>
                      <td className="px-3 py-2">
                        <Badge variant={roleBadgeVariant(m.role)}>{m.role}</Badge>
                      </td>
                      <td className="px-3 py-2">
                        <Badge variant="secondary">{m.status}</Badge>
                      </td>
                      <td className="px-3 py-2 text-muted-foreground">
                        {m.joined_at ? new Date(m.joined_at).toLocaleDateString() : "—"}
                      </td>
                      <td className="px-3 py-2 text-right">
                        <MemberRowActions
                          member={m}
                          orgId={org!.id}
                          onTransfer={() => setTransferTarget(m)}
                          onRemove={() => setPendingRemove(m)}
                          onRoleChanged={refresh}
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </DataState>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose} data-action={`org-${org?.id}-members-close`}>
            Close
          </Button>
        </DialogFooter>

        <ConfirmDialog
          open={pendingRemove !== null}
          onOpenChange={(o) => !o && setPendingRemove(null)}
          title="Remove member?"
          description={
            pendingRemove
              ? pendingRemove.role === "owner"
                ? `This member owns ${org?.name ?? "the organization"}. Removing them applies its owner-removal policy — ${
                    org ? ON_OWNER_REMOVAL_LABEL[org.on_owner_removal].toLowerCase() : "the configured policy"
                  } — which may delete or freeze the whole workspace. Transfer ownership first if you only mean to remove the person.`
                : `They immediately lose access to ${org?.name ?? "this organization"} and anything shared inside it.`
              : ""
          }
          confirmLabel="Remove"
          variant="danger"
          onConfirm={async () => {
            if (!pendingRemove || !org) return
            const who = memberLabel(pendingRemove)
            try {
              await removeMember(arcadia, org.id, pendingRemove.user_id)
              setPendingRemove(null)
              await refresh()
              toast.success(`Removed ${who} from ${org.name}`)
            } catch (err) {
              setPendingRemove(null)
              toast.error(errorMessage(err, `remove ${who} from ${org.name}`))
            }
          }}
        />

        <ConfirmDialog
          open={transferTarget !== null}
          onOpenChange={(o) => !o && setTransferTarget(null)}
          title="Transfer ownership?"
          description={
            transferTarget
              ? `${memberLabel(transferTarget)} becomes the owner of ${org?.name ?? "this organization"}, and the current owner is demoted to admin.`
              : ""
          }
          confirmLabel="Transfer"
          variant="default"
          onConfirm={async () => {
            if (!transferTarget || !org) return
            const who = memberLabel(transferTarget)
            try {
              await transferOwnership(arcadia, org.id, transferTarget.user_id)
              setTransferTarget(null)
              await refresh()
              toast.success(`${org.name} is now owned by ${who}`)
            } catch (err) {
              setTransferTarget(null)
              toast.error(errorMessage(err, `transfer ${org.name} to ${who}`))
            }
          }}
        />
      </DialogContent>
    </Dialog>
  )
}

function MemberRowActions({
  member,
  orgId,
  onTransfer,
  onRemove,
  onRoleChanged,
}: {
  member: OrgMembership
  orgId: string
  onTransfer: () => void
  onRemove: () => void
  onRoleChanged: () => Promise<void>
}) {
  const arcadia = useArcadiaClient()
  const toast = useToast()

  const items: ActionItem[] = []

  if (member.role !== "owner") {
    items.push({
      id: "promote-admin",
      label: member.role === "admin" ? "Demote to member" : "Promote to admin",
      icon: <UserCog className="size-4" />,
      dataAction: `org-${orgId}-member-${member.id}-role`,
      onSelect: async () => {
        const next = member.role === "admin" ? "member" : "admin"
        try {
          await changeMemberRole(arcadia, orgId, member.user_id, next)
          await onRoleChanged()
          toast.success(`${memberLabel(member)} is now ${next === "admin" ? "an admin" : "a member"}`)
        } catch (err) {
          toast.error(errorMessage(err, `change ${memberLabel(member)} to ${next}`))
        }
      },
    })
    items.push({
      id: "transfer",
      label: "Transfer ownership to this user",
      icon: <Crown className="size-4" />,
      dataAction: `org-${orgId}-member-${member.id}-transfer`,
      onSelect: onTransfer,
    })
  }

  items.push({
    id: "remove",
    label: "Remove",
    icon: <Trash2 className="size-4" />,
    destructive: true,
    dataAction: `org-${orgId}-member-${member.id}-remove`,
    onSelect: onRemove,
  })

  return (
    <ActionsCell items={items} triggerDataAction={`org-${orgId}-member-${member.id}-actions`} />
  )
}

// ============================================================================
// Invite-by-email and add-restricted forms
// ============================================================================

function InviteByEmailForm({
  orgId,
  onCancel,
  onSaved,
}: {
  orgId: string
  onCancel: () => void
  onSaved: (message: string) => Promise<void>
}) {
  const arcadia = useArcadiaClient()
  const [email, setEmail] = useState("")
  const [role, setRole] = useState<OrgRole>("member")
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<unknown>(null)

  const submit = async () => {
    setError(null)
    setSaving(true)
    try {
      const res = await inviteMember(arcadia, orgId, { email, role })
      await onSaved(
        res.type === "membership"
          ? `Added ${email.trim()} — they already had an account`
          : `Invitation sent to ${email.trim()}`,
      )
    } catch (err) {
      // The form stays filled in; the error lands right under it.
      setError(err)
      setSaving(false)
    }
  }

  return (
    <div className="rounded-md border border-border bg-muted/20 p-3">
      <div className="grid gap-2 sm:grid-cols-[1fr_140px_auto_auto]">
        <Input
          placeholder="email@example.com"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          data-action={`org-${orgId}-invite-email`}
        />
        <Select value={role} onValueChange={(v) => setRole(v as OrgRole)}>
          <SelectTrigger data-action={`org-${orgId}-invite-role`}>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="member">Member</SelectItem>
            <SelectItem value="admin">Admin</SelectItem>
          </SelectContent>
        </Select>
        <Button
          variant="outline"
          size="sm"
          onClick={onCancel}
          disabled={saving}
          data-action={`org-${orgId}-invite-cancel`}
        >
          Cancel
        </Button>
        <Button
          size="sm"
          disabled={!email || saving}
          onClick={submit}
          data-action={`org-${orgId}-invite-submit`}
        >
          Send invite
        </Button>
      </div>

      {error ? (
        <div className="mt-2">
          <DialogError error={error} context="send the invitation" />
        </div>
      ) : null}

      <p className="mt-2 text-xs text-muted-foreground">
        If an account with that email already exists in this tenant, an invited membership is
        created; otherwise an email invitation is sent and the user is materialized on accept.
      </p>
    </div>
  )
}

function AddRestrictedForm({
  orgId,
  onCancel,
  onSaved,
}: {
  orgId: string
  onCancel: () => void
  onSaved: (message: string) => Promise<void>
}) {
  const arcadia = useArcadiaClient()
  const [email, setEmail] = useState("")
  const [firstName, setFirstName] = useState("")
  const [lastName, setLastName] = useState("")
  const [password, setPassword] = useState("")
  const [role, setRole] = useState<OrgRole>("member")
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<unknown>(null)

  const submit = async () => {
    setError(null)
    setSaving(true)
    try {
      await addRestrictedMember(arcadia, orgId, {
        email,
        password,
        first_name: firstName,
        last_name: lastName,
        role,
      })
      await onSaved(`Added ${email.trim()} as a restricted user`)
    } catch (err) {
      setError(err)
      setSaving(false)
    }
  }

  return (
    <div className="rounded-md border border-border bg-muted/20 p-3">
      <div className="grid gap-2 sm:grid-cols-2">
        <div className="flex flex-col gap-1">
          <Label htmlFor="r-email">Email</Label>
          <Input
            id="r-email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            data-action={`org-${orgId}-restricted-email`}
          />
        </div>
        <div className="flex flex-col gap-1">
          <Label htmlFor="r-password">Initial password</Label>
          <Input
            id="r-password"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            data-action={`org-${orgId}-restricted-password`}
          />
        </div>
        <div className="flex flex-col gap-1">
          <Label htmlFor="r-first">First name</Label>
          <Input
            id="r-first"
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
            data-action={`org-${orgId}-restricted-first-name`}
          />
        </div>
        <div className="flex flex-col gap-1">
          <Label htmlFor="r-last">Last name</Label>
          <Input
            id="r-last"
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
            data-action={`org-${orgId}-restricted-last-name`}
          />
        </div>
        <div className="flex flex-col gap-1">
          <Label htmlFor="r-role">Role</Label>
          <Select value={role} onValueChange={(v) => setRole(v as OrgRole)}>
            <SelectTrigger id="r-role" data-action={`org-${orgId}-restricted-role`}>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="member">Member</SelectItem>
              <SelectItem value="admin">Admin</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {error ? (
        <div className="mt-3">
          <DialogError error={error} context="add the restricted user" />
        </div>
      ) : null}

      <div className="mt-3 flex items-center justify-end gap-2">
        <Button
          variant="outline"
          size="sm"
          onClick={onCancel}
          disabled={saving}
          data-action={`org-${orgId}-restricted-cancel`}
        >
          Cancel
        </Button>
        <Button
          size="sm"
          disabled={!email || !password || !firstName || !lastName || saving}
          onClick={submit}
          data-action={`org-${orgId}-restricted-submit`}
        >
          Add user
        </Button>
      </div>
      <p className="mt-2 text-xs text-muted-foreground">
        Restricted users exist only inside this org — they can never act in personal mode and have
        no plan of their own.
      </p>
    </div>
  )
}

// ============================================================================
// Settings dialog
// ============================================================================

function SettingsDialog({
  state,
  onClose,
  onSaved,
}: {
  state: SettingsDialogState
  onClose: () => void
  onSaved: (message: string) => Promise<void>
}) {
  const arcadia = useArcadiaClient()
  const open = state !== null
  const org = state?.org

  const [name, setName] = useState("")
  const [status, setStatus] = useState<OrgStatus>("active")
  const [onOwnerRemoval, setOnOwnerRemoval] = useState<OnOwnerRemoval>("require_transfer")
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<unknown>(null)

  useEffect(() => {
    if (org) {
      setName(org.name)
      setStatus(org.status)
      setOnOwnerRemoval(org.on_owner_removal)
      setError(null)
      setSaving(false)
    }
  }, [org])

  const submit = async () => {
    if (!org) return
    setError(null)
    setSaving(true)
    try {
      await updateOrganization(arcadia, org.id, {
        name,
        status,
        on_owner_removal: onOwnerRemoval,
      })
      await onSaved(`Saved ${name.trim() || org.name}`)
    } catch (err) {
      setError(err)
      setSaving(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{org ? `Settings — ${org.name}` : "Settings"}</DialogTitle>
          <DialogDescription>Change name, status, or owner-removal policy.</DialogDescription>
        </DialogHeader>

        <div className="flex flex-col gap-3">
          <div className="flex flex-col gap-1">
            <Label htmlFor="o-name">Name</Label>
            <Input
              id="o-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              data-action="org-settings-name"
            />
          </div>

          <div className="flex flex-col gap-1">
            <Label htmlFor="o-status">Status</Label>
            <Select value={status} onValueChange={(v) => setStatus(v as OrgStatus)}>
              <SelectTrigger id="o-status" data-action="org-settings-status">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="active">Active</SelectItem>
                <SelectItem value="frozen">Frozen</SelectItem>
                <SelectItem value="pending_deletion">Pending deletion</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="flex flex-col gap-1">
            <Label htmlFor="o-policy">Owner-removal policy</Label>
            <Select
              value={onOwnerRemoval}
              onValueChange={(v) => setOnOwnerRemoval(v as OnOwnerRemoval)}
            >
              <SelectTrigger id="o-policy" data-action="org-settings-policy">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="require_transfer">Require transfer (safest)</SelectItem>
                <SelectItem value="freeze_until_new_owner">Freeze until new owner</SelectItem>
                <SelectItem value="delete">Delete on owner removal</SelectItem>
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground">
              Decides what happens when the owner's membership is removed.
            </p>
          </div>
        </div>

        {error ? <DialogError error={error} context="save the organization" /> : null}

        <DialogFooter>
          <Button
            variant="outline"
            onClick={onClose}
            disabled={saving}
            data-action="org-settings-cancel"
          >
            Cancel
          </Button>
          <Button disabled={saving} onClick={submit} data-action="org-settings-save">
            {saving ? "Saving…" : "Save"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}

export { RouteErrorBoundary as ErrorBoundary } from "~/components/route-error"
