"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { PasswordInput } from "@/components/ui/password-input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Card, CardContent } from "@/components/ui/card";
import DataService from "@/config/axios";
import { useRequireSuperAdmin } from "@/hooks/use-require-super-admin";
import { getApiErrorMessage } from "@/lib/api-error";
import { toast } from "sonner";
import { Check, Copy, KeyRound, Pencil, Trash2 } from "lucide-react";
import { MODULE_OPTIONS } from "@/lib/tenant-api";

type ClientRow = {
  _id: string;
  name: string;
  clientId: string;
  status: string;
  createdAt?: string;
  enabledModules?: string[];
};

type RoleOpt = { _id: string; name: string };

function generateRandomPassword() {
  const lower = "abcdefghjkmnpqrstuvwxyz";
  const upper = "ABCDEFGHJKMNPQRSTUVWXYZ";
  const nums = "23456789";
  const special = "_!@#$%";
  const pick = (s: string) => s[Math.floor(Math.random() * s.length)];
  const parts = [pick(upper), pick(lower), pick(nums), pick(special)];
  const all = lower + upper + nums + special;
  for (let i = 0; i < 10; i++) parts.push(pick(all));
  return parts.sort(() => Math.random() - 0.5).join("");
}

const defaultModules = () => MODULE_OPTIONS.map((m) => m.id);

function formatModulesLabel(mods?: string[]) {
  const list = mods?.length ? mods : defaultModules();
  return list
    .map((id) => MODULE_OPTIONS.find((m) => m.id === id)?.label ?? id)
    .join(", ");
}

export default function AdminClientsBlock() {
  const ready = useRequireSuperAdmin();
  const [clients, setClients] = useState<ClientRow[]>([]);
  const [copiedRowId, setCopiedRowId] = useState<string | null>(null);
  const copyResetRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const copyClientId = useCallback((clientId: string, rowId: string) => {
    void navigator.clipboard.writeText(clientId);
    toast.success("Client ID copied");
    setCopiedRowId(rowId);
    if (copyResetRef.current) clearTimeout(copyResetRef.current);
    copyResetRef.current = setTimeout(() => {
      setCopiedRowId(null);
      copyResetRef.current = null;
    }, 2000);
  }, []);

  useEffect(() => {
    return () => {
      if (copyResetRef.current) clearTimeout(copyResetRef.current);
    };
  }, []);
  const [loading, setLoading] = useState(true);
  const [open, setOpen] = useState(false);
  const [secretDialog, setSecretDialog] = useState<{
    title: string;
    clientId: string;
    clientSecret: string;
    initialUser?: {
      username: string;
      email: string;
      firstName: string;
      lastName: string;
      phone?: string;
      roleName: string | null;
      temporaryPassword: string;
    };
  } | null>(null);
  const [editing, setEditing] = useState<ClientRow | null>(null);
  const [formName, setFormName] = useState("");
  const [formModules, setFormModules] = useState<string[]>(defaultModules);
  const [roles, setRoles] = useState<RoleOpt[]>([]);
  const [ownerFirstName, setOwnerFirstName] = useState("");
  const [ownerLastName, setOwnerLastName] = useState("");
  const [ownerEmail, setOwnerEmail] = useState("");
  const [ownerPhone, setOwnerPhone] = useState("");
  const [ownerUsername, setOwnerUsername] = useState("");
  const [ownerPassword, setOwnerPassword] = useState("");
  const [ownerRoleId, setOwnerRoleId] = useState("");

  const toggleModule = (id: string, checked: boolean) => {
    setFormModules((prev) => {
      if (checked) return prev.includes(id) ? prev : [...prev, id];
      return prev.filter((m) => m !== id);
    });
  };

  const load = useCallback(async () => {
    try {
      const res = await DataService.get("/admin/clients");
      setClients(res.data?.data || []);
    } catch {
      toast.error("Failed to load clients");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    if (ready) load();
  }, [ready, load]);

  useEffect(() => {
    if (!ready) return;
    let cancelled = false;
    DataService.get("/admin/roles")
      .then((res) => {
        if (!cancelled) setRoles(res.data?.data || []);
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, [ready]);

  const openCreate = () => {
    setEditing(null);
    setFormName("");
    setFormModules(defaultModules());
    setOwnerFirstName("");
    setOwnerLastName("");
    setOwnerEmail("");
    setOwnerPhone("");
    setOwnerUsername("");
    setOwnerPassword("");
    setOwnerRoleId("");
    setOpen(true);
  };

  const openEdit = (c: ClientRow) => {
    setEditing(c);
    setFormName(c.name);
    setFormModules(
      c.enabledModules?.length ? [...c.enabledModules] : defaultModules()
    );
    setOpen(true);
  };

  const save = async () => {
    try {
      if (!formName.trim()) {
        toast.error("Business name is required");
        return;
      }
      if (formModules.length === 0) {
        toast.error("Select at least one module");
        return;
      }
      if (!editing) {
        if (!ownerEmail.trim()) {
          toast.error("Owner email is required");
          return;
        }
        if (ownerPassword.trim()) {
          const p = ownerPassword;
          const ok =
            p.length >= 8 &&
            /[a-z]/.test(p) &&
            /[A-Z]/.test(p) &&
            /\d/.test(p) &&
            /[^a-zA-Z0-9]/.test(p);
          if (!ok) {
            toast.error(
              "Password must be 8+ chars with lowercase, uppercase, number, and special character (or leave blank to auto-generate)"
            );
            return;
          }
        }
      }
      if (editing) {
        await DataService.patch(`/admin/clients/${editing._id}`, {
          name: formName.trim(),
          status: editing.status,
          enabledModules: formModules,
        });
        toast.success("Client updated");
      } else {
        const payload: Record<string, unknown> = {
          name: formName.trim(),
          enabledModules: formModules,
          createInitialUser: true,
          ownerEmail: ownerEmail.trim(),
          ownerFirstName: ownerFirstName.trim(),
          ownerLastName: ownerLastName.trim(),
          ownerPhone: ownerPhone.trim(),
        };
        if (ownerUsername.trim()) payload.ownerUsername = ownerUsername.trim();
        if (ownerPassword.trim()) payload.ownerPassword = ownerPassword.trim();
        if (ownerRoleId) payload.ownerRole = ownerRoleId;

        const res = await DataService.post("/admin/clients", payload);
        const secret = res.data?.clientSecret as string | undefined;
        const newClientId = (res.data?.data?.clientId as string | undefined) || "";
        const initialUser = res.data?.initialUser as
          | {
              username: string;
              email: string;
              firstName: string;
              lastName: string;
              phone?: string;
              roleName: string | null;
              temporaryPassword: string;
            }
          | undefined;
        if (secret) {
          setSecretDialog({
            title: "Client created — copy API and login details now",
            clientId: newClientId,
            clientSecret: secret,
            ...(initialUser ? { initialUser } : {}),
          });
        }
        toast.success(
          initialUser
            ? "Client and tenant owner user created"
            : "Client created (ID and secret auto-generated)"
        );
      }
      setOpen(false);
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not save client"));
    }
  };

  const regenerate = async (c: ClientRow) => {
    if (!confirm(`Regenerate secret for ${c.name}? The old secret will stop working.`)) return;
    try {
      const res = await DataService.post(`/admin/clients/${c._id}/regenerate-secret`);
      const secret = res.data?.clientSecret as string | undefined;
      if (secret) {
        setSecretDialog({
          title: "New client secret",
          clientId: c.clientId,
          clientSecret: secret,
        });
      }
      toast.success("Secret regenerated");
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Failed to regenerate secret"));
    }
  };

  const remove = async (c: ClientRow) => {
    if (!confirm(`Delete client ${c.name}?`)) return;
    try {
      await DataService.delete(`/admin/clients/${c._id}`);
      toast.success("Client deleted");
      load();
    } catch (e) {
      toast.error(getApiErrorMessage(e, "Could not delete client"));
    }
  };

  if (!ready || loading) {
    return (
      <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>
    );
  }

  return (
    <div>
      <MainTitle title="API clients (Super admin)">
        <Button onClick={openCreate}>Add client</Button>
      </MainTitle>

      <p className="mb-4 max-w-3xl text-sm text-gray-600">
        New clients get a random <strong>client ID</strong> and <strong>client secret</strong>{" "}
        (prefixes <code className="rounded bg-gray-100 px-1">cid_</code> and{" "}
        <code className="rounded bg-gray-100 px-1">cs_</code>). Secrets are stored hashed; copy
        them once from the dialog. Use &quot;New secret&quot; to rotate.
      </p>

      {/* Mobile: stacked cards */}
      <div className="space-y-3 md:hidden">
        {clients.length === 0 ? (
          <div className="rounded-md border border-dashed bg-gray-50/80 py-10 text-center text-sm text-gray-500">
            No clients
          </div>
        ) : (
          clients.map((c) => (
            <Card key={c._id} className="overflow-hidden border shadow-sm">
              <CardContent className="space-y-3 p-4">
                <div>
                  <p className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">
                    Name
                  </p>
                  <p className="font-medium text-gray-900">{c.name}</p>
                </div>
                <div className="min-w-0">
                  <p className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">
                    Client ID
                  </p>
                  <div className="flex min-w-0 items-center gap-2">
                    <button
                      type="button"
                      className="min-w-0 flex-1 cursor-pointer break-all rounded-sm border-0 bg-transparent p-0 text-left font-mono text-[11px] leading-snug text-gray-800 hover:bg-gray-100 hover:underline focus-visible:outline focus-visible:ring-2 focus-visible:ring-primary/40"
                      onClick={() => copyClientId(c.clientId, c._id)}
                      title="Click to copy Client ID"
                    >
                      {c.clientId}
                    </button>
                    <Button
                      type="button"
                      variant="outline"
                      size="icon"
                      className="m-0 size-8 shrink-0 p-0"
                      title="Copy Client ID"
                      aria-label="Copy Client ID"
                      onClick={() => copyClientId(c.clientId, c._id)}
                    >
                      {copiedRowId === c._id ? (
                        <Check className="size-3.5 text-green-600" strokeWidth={2.5} />
                      ) : (
                        <Copy className="size-3.5" />
                      )}
                    </Button>
                  </div>
                </div>
                <div>
                  <p className="text-[11px] font-semibold uppercase tracking-wide text-gray-500">
                    Modules
                  </p>
                  <p className="text-sm text-gray-700">{formatModulesLabel(c.enabledModules)}</p>
                </div>
                <div className="flex flex-wrap items-center justify-between gap-2 border-t pt-3">
                  <span className="inline-flex rounded-full bg-gray-100 px-2.5 py-0.5 text-xs capitalize text-gray-800">
                    {c.status}
                  </span>
                  <div className="flex flex-wrap justify-end gap-2">
                    <Button
                      variant="outline"
                      size="icon"
                      className="shrink-0"
                      onClick={() => openEdit(c)}
                      aria-label="Edit client"
                    >
                      <Pencil className="size-4" />
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="shrink-0"
                      onClick={() => regenerate(c)}
                    >
                      <KeyRound className="size-4 mr-1" />
                      New secret
                    </Button>
                    <Button
                      variant="outline"
                      size="icon"
                      className="shrink-0"
                      onClick={() => remove(c)}
                      aria-label="Delete client"
                    >
                      <Trash2 className="size-4 text-red-600" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      {/* Tablet/desktop: horizontal scroll + table */}
      <div className="hidden md:block">
        <div className="overflow-x-auto rounded-md border bg-white [-webkit-overflow-scrolling:touch]">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="min-w-[120px] whitespace-nowrap">Name</TableHead>
                <TableHead className="min-w-[200px] max-w-[min(40vw,28rem)]">Client ID</TableHead>
                <TableHead className="min-w-[160px]">Modules</TableHead>
                <TableHead className="whitespace-nowrap">Status</TableHead>
                <TableHead className="min-w-[200px] text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {clients.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={5} className="text-center text-gray-400">
                    No clients
                  </TableCell>
                </TableRow>
              ) : (
                clients.map((c) => (
                  <TableRow key={c._id}>
                    <TableCell className="align-top font-medium">{c.name}</TableCell>
                    <TableCell className="align-middle">
                      <div className="flex max-w-md items-center gap-2">
                        <button
                          type="button"
                          className="min-w-0 flex-1 cursor-pointer break-all text-left font-mono text-xs leading-normal text-gray-900 hover:underline focus-visible:outline focus-visible:ring-2 focus-visible:ring-primary/40"
                          onClick={() => copyClientId(c.clientId, c._id)}
                          title="Click to copy Client ID"
                        >
                          {c.clientId}
                        </button>
                        <Button
                          type="button"
                          variant="ghost"
                          size="icon"
                          className="m-0 size-8 shrink-0 p-0 text-gray-600 hover:text-gray-900"
                          title="Copy Client ID"
                          aria-label="Copy Client ID"
                          onClick={() => copyClientId(c.clientId, c._id)}
                        >
                          {copiedRowId === c._id ? (
                            <Check className="size-4 text-green-600" strokeWidth={2.5} />
                          ) : (
                            <Copy className="size-4" />
                          )}
                        </Button>
                      </div>
                    </TableCell>
                    <TableCell className="align-top text-xs text-gray-600">
                      {formatModulesLabel(c.enabledModules)}
                    </TableCell>
                    <TableCell className="align-top whitespace-nowrap capitalize">{c.status}</TableCell>
                    <TableCell className="align-top">
                      <div className="flex flex-wrap justify-end gap-2">
                        <Button variant="outline" size="icon" onClick={() => openEdit(c)}>
                          <Pencil className="size-4" />
                        </Button>
                        <Button variant="outline" size="sm" onClick={() => regenerate(c)}>
                          <KeyRound className="size-4 mr-1" />
                          New secret
                        </Button>
                        <Button variant="outline" size="icon" onClick={() => remove(c)}>
                          <Trash2 className="size-4 text-red-600" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-h-[min(90vh,800px)] overflow-y-auto sm:max-w-xl">
          <DialogHeader>
            <DialogTitle>{editing ? "Edit client" : "Add client"}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-3 py-2">
            <div className="grid gap-2">
              <Label htmlFor="cname">Business name</Label>
              <Input
                id="cname"
                value={formName}
                onChange={(e) => setFormName(e.target.value)}
                placeholder="e.g. Muhammad Arcade"
              />
            </div>
            {!editing && (
              <>
                <p className="text-xs text-gray-500">
                  Creates the <strong>API client</strong> and a <strong>tenant user</strong> linked to it.
                  Client ID, secret, and password (if auto-generated) are shown once after create.
                </p>
                <div className="rounded-md border bg-gray-50/80 p-3">
                  <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-gray-600">
                    Tenant owner (login)
                  </p>
                  <div className="grid gap-3 sm:grid-cols-2">
                    <div className="grid gap-2 sm:col-span-2">
                      <Label htmlFor="ownerEmail">Email</Label>
                      <Input
                        id="ownerEmail"
                        type="email"
                        value={ownerEmail}
                        onChange={(e) => setOwnerEmail(e.target.value)}
                        placeholder="owner@company.com"
                        autoComplete="off"
                      />
                    </div>
                    <div className="grid gap-2">
                      <Label htmlFor="ownerFirst">First name</Label>
                      <Input
                        id="ownerFirst"
                        value={ownerFirstName}
                        onChange={(e) => setOwnerFirstName(e.target.value)}
                        placeholder="Optional"
                      />
                    </div>
                    <div className="grid gap-2">
                      <Label htmlFor="ownerLast">Last name</Label>
                      <Input
                        id="ownerLast"
                        value={ownerLastName}
                        onChange={(e) => setOwnerLastName(e.target.value)}
                        placeholder="Optional (defaults to Owner)"
                      />
                    </div>
                    <div className="grid gap-2 sm:col-span-2">
                      <Label htmlFor="ownerPhone">Phone</Label>
                      <Input
                        id="ownerPhone"
                        type="tel"
                        value={ownerPhone}
                        onChange={(e) => setOwnerPhone(e.target.value)}
                        placeholder="Optional"
                      />
                    </div>
                    <div className="grid gap-2 sm:col-span-2">
                      <Label htmlFor="ownerUser">Username</Label>
                      <Input
                        id="ownerUser"
                        value={ownerUsername}
                        onChange={(e) => setOwnerUsername(e.target.value)}
                        placeholder="Optional — generated from name if empty"
                        autoComplete="off"
                      />
                    </div>
                    <div className="grid gap-2 sm:col-span-2">
                      <div className="flex flex-wrap items-end gap-2">
                        <div className="min-w-0 flex-1 grid gap-2">
                          <Label htmlFor="ownerPwd">Password</Label>
                          <PasswordInput
                            id="ownerPwd"
                            value={ownerPassword}
                            onChange={(e) => setOwnerPassword(e.target.value)}
                            placeholder="Leave blank to auto-generate"
                            autoComplete="new-password"
                          />
                        </div>
                        <Button
                          type="button"
                          variant="outline"
                          className="shrink-0"
                          onClick={() => setOwnerPassword(generateRandomPassword())}
                        >
                          Generate
                        </Button>
                      </div>
                      <p className="text-[11px] text-gray-500">
                        If set: 8+ characters with upper, lower, number, and special character.
                      </p>
                    </div>
                    <div className="grid gap-2 sm:col-span-2">
                      <Label>Role</Label>
                      <Select
                        value={ownerRoleId || "__default__"}
                        onValueChange={(v) => setOwnerRoleId(v === "__default__" ? "" : v)}
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Default" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="__default__">Default (env / first role)</SelectItem>
                          {roles.map((r) => (
                            <SelectItem key={r._id} value={r._id}>
                              {r.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
              </>
            )}
            <div className="grid gap-2">
              <Label>Enabled modules</Label>
              <div className="flex flex-col gap-2 rounded-md border p-3">
                {MODULE_OPTIONS.map((m) => (
                  <label key={m.id} className="flex cursor-pointer items-center gap-2 text-sm">
                    <input
                      type="checkbox"
                      className="size-4 rounded border-gray-300"
                      checked={formModules.includes(m.id)}
                      onChange={(e) => toggleModule(m.id, e.target.checked)}
                    />
                    {m.label}
                  </label>
                ))}
              </div>
            </div>
            {editing && (
              <div className="grid gap-2">
                <Label>Status</Label>
                <Select
                  value={editing.status}
                  onValueChange={(v) => setEditing({ ...editing, status: v })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">active</SelectItem>
                    <SelectItem value="inactive">inactive</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>
              Cancel
            </Button>
            <Button onClick={save}>{editing ? "Save" : "Create"}</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={!!secretDialog} onOpenChange={() => setSecretDialog(null)}>
        <DialogContent
          className={
            secretDialog?.initialUser ? "max-h-[90vh] overflow-y-auto sm:max-w-xl" : "sm:max-w-lg"
          }
        >
          <DialogHeader>
            <DialogTitle>{secretDialog?.title}</DialogTitle>
          </DialogHeader>
          {secretDialog && (
            <div className="grid gap-4 py-2">
              <p className="text-xs text-amber-800 bg-amber-50 border border-amber-200 rounded-md px-3 py-2">
                Copy and store these values securely. They won&apos;t be shown again in full.
              </p>
              <div className="grid gap-2">
                <Label className="text-gray-700">Client ID</Label>
                <div className="flex items-start gap-2">
                  <code className="min-w-0 flex-1 rounded-md border bg-gray-50 px-3 py-2 font-mono text-xs leading-relaxed break-all">
                    {secretDialog.clientId}
                  </code>
                  <Button
                    type="button"
                    variant="outline"
                    size="icon"
                    className="shrink-0"
                    title="Copy Client ID"
                    aria-label="Copy Client ID"
                    onClick={() => {
                      void navigator.clipboard.writeText(secretDialog.clientId);
                      toast.success("Client ID copied");
                    }}
                  >
                    <Copy className="size-4" />
                  </Button>
                </div>
              </div>
              <div className="grid gap-2">
                <Label className="text-gray-700">Client secret</Label>
                <div className="flex items-start gap-2">
                  <code className="min-w-0 flex-1 rounded-md border bg-gray-50 px-3 py-2 font-mono text-xs leading-relaxed break-all">
                    {secretDialog.clientSecret}
                  </code>
                  <Button
                    type="button"
                    variant="outline"
                    size="icon"
                    className="shrink-0"
                    title="Copy client secret"
                    aria-label="Copy client secret"
                    onClick={() => {
                      void navigator.clipboard.writeText(secretDialog.clientSecret);
                      toast.success("Client secret copied");
                    }}
                  >
                    <Copy className="size-4" />
                  </Button>
                </div>
              </div>

              {secretDialog.initialUser && (
                <div className="space-y-3 border-t pt-4">
                  <p className="text-sm font-medium text-gray-800">Tenant owner user</p>
                  <p className="text-xs text-gray-600">
                    Role:{" "}
                    <span className="font-medium">
                      {secretDialog.initialUser.roleName || "(none)"}
                    </span>
                    {" — "}
                    use these credentials to sign in to HR / Property apps for this client.
                  </p>
                  {[
                    { label: "First name", value: secretDialog.initialUser.firstName },
                    { label: "Last name", value: secretDialog.initialUser.lastName },
                    ...(secretDialog.initialUser.phone
                      ? [{ label: "Phone", value: secretDialog.initialUser.phone }]
                      : []),
                    { label: "Username", value: secretDialog.initialUser.username },
                    { label: "Email", value: secretDialog.initialUser.email },
                    { label: "Password", value: secretDialog.initialUser.temporaryPassword },
                  ].map((row) => (
                    <div key={row.label} className="grid gap-2">
                      <Label className="text-gray-700">{row.label}</Label>
                      <div className="flex items-start gap-2">
                        <code className="min-w-0 flex-1 rounded-md border bg-gray-50 px-3 py-2 font-mono text-xs leading-relaxed break-all">
                          {row.value}
                        </code>
                        <Button
                          type="button"
                          variant="outline"
                          size="icon"
                          className="shrink-0"
                          title={`Copy ${row.label}`}
                          aria-label={`Copy ${row.label}`}
                          onClick={() => {
                            void navigator.clipboard.writeText(row.value);
                            toast.success(`${row.label} copied`);
                          }}
                        >
                          <Copy className="size-4" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
          <DialogFooter className="gap-2 sm:gap-0">
            <Button
              type="button"
              variant="secondary"
              onClick={() => {
                if (!secretDialog) return;
                const lines = [
                  `Client ID: ${secretDialog.clientId}`,
                  `Client secret: ${secretDialog.clientSecret}`,
                ];
                if (secretDialog.initialUser) {
                  const u = secretDialog.initialUser;
                  lines.push(
                    `First name: ${u.firstName}`,
                    `Last name: ${u.lastName}`,
                    ...(u.phone ? [`Phone: ${u.phone}`] : []),
                    `Username: ${u.username}`,
                    `Email: ${u.email}`,
                    `Password: ${u.temporaryPassword}`
                  );
                }
                void navigator.clipboard.writeText(lines.join("\n"));
                toast.success("Copied all credentials");
              }}
            >
              Copy all
            </Button>
            <Button variant="outline" onClick={() => setSecretDialog(null)}>
              Close
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
