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 { ArcadiaError, useArcadiaClient } from "@crema/arcadia-core-client"
import {
  ActionsCell,
  BadgeCell,
  DataTable,
  DateCell,
  Pagination,
  useTable,
  type ActionItem,
  type BadgeTone,
  type Column,
} from "@crema/table-ui"
import { SearchInput } from "@crema/search-ui"
import { AlertBanner, ConfirmDialog, EmptyState, LoadingOverlay } from "@crema/feedback-ui"

import { AppShell } from "~/components/layout/app-shell"
import { Badge } from "~/components/ui/badge"
import { Button } from "~/components/ui/button"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} 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",
}

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

  const [orgs, setOrgs] = useState<Organization[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [info, setInfo] = useState<string | null>(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 instanceof ArcadiaError ? err.message : "Failed to load organizations.")
    } 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} />
        },
      },
    ],
    [],
  )

  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>

        {error ? (
          <AlertBanner variant="error" dismissible onDismiss={() => setError(null)}>
            {error}
          </AlertBanner>
        ) : null}
        {info ? (
          <AlertBanner variant="success" dismissible onDismiss={() => setInfo(null)}>
            {info}
          </AlertBanner>
        ) : null}

        <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">
            <LoadingOverlay
              active={loading && orgs.length === 0}
              label="Loading organizations…"
            />
            {table.total === 0 && !loading ? (
              <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}
                />
              </>
            )}
          </CardContent>
        </Card>
      </div>

      <MembersDialog
        state={membersDialog}
        onClose={() => setMembersDialog(null)}
        onInfo={setInfo}
        onError={setError}
      />
      <SettingsDialog
        state={settingsDialog}
        onClose={() => setSettingsDialog(null)}
        onSaved={async (msg) => {
          setSettingsDialog(null)
          if (msg) setInfo(msg)
          await refresh()
        }}
        onError={setError}
      />
    </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,
  onInfo,
  onError,
}: {
  state: MembersDialogState
  onClose: () => void
  onInfo: (msg: string | null) => void
  onError: (msg: string | null) => void
}) {
  const arcadia = useArcadiaClient()
  const open = state !== null
  const org = state?.org

  const [members, setMembers] = useState<OrgMembership[]>([])
  const [loading, setLoading] = useState(false)
  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
    setLoading(true)
    try {
      setMembers(await listMembers(arcadia, org.id))
    } catch (err) {
      onError(err instanceof ArcadiaError ? err.message : "Failed to load members.")
    } finally {
      setLoading(false)
    }
  }, [arcadia, org, onError])

  useEffect(() => {
    if (open) 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 (msg) => {
              setPane("none")
              onInfo(msg)
              await refresh()
            }}
            onError={onError}
          />
        ) : (
          <AddRestrictedForm
            orgId={org!.id}
            onCancel={() => setPane("none")}
            onSaved={async (msg) => {
              setPane("none")
              onInfo(msg)
              await refresh()
            }}
            onError={onError}
          />
        )}

        <div className="relative">
          <LoadingOverlay active={loading && members.length === 0} label="Loading members…" />
          {members.length === 0 && !loading ? (
            <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">{m.user_id.slice(0, 8)}…</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={async (msg) => {
                            onInfo(msg)
                            await refresh()
                          }}
                          onError={onError}
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </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 is the owner. Removal will follow the org's owner-removal policy."
                : "They will lose access to this organization."
              : ""
          }
          confirmLabel="Remove"
          variant="danger"
          onConfirm={async () => {
            if (!pendingRemove || !org) return
            try {
              await removeMember(arcadia, org.id, pendingRemove.user_id)
              setPendingRemove(null)
              onInfo("Member removed.")
              await refresh()
            } catch (err) {
              onError(err instanceof ArcadiaError ? err.message : "Remove failed.")
              setPendingRemove(null)
            }
          }}
        />

        <ConfirmDialog
          open={transferTarget !== null}
          onOpenChange={(o) => !o && setTransferTarget(null)}
          title="Transfer ownership?"
          description={
            transferTarget
              ? `The current owner will be demoted to admin. ${transferTarget.user_id.slice(0, 8)}… will become owner.`
              : ""
          }
          confirmLabel="Transfer"
          variant="default"
          onConfirm={async () => {
            if (!transferTarget || !org) return
            try {
              await transferOwnership(arcadia, org.id, transferTarget.user_id)
              setTransferTarget(null)
              onInfo("Ownership transferred.")
              await refresh()
            } catch (err) {
              onError(err instanceof ArcadiaError ? err.message : "Transfer failed.")
              setTransferTarget(null)
            }
          }}
        />
      </DialogContent>
    </Dialog>
  )
}

function MemberRowActions({
  member,
  orgId,
  onTransfer,
  onRemove,
  onRoleChanged,
  onError,
}: {
  member: OrgMembership
  orgId: string
  onTransfer: () => void
  onRemove: () => void
  onRoleChanged: (msg: string) => Promise<void>
  onError: (msg: string | null) => void
}) {
  const arcadia = useArcadiaClient()

  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(`Role set to ${next}.`)
        } catch (err) {
          onError(err instanceof ArcadiaError ? err.message : "Role change failed.")
        }
      },
    })
    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} />
}

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

function InviteByEmailForm({
  orgId,
  onCancel,
  onSaved,
  onError,
}: {
  orgId: string
  onCancel: () => void
  onSaved: (msg: string) => Promise<void>
  onError: (msg: string | null) => void
}) {
  const arcadia = useArcadiaClient()
  const [email, setEmail] = useState("")
  const [role, setRole] = useState<OrgRole>("member")
  const [saving, setSaving] = useState(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)}
        />
        <Select value={role} onValueChange={(v) => setRole(v as OrgRole)}>
          <SelectTrigger>
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="member">Member</SelectItem>
            <SelectItem value="admin">Admin</SelectItem>
          </SelectContent>
        </Select>
        <Button variant="outline" size="sm" onClick={onCancel} disabled={saving}>
          Cancel
        </Button>
        <Button
          size="sm"
          disabled={!email || saving}
          onClick={async () => {
            setSaving(true)
            try {
              const res = await inviteMember(arcadia, orgId, { email, role })
              await onSaved(
                res.type === "membership"
                  ? "Invited existing user."
                  : "Email invitation sent.",
              )
            } catch (err) {
              onError(err instanceof ArcadiaError ? err.message : "Invite failed.")
            } finally {
              setSaving(false)
            }
          }}
        >
          Send invite
        </Button>
      </div>
      <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,
  onError,
}: {
  orgId: string
  onCancel: () => void
  onSaved: (msg: string) => Promise<void>
  onError: (msg: string | null) => 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)

  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)} />
        </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)}
          />
        </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)} />
        </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)} />
        </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">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="member">Member</SelectItem>
              <SelectItem value="admin">Admin</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>
      <div className="mt-3 flex items-center justify-end gap-2">
        <Button variant="outline" size="sm" onClick={onCancel} disabled={saving}>
          Cancel
        </Button>
        <Button
          size="sm"
          disabled={!email || !password || !firstName || !lastName || saving}
          onClick={async () => {
            setSaving(true)
            try {
              await addRestrictedMember(arcadia, orgId, {
                email,
                password,
                first_name: firstName,
                last_name: lastName,
                role,
              })
              await onSaved("Restricted user added.")
            } catch (err) {
              onError(err instanceof ArcadiaError ? err.message : "Add failed.")
            } finally {
              setSaving(false)
            }
          }}
        >
          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,
  onError,
}: {
  state: SettingsDialogState
  onClose: () => void
  onSaved: (msg?: string) => Promise<void>
  onError: (msg: string | null) => 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)

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

  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)} />
          </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">
                <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">
                <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>

        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={saving}>
            Cancel
          </Button>
          <Button
            disabled={saving}
            onClick={async () => {
              if (!org) return
              setSaving(true)
              try {
                await updateOrganization(arcadia, org.id, {
                  name,
                  status,
                  on_owner_removal: onOwnerRemoval,
                })
                await onSaved("Organization updated.")
              } catch (err) {
                onError(err instanceof ArcadiaError ? err.message : "Save failed.")
              } finally {
                setSaving(false)
              }
            }}
          >
            Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
