"use client"

import { useCallback, useEffect, useMemo, useRef, useState, useTransition } from "react"
import { format } from "date-fns"
import { ptBR } from "date-fns/locale"
import { Controller, FormProvider, useFieldArray, useForm } from "react-hook-form"
import { zodResolver } from "@/lib/zod-resolver"
import {
  IconBuildingSkyscraper,
  IconChevronRight,
  IconFilter,
  IconMapPin,
  IconNotebook,
  IconPencil,
  IconPlus,
  IconCopy,
  IconSearch,
  IconTrash,
  IconUserPlus,
  IconUsers,
  IconBuildingOff,
  IconUserOff,
} from "@tabler/icons-react"
import { toast } from "sonner"
import { useQuery, useMutation } from "convex/react"
import { useAuth } from "@/lib/auth-client"
import type { Id } from "@/convex/_generated/dataModel"
import { api } from "@/convex/_generated/api"

import {
  COMPANY_CONTACT_ROLES,
  COMPANY_CONTRACT_SCOPES,
  COMPANY_CONTRACT_TYPES,
  COMPANY_LOCATION_TYPES,
  companyFormSchema,
  type CompanyContact,
  type CompanyContract,
  type CompanyFormValues,
  type CompanyLocation,
} from "@/lib/schemas/company"
import type { NormalizedCompany } from "@/server/company-service"
import { cn } from "@/lib/utils"
import type { RoleOption } from "@/lib/authz"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Checkbox } from "@/components/ui/checkbox"
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { MultiValueInput } from "@/components/ui/multi-value-input"
import { DatePicker } from "@/components/ui/date-picker"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Textarea } from "@/components/ui/textarea"
import { Badge } from "@/components/ui/badge"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { EmptyIndicator } from "@/components/ui/empty-indicator"
import { Skeleton } from "@/components/ui/skeleton"

export type AdminAccount = {
  id: string
  email: string
  name: string
  role: "MANAGER" | "COLLABORATOR"
  companyId: string | null
  companyName: string | null
  jobTitle: string | null
  managerId: string | null
  managerName: string | null
  managerEmail: string | null
  tenantId: string
  createdAt: string
  updatedAt: string
  authUserId: string | null
  lastSeenAt: string | null
}

type Props = {
  initialAccounts: AdminAccount[]
  companies: NormalizedCompany[]
  tenantId: string
  autoOpenCreate?: boolean
}

type SectionEditorState =
  | null
  | {
      section: "contacts" | "locations" | "contracts"
      company: NormalizedCompany
    }

const ROLE_LABEL: Record<AdminAccount["role"], string> = {
  MANAGER: "Gestor",
  COLLABORATOR: "Colaborador",
}

const ROLE_TO_OPTION: Record<AdminAccount["role"], RoleOption> = {
  MANAGER: "manager",
  COLLABORATOR: "collaborator",
}

const ROLE_OPTIONS_DISPLAY: ReadonlyArray<{ value: AdminAccount["role"]; label: string }> = [
  { value: "MANAGER", label: "Gestor" },
  { value: "COLLABORATOR", label: "Colaborador" },
]

const DEFAULT_CREATE_ROLE: AdminAccount["role"] = "COLLABORATOR"

const NO_COMPANY_SELECT_VALUE = "__none__"
const NO_MANAGER_SELECT_VALUE = "__no_manager__"

const NO_CONTACT_VALUE = "__none__"

type CreateAccountFormState = {
  name: string
  email: string
  role: AdminAccount["role"]
  companyId: string
  jobTitle: string
  managerId: string
}

function createDefaultAccountForm(): CreateAccountFormState {
  return {
    name: "",
    email: "",
    role: DEFAULT_CREATE_ROLE,
    companyId: NO_COMPANY_SELECT_VALUE,
    jobTitle: "",
    managerId: NO_MANAGER_SELECT_VALUE,
  }
}

function createId(prefix: string) {
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
    return `${prefix}-${crypto.randomUUID()}`
  }
  return `${prefix}-${Math.random().toString(36).slice(2, 10)}`
}

function formatDate(value: string | null) {
  if (!value) return "Nunca"
  const parsed = new Date(value)
  return format(parsed, "dd/MM/yy HH:mm", { locale: ptBR })
}

function FieldError({ message }: { message?: string }) {
  if (!message) return null
  return <p className="text-xs font-medium text-destructive">{message}</p>
}

export function AdminUsersWorkspace({ initialAccounts, companies, tenantId, autoOpenCreate = false }: Props) {
  const [tab, setTab] = useState<"accounts" | "structure">("accounts")
  return (
    <Tabs value={tab} onValueChange={(value) => setTab(value as typeof tab)}>
      <TabsList className="mb-6">
        <TabsTrigger value="accounts">Usuários com acesso</TabsTrigger>
        <TabsTrigger value="structure">Estrutura das empresas</TabsTrigger>
      </TabsList>
      <TabsContent value="accounts">
        <AccountsTable
          initialAccounts={initialAccounts}
          companies={companies}
          tenantId={tenantId}
          autoOpenCreate={autoOpenCreate}
        />
      </TabsContent>
      <TabsContent value="structure">
        <CompanyStructurePanel initialCompanies={companies} />
      </TabsContent>
    </Tabs>
  )
}

function AccountsTable({
  initialAccounts,
  companies,
  tenantId,
  autoOpenCreate,
}: {
  initialAccounts: AdminAccount[]
  companies: NormalizedCompany[]
  tenantId: string
  autoOpenCreate?: boolean
}) {
  const [accounts, setAccounts] = useState(initialAccounts)
  const [search, setSearch] = useState("")
  const [roleFilter, setRoleFilter] = useState<"all" | AdminAccount["role"]>("all")
  const [companyFilter, setCompanyFilter] = useState<string>("all")
  const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({})
  const [isPending, startTransition] = useTransition()
  const [deleteDialogIds, setDeleteDialogIds] = useState<string[]>([])
  const [editAccountId, setEditAccountId] = useState<string | null>(null)
  const [editAuthUserId, setEditAuthUserId] = useState<string | null>(null)
  const [editForm, setEditForm] = useState({
    name: "",
    email: "",
    role: "COLLABORATOR" as AdminAccount["role"],
    companyId: "",
    jobTitle: "",
    managerId: "",
  })
  const [isSavingAccount, setIsSavingAccount] = useState(false)
  const [isResettingPassword, setIsResettingPassword] = useState(false)
  const [passwordPreview, setPasswordPreview] = useState<string | null>(null)
  const [createDialogOpen, setCreateDialogOpen] = useState(false)
  const autoOpenHandledRef = useRef(false)
  const [isCreatingAccount, setIsCreatingAccount] = useState(false)
  const [createForm, setCreateForm] = useState<CreateAccountFormState>(() => createDefaultAccountForm())

  const effectiveTenantId = tenantId || DEFAULT_TENANT_ID

  const headerCellClass =
    "px-3 py-3 text-[11px] font-semibold uppercase tracking-wide text-neutral-600 first:pl-4 last:pr-4"
  const cellClass =
    "px-3 py-4 text-sm text-neutral-700 first:pl-4 last:pr-4 whitespace-pre-wrap leading-snug"
  const rowClass = "border-b border-border/60 text-sm transition-colors hover:bg-muted/40 last:border-b-0"
  const metaLabelClass =
    "text-[11px] font-semibold uppercase tracking-wide text-neutral-500"
  const metaValueClass = "text-sm text-neutral-600 leading-tight break-words"

  const filteredAccounts = useMemo(() => {
    const term = search.trim().toLowerCase()
    return accounts.filter((account) => {
      if (roleFilter !== "all" && account.role !== roleFilter) return false
      if (companyFilter !== "all" && account.companyId !== companyFilter) return false
      if (!term) return true
      return (
        account.name.toLowerCase().includes(term) ||
        account.email.toLowerCase().includes(term) ||
        (account.jobTitle ?? "").toLowerCase().includes(term) ||
        (account.managerName ?? "").toLowerCase().includes(term) ||
        (account.managerEmail ?? "").toLowerCase().includes(term) ||
        (account.companyName ?? "").toLowerCase().includes(term)
      )
    })
  }, [accounts, roleFilter, companyFilter, search])

  const selectedIds = useMemo(
    () => Object.entries(rowSelection).filter(([, selected]) => selected).map(([id]) => id),
    [rowSelection]
  )

  const visibleSelectedCount = useMemo(
    () => filteredAccounts.reduce((total, account) => total + (rowSelection[account.id] ? 1 : 0), 0),
    [filteredAccounts, rowSelection],
  )

  const allVisibleSelected = filteredAccounts.length > 0 && visibleSelectedCount === filteredAccounts.length
  const isVisibleIndeterminate = visibleSelectedCount > 0 && visibleSelectedCount < filteredAccounts.length

  const editAccount = useMemo(
    () => (editAccountId ? accounts.find((account) => account.id === editAccountId) ?? null : null),
    [accounts, editAccountId]
  )

  // Tipos de solicitação por usuário
  const { convexUserId } = useAuth()
  const formSettings = useQuery(
    api.ticketFormSettings.list,
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as Array<{ template: string; scope: string; userId?: string | null; enabled: boolean; updatedAt: number }> | undefined
  const templates = useQuery(
    api.ticketFormTemplates.listActive,
    convexUserId ? { tenantId, viewerId: convexUserId as Id<"users"> } : "skip"
  ) as Array<{ key: string; label: string }> | undefined
  const upsertFormSetting = useMutation(api.ticketFormSettings.upsert)
  const ensureTicketForms = useMutation(api.tickets.ensureTicketFormDefaults)
  const ensuredRef = useRef(false)

  useEffect(() => {
    if (!convexUserId || ensuredRef.current) return
    ensuredRef.current = true
    ensureTicketForms({ tenantId, actorId: convexUserId as Id<"users"> }).catch((error) => {
      console.error("Falha ao garantir formulários padrão", error)
      ensuredRef.current = false
    })
  }, [convexUserId, ensureTicketForms, tenantId])

  const resolveUserFormEnabled = useCallback((template: string) => {
    if (!editAccount) return true
    const scoped = (formSettings ?? []).filter((s) => s.template === template)
    const latest = scoped
      .filter((s) => s.scope === "user" && String(s.userId ?? "") === String(editAccount.id))
      .sort((a, b) => b.updatedAt - a.updatedAt)[0]
    return typeof latest?.enabled === "boolean" ? latest.enabled : true
  }, [formSettings, editAccount])

  const handleToggleUserForm = useCallback(async (template: string, enabled: boolean) => {
    if (!convexUserId || !editAccount) return
    try {
      await upsertFormSetting({
        tenantId,
        actorId: convexUserId as Id<"users">,
        template,
        scope: "user",
        userId: editAccount.id as unknown as Id<"users">,
        enabled,
      })
      toast.success("Configuração salva.")
    } catch (error) {
      console.error("Falha ao salvar configuração de formulário por usuário", error)
      toast.error("Não foi possível salvar a configuração.")
    }
  }, [tenantId, convexUserId, editAccount, upsertFormSetting])

  const roleSelectOptions = useMemo<SearchableComboboxOption[]>(
    () => ROLE_OPTIONS_DISPLAY.map((option) => ({ value: option.value, label: option.label })),
    [],
  )

  const roleFilterOptions = useMemo<SearchableComboboxOption[]>(
    () => [{ value: "all", label: "Todos os papéis" }, ...roleSelectOptions],
    [roleSelectOptions],
  )

  const companyFilterOptions = useMemo<SearchableComboboxOption[]>(
    () => [
      { value: "all", label: "Todas as empresas" },
      ...companies.map((company) => ({ value: company.id, label: company.name })),
    ],
    [companies],
  )

  const editCompanyOptions = useMemo<SearchableComboboxOption[]>(
    () => [
      { value: NO_COMPANY_SELECT_VALUE, label: "Sem empresa vinculada" },
      ...companies.map((company) => ({ value: company.id, label: company.name })),
    ],
    [companies],
  )

  const managerOptions = useMemo<SearchableComboboxOption[]>(() => {
    const base: SearchableComboboxOption[] = [
      { value: NO_MANAGER_SELECT_VALUE, label: "Sem gestor", keywords: ["nenhum", "sem"] },
    ]
    const managers = accounts
      .filter((account) => account.role === "MANAGER")
      .map((manager) => {
        const keywords: string[] = [manager.email]
        if (manager.jobTitle) {
          keywords.push(manager.jobTitle)
        }
        return {
          value: manager.id,
          label: manager.name,
          description: manager.jobTitle ? `${manager.jobTitle} • ${manager.email}` : manager.email,
          keywords,
        }
      })
    return [...base, ...managers]
  }, [accounts])

  const editManagerOptions = useMemo<SearchableComboboxOption[]>(() => {
    if (!editAccountId) return managerOptions
    return managerOptions.filter(
      (option) => option.value === NO_MANAGER_SELECT_VALUE || option.value !== editAccountId,
    )
  }, [managerOptions, editAccountId])

  const openDeleteDialog = useCallback((ids: string[]) => {
    setDeleteDialogIds(ids)
  }, [])

  const closeDeleteDialog = useCallback(() => setDeleteDialogIds([]), [])

  const toggleVisibleSelection = useCallback(
    (checked: boolean) => {
      setRowSelection((prev) => {
        const next = { ...prev }
        filteredAccounts.forEach((account) => {
          next[account.id] = checked
        })
        return next
      })
    },
    [filteredAccounts],
  )

  const closeEditor = useCallback(() => {
    setEditAccountId(null)
    setEditAuthUserId(null)
    setPasswordPreview(null)
  }, [])

  const handleOpenCreateDialog = useCallback(() => {
    setCreateForm(createDefaultAccountForm())
    setCreateDialogOpen(true)
  }, [])

  const handleCloseCreateDialog = useCallback(() => {
    setCreateDialogOpen(false)
    setCreateForm(createDefaultAccountForm())
  }, [])

  useEffect(() => {
    if (!autoOpenCreate || autoOpenHandledRef.current) return
    autoOpenHandledRef.current = true
    setCreateForm(createDefaultAccountForm())
    setCreateDialogOpen(true)
  }, [autoOpenCreate])

  useEffect(() => {
    if (typeof window === "undefined") return
    const handler = () => {
      handleOpenCreateDialog()
    }
    window.addEventListener("quick-open-user", handler)
    return () => window.removeEventListener("quick-open-user", handler)
  }, [handleOpenCreateDialog])

  useEffect(() => {
    if (editAccount) {
      setEditForm({
        name: editAccount.name,
        email: editAccount.email,
        role: editAccount.role,
        companyId: editAccount.companyId ?? "",
        jobTitle: editAccount.jobTitle ?? "",
        managerId: editAccount.managerId ?? "",
      })
    } else {
      setEditForm({
        name: "",
        email: "",
        role: "COLLABORATOR" as AdminAccount["role"],
        companyId: "",
        jobTitle: "",
        managerId: "",
      })
    }
  }, [editAccount])

  const refreshAccounts = useCallback(async () => {
    try {
      const response = await fetch("/api/admin/users", { credentials: "include", cache: "no-store" })
      if (!response.ok) {
        const payload = await response.json().catch(() => null)
        throw new Error(payload?.error ?? "Não foi possível atualizar a lista de usuários.")
      }
      const data = (await response.json()) as { items: Array<AdminAccount & { name: string | null }> }
      setAccounts(
        data.items.map((item) => ({
          ...item,
          name: item.name ?? item.email,
        })),
      )
    } catch (error) {
      const message = error instanceof Error ? error.message : "Falha ao atualizar usuários."
      toast.error(message)
    }
  }, [])

  const handleOpenEditor = useCallback((account: AdminAccount) => {
    if (!account.authUserId) {
      toast.error("Não foi possível localizar o perfil de acesso para este usuário.")
      return
    }
    setEditAccountId(account.id)
    setEditAuthUserId(account.authUserId)
    setPasswordPreview(null)
  }, [])

  const handleSaveAccount = useCallback(
    async (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault()
      if (!editAccount || !editAuthUserId) {
        toast.error("Nenhum usuário selecionado.")
        return
      }

      const jobTitleValue = editForm.jobTitle.trim()
      const managerIdValue = editForm.managerId ? editForm.managerId : null
      if (managerIdValue && managerIdValue === editAccount.id) {
        toast.error("Um usuário não pode ser gestor de si mesmo.")
        return
      }

      const payload = {
        name: editForm.name.trim(),
        email: editForm.email.trim().toLowerCase(),
        role: ROLE_TO_OPTION[editForm.role] ?? "collaborator",
        tenantId: editAccount.tenantId,
        companyId: editForm.companyId ? editForm.companyId : null,
        jobTitle: jobTitleValue.length > 0 ? jobTitleValue : null,
        managerId: managerIdValue,
      }

      if (!payload.name) {
        toast.error("Informe o nome do usuário.")
        return
      }
      if (!payload.email || !payload.email.includes("@")) {
        toast.error("Informe um e-mail válido.")
        return
      }

      setIsSavingAccount(true)
      try {
        const response = await fetch(`/api/admin/users/${editAuthUserId}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify(payload),
        })
        if (!response.ok) {
          const data = await response.json().catch(() => null)
          throw new Error(data?.error ?? "Não foi possível salvar as alterações.")
        }
        await refreshAccounts()
        toast.success("Usuário atualizado com sucesso.")
        closeEditor()
      } catch (error) {
        const message = error instanceof Error ? error.message : "Erro ao salvar usuário."
        toast.error(message)
      } finally {
        setIsSavingAccount(false)
      }
    },
    [editAccount, editAuthUserId, editForm, refreshAccounts, closeEditor]
  )

  const handleResetPassword = useCallback(async () => {
    if (!editAuthUserId) {
      toast.error("Usuário inválido para gerar senha.")
      return
    }
    setIsResettingPassword(true)
    toast.loading("Gerando nova senha...", { id: "admin-users-reset-password" })
    try {
      const response = await fetch(`/api/admin/users/${editAuthUserId}/reset-password`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "include",
      })
      if (!response.ok) {
        const data = await response.json().catch(() => null)
        throw new Error(data?.error ?? "Falha ao gerar senha temporária.")
      }
      const data = (await response.json()) as { temporaryPassword: string }
      setPasswordPreview(data.temporaryPassword)
      toast.success("Senha temporária criada com sucesso.", { id: "admin-users-reset-password" })
    } catch (error) {
      const message = error instanceof Error ? error.message : "Erro ao gerar senha."
      toast.error(message, { id: "admin-users-reset-password" })
    } finally {
      setIsResettingPassword(false)
    }
  }, [editAuthUserId])

  const handleCreateAccount = useCallback(
    async (event: React.FormEvent<HTMLFormElement>) => {
      event.preventDefault()
      const name = createForm.name.trim()
      const email = createForm.email.trim().toLowerCase()
      if (!name) {
        toast.error("Informe o nome do usuário.")
        return
      }
      if (!email || !email.includes("@")) {
        toast.error("Informe um e-mail válido.")
        return
      }

      const jobTitleValue = createForm.jobTitle.trim()
      const managerId =
        createForm.managerId && createForm.managerId !== NO_MANAGER_SELECT_VALUE ? createForm.managerId : null

      const payload = {
        name,
        email,
        role: ROLE_TO_OPTION[createForm.role] ?? "collaborator",
        tenantId: effectiveTenantId,
        jobTitle: jobTitleValue.length > 0 ? jobTitleValue : null,
        managerId,
      }

      setIsCreatingAccount(true)
      try {
        const response = await fetch("/api/admin/users", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          credentials: "include",
          body: JSON.stringify(payload),
        })
        if (!response.ok) {
          const data = await response.json().catch(() => null)
          throw new Error(data?.error ?? "Não foi possível criar o usuário.")
        }
        const data = (await response.json()) as { user: { email: string }; temporaryPassword?: string }

        let assignError: string | null = null
        if (createForm.companyId && createForm.companyId !== NO_COMPANY_SELECT_VALUE) {
          const assignResponse = await fetch("/api/admin/users/assign-company", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            credentials: "include",
            body: JSON.stringify({ email, companyId: createForm.companyId }),
          })
          if (!assignResponse.ok) {
            const assignData = await assignResponse.json().catch(() => null)
            assignError = assignData?.error ?? "Usuário criado, mas não foi possível vincular a empresa."
          }
        }

        await refreshAccounts()
        setCreateForm(createDefaultAccountForm())
        setCreateDialogOpen(false)
        toast.success("Usuário criado com sucesso.", {
          description: data.temporaryPassword ? `Senha temporária: ${data.temporaryPassword}` : undefined,
          action: data.temporaryPassword
            ? {
                label: "Copiar",
                onClick: async () => {
                  try {
                    await navigator.clipboard?.writeText?.(data.temporaryPassword ?? "")
                    toast.success("Senha copiada para a área de transferência.")
                  } catch (error) {
                    const message = error instanceof Error ? error.message : "Não foi possível copiar a senha."
                    toast.error(message)
                  }
                },
              }
            : undefined,
        })
        if (assignError) {
          toast.error(assignError)
        }
      } catch (error) {
        const message = error instanceof Error ? error.message : "Erro ao criar usuário."
        toast.error(message)
      } finally {
        setIsCreatingAccount(false)
      }
    },
    [createForm, effectiveTenantId, refreshAccounts]
  )

  const handleDelete = useCallback(
    (ids: string[]) => {
      if (ids.length === 0) return
      startTransition(async () => {
        try {
          const response = await fetch("/api/admin/users", {
            method: "DELETE",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ ids }),
          })
          if (!response.ok) {
            const payload = await response.json().catch(() => null)
            throw new Error(payload?.error ?? "Não foi possível excluir os usuários selecionados.")
          }
          const json = (await response.json()) as { deletedIds: string[] }
          setAccounts((prev) => prev.filter((account) => !json.deletedIds.includes(account.id)))
          setRowSelection({})
          setDeleteDialogIds([])
          toast.success(
            json.deletedIds.length === 1
              ? "Usuário removido com sucesso."
              : `${json.deletedIds.length} usuários removidos com sucesso.`,
          )
        } catch (error) {
          const message =
            error instanceof Error ? error.message : "Não foi possível excluir os usuários selecionados."
          toast.error(message)
        }
      })
    },
    [startTransition],
  )

  return (
    <>
      <Card>
      <CardHeader className="pb-3">
        <CardTitle className="text-base font-semibold">Usuários do cliente</CardTitle>
        <CardDescription>Gestores e colaboradores com acesso ao portal de chamados.</CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
          <div className="flex flex-1 flex-wrap gap-3">
            <div className="relative flex-1 min-w-[16rem]">
              <IconSearch className="pointer-events-none absolute left-3 top-2.5 size-4 text-muted-foreground" />
              <Input
                value={search}
                onChange={(event) => setSearch(event.target.value)}
                placeholder="Buscar por nome, e-mail ou empresa..."
                className="pl-9"
              />
            </div>
            <div className="flex flex-wrap gap-3">
            <div className="flex items-center gap-2 text-muted-foreground">
              <IconFilter className="size-4" />
              <SearchableCombobox
                value={roleFilter}
                onValueChange={(next) => {
                  const normalized =
                    next === "MANAGER" || next === "COLLABORATOR" ? next : "all"
                  setRoleFilter(normalized)
                }}
                options={roleFilterOptions}
                placeholder="Todos os papéis"
                searchPlaceholder="Buscar papel..."
                className="md:w-[12rem]"
              />
            </div>
            <SearchableCombobox
              value={companyFilter}
              onValueChange={(next) => setCompanyFilter(next ?? "all")}
              options={companyFilterOptions}
              placeholder="Todas as empresas"
              searchPlaceholder="Buscar empresa..."
              className="md:w-[16rem]"
            />
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button type="button" className="gap-2" onClick={handleOpenCreateDialog}>
            <IconUserPlus className="size-4" />
            Novo usuário
          </Button>
          <Button
            variant="destructive"
            disabled={selectedIds.length === 0 || isPending}
            onClick={() => openDeleteDialog(selectedIds)}
          >
            <IconTrash className="mr-2 size-4" />
            Remover
          </Button>
        </div>
        </div>

        <div className="w-full overflow-hidden rounded-2xl border border-border/60 bg-background">
          <Table className="w-full text-sm">
            <TableHeader className="bg-muted/60">
              <TableRow className="bg-transparent">
                <TableHead className="w-12 px-3">
                  <Checkbox
                    checked={isVisibleIndeterminate ? "indeterminate" : allVisibleSelected}
                    onCheckedChange={(checked) => toggleVisibleSelection(checked === true)}
                    aria-label="Selecionar todos os usuários visíveis"
                  />
                </TableHead>
                <TableHead className={cn(headerCellClass, "text-center min-w-[220px]")}>Usuário</TableHead>
                <TableHead className={cn(headerCellClass, "hidden xl:table-cell text-center")}>Cargo</TableHead>
                <TableHead className={cn(headerCellClass, "hidden lg:table-cell text-center")}>Gestor</TableHead>
                <TableHead className={cn(headerCellClass, "hidden md:table-cell text-center")}>Empresa</TableHead>
                <TableHead className={cn(headerCellClass, "text-center")}>Papel</TableHead>
                <TableHead className={cn(headerCellClass, "text-center")}>Último acesso</TableHead>
                <TableHead className={cn(headerCellClass, "text-center")}>Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filteredAccounts.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={8} className={cn(cellClass, "text-center text-sm text-muted-foreground")}>
                    Nenhum usuário encontrado.
                  </TableCell>
                </TableRow>
              ) : (
                filteredAccounts.map((account) => {
                  const initials = account.name
                    .split(" ")
                    .filter(Boolean)
                    .slice(0, 2)
                    .map((part) => part.charAt(0).toUpperCase())
                    .join("")
                  return (
                    <TableRow key={account.id} className={rowClass}>
                      <TableCell className="w-12 px-3 py-4 align-middle">
                        <Checkbox
                          checked={rowSelection[account.id] ?? false}
                          onCheckedChange={(checked) =>
                            setRowSelection((prev) => ({ ...prev, [account.id]: checked === true }))
                          }
                          aria-label={`Selecionar ${account.name}`}
                        />
                      </TableCell>
                      <TableCell className={cn(cellClass, "align-top text-neutral-900")}>
                        <div className="flex flex-col items-center gap-3 text-center sm:max-w-[28ch] sm:items-center sm:justify-center">
                          <div className="min-w-0 space-y-1">
                            <p className="text-base font-semibold leading-tight text-neutral-900 break-words">
                              {account.name}
                            </p>
                            <p className="text-xs text-neutral-500 break-words">{account.email}</p>
                          </div>
                          <div className="mt-1 grid gap-3 xl:hidden">
                            <div className="flex flex-col gap-1">
                              <span className={metaLabelClass}>Cargo</span>
                              <span className={cn(metaValueClass, "max-w-[28ch]")}>
                                {account.jobTitle ?? "Sem cargo"}
                              </span>
                            </div>
                            <div className="flex flex-col gap-1">
                              <span className={metaLabelClass}>Empresa</span>
                              {account.companyName ? (
                                <span className={cn(metaValueClass, "max-w-[28ch]")}>{account.companyName}</span>
                              ) : (
                                <span className={cn(metaValueClass, "flex justify-center")}>
                                  <EmptyIndicator icon={IconBuildingOff} label="Nenhuma empresa vinculada" />
                                </span>
                              )}
                            </div>
                            <div className="flex flex-col gap-1">
                              <span className={metaLabelClass}>Gestor</span>
                              {account.managerName ? (
                                <div className={cn(metaValueClass, "max-w-[28ch] space-y-0.5")}>
                                  <span className="block text-neutral-700">{account.managerName}</span>
                                  {account.managerEmail ? (
                                    <span className="block text-[11px] text-neutral-500 break-words">
                                      {account.managerEmail}
                                    </span>
                                  ) : null}
                                </div>
                              ) : (
                                <span className={cn(metaValueClass, "flex justify-center")}>
                                  <EmptyIndicator icon={IconUserOff} label="Nenhum gestor vinculado" />
                                </span>
                              )}
                            </div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell
                        className={cn(
                          cellClass,
                          "hidden xl:table-cell text-center text-xs text-neutral-600",
                        )}
                      >
                        {account.jobTitle ? (
                          <span className="mx-auto block max-w-[28ch] break-words text-sm font-medium text-neutral-700 leading-snug">
                            {account.jobTitle}
                          </span>
                        ) : (
                          <span className="text-neutral-400">Sem cargo</span>
                        )}
                      </TableCell>
                      <TableCell
                        className={cn(
                          cellClass,
                          "hidden lg:table-cell text-center text-xs text-neutral-600",
                        )}
                      >
                        {account.managerName ? (
                          <div className="mx-auto flex max-w-[28ch] flex-col items-center gap-1">
                            <span className="text-sm font-medium text-neutral-700 leading-tight">
                              {account.managerName}
                            </span>
                            {account.managerEmail ? (
                              <span className="text-[11px] text-neutral-500 break-words leading-tight">
                                {account.managerEmail}
                              </span>
                            ) : null}
                          </div>
                        ) : (
                          <span className="flex justify-center">
                            <EmptyIndicator icon={IconUserOff} label="Nenhum gestor vinculado" />
                          </span>
                        )}
                      </TableCell>
                      <TableCell
                        className={cn(
                          cellClass,
                          "hidden md:table-cell text-center text-xs text-neutral-600",
                        )}
                      >
                        {account.companyName ? (
                          <span className="mx-auto block max-w-[28ch] break-words text-sm text-neutral-700 leading-snug">
                            {account.companyName}
                          </span>
                        ) : (
                          <span className="flex justify-center">
                            <EmptyIndicator icon={IconBuildingOff} label="Nenhuma empresa vinculada" />
                          </span>
                        )}
                      </TableCell>
                      <TableCell className={cn(cellClass, "align-middle text-center text-neutral-700")}>
                        <Badge variant="secondary" className="mx-auto bg-neutral-900 text-white hover:bg-neutral-900">
                          {ROLE_LABEL[account.role]}
                        </Badge>
                      </TableCell>
                      <TableCell
                        className={cn(
                          cellClass,
                          "align-middle text-center text-xs text-neutral-600",
                        )}
                      >
                        {formatDate(account.lastSeenAt)}
                      </TableCell>
                      <TableCell className={cn(cellClass, "align-middle text-center")}>
                        <div className="flex justify-center gap-2">
                          <Button
                            variant="outline"
                            size="icon"
                            disabled={!account.authUserId || isPending}
                            onClick={() => handleOpenEditor(account)}
                            title="Editar usuário"
                          >
                            <IconPencil className="size-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="icon"
                            className="text-rose-600 hover:bg-rose-50 hover:text-rose-700"
                            disabled={isPending}
                            onClick={() => openDeleteDialog([account.id])}
                            title="Remover usuário"
                          >
                            <IconTrash className="size-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  )
                })
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>

      <Dialog open={deleteDialogIds.length > 0} onOpenChange={(open) => (!open ? closeDeleteDialog() : null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Remover usuários</DialogTitle>
            <DialogDescription>
              Os usuários selecionados perderão o acesso ao portal e seus convites ativos serão revogados.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="outline" onClick={closeDeleteDialog}>
              Cancelar
            </Button>
            <Button variant="destructive" onClick={() => handleDelete(deleteDialogIds)}>
              Remover
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Sheet open={Boolean(editAccountId)} onOpenChange={(open) => (!open ? closeEditor() : null)}>
        <SheetContent side="right" className="space-y-6 overflow-y-auto px-6 pb-10 sm:max-w-lg">
          <SheetHeader className="px-0 pt-6">
            <SheetTitle>Editar usuário</SheetTitle>
            <p className="text-sm text-muted-foreground">
              Atualize os dados cadastrais, papel e vínculo do colaborador.
            </p>
          </SheetHeader>

          {editAccount ? (
            <form className="space-y-6" onSubmit={handleSaveAccount}>
              <div className="rounded-lg border border-border/60 bg-muted/40 p-4">
                <p className="text-sm font-semibold text-foreground">{editAccount.name}</p>
                <p className="text-xs text-muted-foreground">{editAccount.email}</p>
                <div className="mt-3 text-xs text-muted-foreground">
                  Essa seleção substitui o vínculo atual no portal do cliente.
                </div>
              </div>

              <div className="grid gap-4">
                <div className="grid gap-2">
                  <Label htmlFor="edit-name">Nome</Label>
                  <Input
                    id="edit-name"
                    value={editForm.name}
                    onChange={(event) => setEditForm((prev) => ({ ...prev, name: event.target.value }))}
                    placeholder="Nome completo"
                    disabled={isSavingAccount}
                    required
                  />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="edit-email">E-mail</Label>
                  <Input
                    id="edit-email"
                    type="email"
                    value={editForm.email}
                    onChange={(event) => setEditForm((prev) => ({ ...prev, email: event.target.value }))}
                    placeholder="usuario@empresa.com"
                    disabled={isSavingAccount}
                    required
                  />
                </div>
                <div className="grid gap-2">
                  <Label>Papel</Label>
                  <SearchableCombobox
                    value={editForm.role}
                    onValueChange={(next) =>
                      setEditForm((prev) => ({
                        ...prev,
                        role: next === "MANAGER" || next === "COLLABORATOR" ? next : prev.role,
                      }))
                    }
                    options={roleSelectOptions}
                    placeholder="Selecione"
                    searchPlaceholder="Buscar papel..."
                    disabled={isSavingAccount}
                  />
                </div>
                <div className="grid gap-2">
                  <Label>Empresa vinculada</Label>
                  <SearchableCombobox
                    value={editForm.companyId || NO_COMPANY_SELECT_VALUE}
                    onValueChange={(next) =>
                      setEditForm((prev) => ({
                        ...prev,
                        companyId: next === NO_COMPANY_SELECT_VALUE || next === null ? "" : next,
                      }))
                    }
                    options={editCompanyOptions}
                    placeholder="Sem empresa vinculada"
                    searchPlaceholder="Buscar empresa..."
                    disabled={isSavingAccount}
                  />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="edit-job-title">Cargo</Label>
                  <Input
                    id="edit-job-title"
                    value={editForm.jobTitle}
                    onChange={(event) => setEditForm((prev) => ({ ...prev, jobTitle: event.target.value }))}
                    placeholder="Cargo ou função"
                    disabled={isSavingAccount}
                  />
                </div>
                <div className="grid gap-2">
                  <Label>Gestor direto</Label>
                  <SearchableCombobox
                    value={editForm.managerId ? editForm.managerId : NO_MANAGER_SELECT_VALUE}
                    onValueChange={(next) =>
                      setEditForm((prev) => ({
                        ...prev,
                        managerId: next === null || next === NO_MANAGER_SELECT_VALUE ? "" : next,
                      }))
                    }
                    options={editManagerOptions}
                    placeholder="Sem gestor definido"
                    searchPlaceholder="Buscar gestor..."
                    allowClear
                    clearLabel="Remover gestor"
                    disabled={isSavingAccount}
                  />
                </div>

                <div className="rounded-lg border border-border/60 bg-muted/20 p-4">
                  <p className="text-sm font-semibold text-foreground">Tipos de solicitação</p>
                  <p className="mb-2 text-xs text-muted-foreground">Disponíveis para este colaborador/gestor no portal. Administradores e agentes sempre veem todas as opções.</p>
                  {!templates ? (
                    <div className="space-y-2">
                      <Skeleton className="h-8 w-full rounded-md" />
                      <Skeleton className="h-8 w-full rounded-md" />
                    </div>
                  ) : templates.length === 0 ? (
                    <p className="text-xs text-neutral-500">Nenhum formulário configurado.</p>
                  ) : (
                    <div className="grid gap-2">
                      {templates.map((template) => (
                        <label key={template.key} className="flex items-center gap-2 text-sm text-foreground">
                          <Checkbox
                            checked={resolveUserFormEnabled(template.key)}
                            onCheckedChange={(v) => handleToggleUserForm(template.key, Boolean(v))}
                            disabled={!editAccount || isSavingAccount}
                          />
                          <span>{template.label}</span>
                        </label>
                      ))}
                    </div>
                  )}
                </div>
              </div>

              <div className="rounded-lg border border-border/60 bg-muted/20 p-4">
                <div className="flex items-start justify-between gap-3">
                  <div>
                    <p className="text-sm font-semibold text-foreground">Gerar nova senha</p>
                    <p className="text-xs text-muted-foreground">
                      Uma senha temporária será exibida abaixo. Compartilhe com o usuário e peça para trocá-la no primeiro acesso.
                    </p>
                  </div>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={handleResetPassword}
                    disabled={isResettingPassword}
                  >
                    {isResettingPassword ? "Gerando..." : "Gerar senha"}
                  </Button>
                </div>
                {passwordPreview ? (
                  <div className="mt-4 flex flex-wrap items-center gap-3 rounded-md border border-dashed border-border/60 bg-background p-3">
                    <code className="text-sm font-semibold text-foreground">{passwordPreview}</code>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => {
                        if (!passwordPreview) return
                        const promise = navigator.clipboard?.writeText(passwordPreview)
                        if (!promise) {
                          toast.error("Não foi possível copiar a senha.")
                          return
                        }
                        promise
                          .then(() => toast.success("Senha copiada para a área de transferência."))
                          .catch(() => toast.error("Não foi possível copiar a senha."))
                      }}
                    >
                      Copiar
                    </Button>
                  </div>
                ) : null}
              </div>

              <SheetFooter className="flex flex-col gap-2 sm:flex-row sm:justify-end">
                <Button type="button" variant="outline" onClick={closeEditor} disabled={isSavingAccount}>
                  Cancelar
                </Button>
                <Button type="submit" disabled={isSavingAccount}>
                  {isSavingAccount ? "Salvando..." : "Salvar alterações"}
                </Button>
              </SheetFooter>
            </form>
          ) : (
            <p className="text-sm text-muted-foreground">Selecione um usuário para visualizar os detalhes.</p>
          )}
        </SheetContent>
      </Sheet>
    </Card>

      <Dialog open={createDialogOpen} onOpenChange={(open) => (!open ? handleCloseCreateDialog() : null)}>
        <DialogContent className="max-w-lg space-y-6">
          <DialogHeader>
            <DialogTitle>Novo usuário</DialogTitle>
            <DialogDescription>
              Crie acessos para gestores ou colaboradores vinculados às empresas cadastradas.
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleCreateAccount} className="space-y-5">
            <div className="grid gap-2">
              <Label htmlFor="create-name">Nome</Label>
              <Input
                id="create-name"
                value={createForm.name}
                onChange={(event) => setCreateForm((prev) => ({ ...prev, name: event.target.value }))}
                placeholder="Nome completo"
                disabled={isCreatingAccount}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="create-email">E-mail</Label>
              <Input
                id="create-email"
                type="email"
                value={createForm.email}
                onChange={(event) => setCreateForm((prev) => ({ ...prev, email: event.target.value }))}
                placeholder="usuario@empresa.com"
                disabled={isCreatingAccount}
                required
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="create-job-title">Cargo</Label>
              <Input
                id="create-job-title"
                value={createForm.jobTitle}
                onChange={(event) => setCreateForm((prev) => ({ ...prev, jobTitle: event.target.value }))}
                placeholder="Ex.: Analista de Suporte"
                disabled={isCreatingAccount}
              />
            </div>
            <div className="grid gap-2">
              <Label>Gestor direto</Label>
              <SearchableCombobox
                value={createForm.managerId}
                onValueChange={(value) =>
                  setCreateForm((prev) => ({
                    ...prev,
                    managerId: value === null ? NO_MANAGER_SELECT_VALUE : value,
                  }))
                }
                options={managerOptions}
                placeholder="Sem gestor definido"
                searchPlaceholder="Buscar gestor..."
                allowClear
                clearLabel="Remover gestor"
                disabled={isCreatingAccount}
              />
            </div>
            <div className="grid gap-2">
              <Label>Papel</Label>
              <Select
                value={createForm.role}
                onValueChange={(value) =>
                  setCreateForm((prev) => ({ ...prev, role: (value as AdminAccount["role"]) ?? prev.role }))
                }
                disabled={isCreatingAccount}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Selecione" />
                </SelectTrigger>
                <SelectContent>
                  {ROLE_OPTIONS_DISPLAY.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <Label>Empresa vinculada</Label>
              <SearchableCombobox
                value={createForm.companyId}
                onValueChange={(value) =>
                  setCreateForm((prev) => ({
                    ...prev,
                    companyId: value === null ? NO_COMPANY_SELECT_VALUE : value,
                  }))
                }
                options={editCompanyOptions}
                placeholder="Sem empresa vinculada"
                searchPlaceholder="Buscar empresa..."
                disabled={isCreatingAccount}
              />
            </div>

            <DialogFooter className="gap-2 sm:gap-0">
              <Button type="button" variant="ghost" onClick={handleCloseCreateDialog} disabled={isCreatingAccount}>
                Cancelar
              </Button>
              <Button type="submit" disabled={isCreatingAccount}>
                {isCreatingAccount ? "Criando..." : "Criar usuário"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </>
  )
}

function CompanyStructurePanel({ initialCompanies }: { initialCompanies: NormalizedCompany[] }) {
  const [companies, setCompanies] = useState(initialCompanies)
  const [search, setSearch] = useState("")
  const [selectedId, setSelectedId] = useState<string | null>(initialCompanies[0]?.id ?? null)
  const [editor, setEditor] = useState<SectionEditorState>(null)

  const filtered = useMemo(() => {
    const term = search.trim().toLowerCase()
    return companies.filter((company) => {
      if (!term) return true
      return (
        company.name.toLowerCase().includes(term) ||
        company.slug.toLowerCase().includes(term) ||
        (company.domain?.toLowerCase().includes(term) ?? false)
      )
    })
  }, [companies, search])

  const selectedCompany = useMemo(
    () => companies.find((company) => company.id === selectedId) ?? null,
    [companies, selectedId]
  )

  const openEditor = useCallback(
    (section: "contacts" | "locations" | "contracts") => {
      if (!selectedCompany) return
      setEditor({ section, company: selectedCompany })
    },
    [selectedCompany],
  )

  const closeEditor = useCallback(() => setEditor(null), [])

  const applyUpdate = useCallback((updated: NormalizedCompany) => {
    setCompanies((prev) => prev.map((company) => (company.id === updated.id ? updated : company)))
  }, [])

  return (
    <div className="grid gap-6 lg:grid-cols-[minmax(18rem,24rem),1fr]">
      <Card className="h-fit">
        <CardHeader className="pb-3">
          <CardTitle className="text-base font-semibold">Empresas</CardTitle>
          <CardDescription>Selecione uma empresa para visualizar contatos, localizações e contratos.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          <div className="relative">
            <IconSearch className="pointer-events-none absolute left-3 top-2.5 size-4 text-muted-foreground" />
            <Input
              className="pl-9"
              placeholder="Buscar empresa..."
              value={search}
              onChange={(event) => setSearch(event.target.value)}
            />
          </div>
          <div className="max-h-[24rem] space-y-2 overflow-y-auto pr-1">
            {filtered.length === 0 ? (
              <div className="rounded-md border border-dashed border-border/60 p-6 text-center text-sm text-muted-foreground">
                Nenhuma empresa encontrada.
              </div>
            ) : (
              filtered.map((company) => {
                const isActive = company.id === selectedId
                return (
                  <button
                    key={company.id}
                    type="button"
                    onClick={() => setSelectedId(company.id)}
                    className={cn(
                      "flex w-full items-center justify-between gap-3 rounded-md border px-3 py-2 text-left transition",
                      isActive
                        ? "border-primary bg-primary/10 text-primary-foreground"
                        : "border-border/60 hover:border-primary hover:bg-primary/5",
                    )}
                  >
                    <div className="min-w-0">
                      <p className="truncate text-sm font-semibold">{company.name}</p>
                      <p className="truncate text-xs text-muted-foreground">{company.slug}</p>
                    </div>
                    <IconChevronRight className="size-4 text-muted-foreground" />
                  </button>
                )
              })
            )}
          </div>
        </CardContent>
      </Card>

      <Card className="min-h-[32rem]">
        {selectedCompany ? (
          <>
            <CardHeader className="pb-4">
              <div className="flex flex-wrap items-start justify-between gap-3">
                <div>
                  <CardTitle className="flex items-center gap-2 text-lg">
                    <IconBuildingSkyscraper className="size-5 text-muted-foreground" />
                    {selectedCompany.name}
                  </CardTitle>
                  <CardDescription className="text-xs">
                    {selectedCompany.domain ?? "Sem domínio"} ·{" "}
                    {selectedCompany.isAvulso ? "Cliente avulso" : "Cliente com contrato"}
                  </CardDescription>
                </div>
                <div className="flex flex-wrap gap-2">
                  <Button variant="outline" size="sm" onClick={() => openEditor("contacts")}>
                    <IconUsers className="mr-1 size-4" />
                    Editar contatos
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => openEditor("locations")}>
                    <IconMapPin className="mr-1 size-4" />
                    Editar localizações
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => openEditor("contracts")}>
                    <IconNotebook className="mr-1 size-4" />
                    Editar contratos
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent className="space-y-6">
              <SectionSummary
                title="Contatos estratégicos"
                emptyMessage="Nenhum contato cadastrado."
                items={selectedCompany.contacts.map((contact) => ({
                  id: contact.id,
                  title: contact.fullName,
                  subtitle: contact.email,
                  description: contact.role.replace("_", " "),
                }))}
              />

              <SectionSummary
                title="Localizações"
                emptyMessage="Nenhuma unidade cadastrada."
                items={selectedCompany.locations.map((location) => ({
                  id: location.id,
                  title: location.name,
                  subtitle: location.type,
                  description: location.address?.city ? `${location.address.city}/${location.address.state}` : location.notes ?? "",
                }))}
              />

              <SectionSummary
                title="Contratos"
                emptyMessage="Nenhum contrato cadastrado."
                items={selectedCompany.contracts.map((contract) => ({
                  id: contract.id,
                  title: `${contract.contractType.toUpperCase()}${contract.planSku ? ` · ${contract.planSku}` : ""}`,
                  subtitle: contract.scope.length ? contract.scope.join(", ") : "Escopo não informado",
                  description: contract.notes ?? "",
                }))}
              />
            </CardContent>
          </>
        ) : (
          <div className="flex h-full flex-col items-center justify-center gap-3 p-8 text-sm text-muted-foreground">
            <IconBuildingSkyscraper className="size-6" />
            <p>Selecione uma empresa para visualizar os detalhes.</p>
          </div>
        )}
      </Card>

      <CompanySectionSheet editor={editor} onClose={closeEditor} onUpdated={applyUpdate} />
    </div>
  )
}

function SectionSummary({
  title,
  items,
  emptyMessage,
}: {
  title: string
  items: { id: string; title: string; subtitle?: string | null; description?: string | null }[]
  emptyMessage: string
}) {
  return (
    <div className="space-y-2">
      <p className="text-sm font-semibold text-foreground">{title}</p>
      {items.length === 0 ? (
        <div className="rounded-md border border-dashed border-border/60 p-6 text-sm text-muted-foreground">
          {emptyMessage}
        </div>
      ) : (
        <div className="space-y-2">
          {items.map((item) => (
            <div key={item.id} className="rounded-md border border-border/60 px-3 py-2">
              <p className="text-sm font-semibold text-foreground">{item.title}</p>
              {item.subtitle ? <p className="text-xs text-muted-foreground">{item.subtitle}</p> : null}
              {item.description ? (
                <p className="text-xs text-muted-foreground/90">{item.description}</p>
              ) : null}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

type CompanySectionSheetProps = {
  editor: SectionEditorState
  onClose(): void
  onUpdated(company: NormalizedCompany): void
}

function CompanySectionSheet({ editor, onClose, onUpdated }: CompanySectionSheetProps) {
  const [isSubmitting, startSubmit] = useTransition()
  const open = Boolean(editor)

  const handleSave = (payload: Partial<CompanyFormValues>, companyId: string) => {
    startSubmit(async () => {
      try {
        const response = await fetch(`/api/admin/companies/${companyId}`, {
          method: "PATCH",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(payload),
        })
        if (!response.ok) {
          const json = await response.json().catch(() => null)
          throw new Error(json?.error ?? "Falha ao atualizar a empresa.")
        }
        const json = (await response.json()) as { company: NormalizedCompany }
        onUpdated(json.company)
        toast.success("Dados atualizados com sucesso.")
        onClose()
      } catch (error) {
        const message = error instanceof Error ? error.message : "Não foi possível salvar as alterações."
        toast.error(message)
      }
    })
  }

  let content: React.ReactNode = null

  if (editor) {
    if (editor.section === "contacts") {
      content = (
        <ContactsEditor
          company={editor.company}
          onCancel={onClose}
          onSubmit={(contacts) => handleSave({ contacts }, editor.company.id)}
        />
      )
    } else if (editor.section === "locations") {
      content = (
        <LocationsEditor
          company={editor.company}
          onCancel={onClose}
          onSubmit={(locations) => handleSave({ locations }, editor.company.id)}
        />
      )
    } else if (editor.section === "contracts") {
      content = (
        <ContractsEditor
          company={editor.company}
          onCancel={onClose}
          onSubmit={(contracts) => handleSave({ contracts }, editor.company.id)}
        />
      )
    }
  }

  return (
    <Sheet open={open} onOpenChange={(value) => (!value ? onClose() : null)}>
      <SheetContent className="flex w-full max-w-none flex-col gap-0 bg-background p-0 sm:max-w-[48rem] lg:max-w-[60rem] xl:max-w-[68rem]">
        <SheetHeader className="border-b border-border/60 px-10 py-7">
          <SheetTitle className="text-xl font-semibold">
            {editor?.section === "contacts" ? "Contatos da empresa" : null}
            {editor?.section === "locations" ? "Localizações e unidades" : null}
            {editor?.section === "contracts" ? "Contratos ativos" : null}
          </SheetTitle>
        </SheetHeader>
        <div className="flex-1 overflow-y-auto px-10 py-8">{content}</div>
        <SheetFooter className="border-t border-border/60 px-10 py-5">
          <div className="flex w-full items-center justify-end">
            {isSubmitting ? (
              <span className="text-sm text-muted-foreground">Salvando...</span>
            ) : null}
          </div>
        </SheetFooter>
      </SheetContent>
    </Sheet>
  )
}

function ContactsEditor({
  company,
  onCancel,
  onSubmit,
}: {
  company: NormalizedCompany
  onCancel(): void
  onSubmit(contacts: CompanyContact[]): void
}) {
  const form = useForm<{ contacts: CompanyContact[] }>({
    resolver: zodResolver(companyFormSchema.pick({ contacts: true })),
    defaultValues: {
      contacts: company.contacts.length
        ? company.contacts
        : [
            {
              id: createId("contact"),
              fullName: "",
              email: "",
              role: COMPANY_CONTACT_ROLES[0]?.value ?? "usuario_chave",
              phone: null,
              whatsapp: null,
              preference: [],
              title: null,
              canAuthorizeTickets: false,
              canApproveCosts: false,
              lgpdConsent: true,
              notes: null,
            },
          ],
    },
  })

  const fieldArray = useFieldArray({ control: form.control, name: "contacts" })

  const submit = form.handleSubmit((values) => {
    onSubmit(values.contacts)
  })

  return (
    <FormProvider {...form}>
      <form onSubmit={submit} className="space-y-8">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1.5">
            <p className="text-base font-semibold text-foreground">Contatos estratégicos</p>
            <p className="text-sm text-muted-foreground">
              Cadastre responsáveis por aprovação, faturamento e comunicação.
            </p>
          </div>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="self-start sm:self-auto"
            onClick={() =>
              fieldArray.append({
                id: createId("contact"),
                fullName: "",
                email: "",
                role: COMPANY_CONTACT_ROLES[0]?.value ?? "usuario_chave",
                phone: null,
                whatsapp: null,
                preference: [],
                title: null,
                canAuthorizeTickets: false,
                canApproveCosts: false,
                lgpdConsent: true,
                notes: null,
              })
            }
          >
            <IconPlus className="mr-2 size-4" />
            Novo contato
          </Button>
        </div>

        <div className="space-y-6">
          {fieldArray.fields.map((field, index) => {
            const errors = form.formState.errors.contacts?.[index]
            return (
              <Card key={field.id} className="border border-border/60 shadow-sm">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
                  <CardTitle className="text-lg font-semibold">Contato #{index + 1}</CardTitle>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => fieldArray.remove(index)}
                    className="text-destructive"
                  >
                    <IconTrash className="size-4" />
                  </Button>
                </CardHeader>
                <CardContent className="grid gap-6 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Nome completo
                    </Label>
                    <Input {...form.register(`contacts.${index}.fullName` as const)} />
                    <FieldError message={errors?.fullName?.message} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      E-mail
                    </Label>
                    <Input {...form.register(`contacts.${index}.email` as const)} />
                    <FieldError message={errors?.email?.message} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Telefone
                    </Label>
                    <Input {...form.register(`contacts.${index}.phone` as const)} placeholder="(11) 99999-0000" />
                    <FieldError message={errors?.phone?.message as string | undefined} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      WhatsApp
                    </Label>
                    <Input {...form.register(`contacts.${index}.whatsapp` as const)} placeholder="(11) 99999-0000" />
                    <FieldError message={errors?.whatsapp?.message as string | undefined} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Função
                    </Label>
                    <Controller
                      name={`contacts.${index}.role` as const}
                      control={form.control}
                      render={({ field }) => (
                        <Select value={field.value} onValueChange={field.onChange}>
                          <SelectTrigger>
                            <SelectValue placeholder="Selecione" />
                          </SelectTrigger>
                          <SelectContent>
                            {COMPANY_CONTACT_ROLES.map((option) => (
                              <SelectItem key={option.value} value={option.value}>
                                {option.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Cargo interno
                    </Label>
                    <Input {...form.register(`contacts.${index}.title` as const)} placeholder="ex.: Coordenador TI" />
                  </div>
                  <div className="md:col-span-2 space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Preferências de contato
                    </Label>
                    <Controller
                      name={`contacts.${index}.preference` as const}
                      control={form.control}
                      render={({ field }) => (
                        <MultiValueInput
                          values={field.value}
                          onChange={field.onChange}
                          placeholder="email, phone, whatsapp..."
                        />
                      )}
                    />
                  </div>
                  <div className="md:col-span-2 flex items-center gap-3 rounded-lg border border-border/60 bg-muted/30 px-4 py-3">
                    <Checkbox
                      checked={form.watch(`contacts.${index}.canAuthorizeTickets` as const)}
                      onCheckedChange={(checked) =>
                        form.setValue(`contacts.${index}.canAuthorizeTickets` as const, Boolean(checked))
                      }
                    />
                    <span className="text-sm font-medium text-neutral-700">Pode autorizar tickets</span>
                  </div>
                  <div className="md:col-span-2 flex items-center gap-3 rounded-lg border border-border/60 bg-muted/30 px-4 py-3">
                    <Checkbox
                      checked={form.watch(`contacts.${index}.canApproveCosts` as const)}
                      onCheckedChange={(checked) =>
                        form.setValue(`contacts.${index}.canApproveCosts` as const, Boolean(checked))
                      }
                    />
                    <span className="text-sm font-medium text-neutral-700">Pode aprovar custos</span>
                  </div>
                  <div className="md:col-span-2 space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Anotações
                    </Label>
                    <Textarea {...form.register(`contacts.${index}.notes` as const)} />
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        <div className="flex flex-col gap-3 sm:flex-row sm:justify-end">
          <Button type="button" variant="ghost" className="whitespace-nowrap sm:w-auto" onClick={onCancel}>
            Cancelar
          </Button>
          <Button type="submit" className="whitespace-nowrap sm:w-auto">
            <IconPencil className="mr-2 size-4" />
            Salvar contatos
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}

function LocationsEditor({
  company,
  onCancel,
  onSubmit,
}: {
  company: NormalizedCompany
  onCancel(): void
  onSubmit(locations: CompanyLocation[]): void
}) {
  const form = useForm<{ locations: CompanyLocation[] }>({
    resolver: zodResolver(companyFormSchema.pick({ locations: true })),
    defaultValues: {
      locations: company.locations.length
        ? company.locations
        : [
            {
              id: createId("location"),
              name: "",
              type: COMPANY_LOCATION_TYPES[0]?.value ?? "matrix",
              address: null,
              responsibleContactId: null,
              serviceWindow: { mode: "inherit", periods: [] },
              notes: null,
            },
          ],
    },
  })

  const fieldArray = useFieldArray({ control: form.control, name: "locations" })

  const submit = form.handleSubmit((values) => onSubmit(values.locations))
  const contacts = company.contacts

  return (
    <FormProvider {...form}>
      <form onSubmit={submit} className="space-y-8">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1.5">
            <p className="text-base font-semibold text-foreground">Localizações</p>
            <p className="text-sm text-muted-foreground">
              Defina unidades críticas, data centers e filiais para atendimento dedicado.
            </p>
          </div>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="self-start sm:self-auto"
            onClick={() =>
              fieldArray.append({
                id: createId("location"),
                name: "",
                type: COMPANY_LOCATION_TYPES[0]?.value ?? "matrix",
                address: null,
                responsibleContactId: null,
                serviceWindow: { mode: "inherit", periods: [] },
                notes: null,
              })
            }
          >
            <IconPlus className="mr-2 size-4" />
            Nova unidade
          </Button>
        </div>

        <div className="space-y-6">
          {fieldArray.fields.map((field, index) => {
            const errors = form.formState.errors.locations?.[index]
            return (
              <Card key={field.id} className="border border-border/60 shadow-sm">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
                  <CardTitle className="text-lg font-semibold">Unidade #{index + 1}</CardTitle>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => fieldArray.remove(index)}
                    className="text-destructive"
                  >
                    <IconTrash className="size-4" />
                  </Button>
                </CardHeader>
                <CardContent className="grid gap-6 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Nome</Label>
                    <Input {...form.register(`locations.${index}.name` as const)} />
                    <FieldError message={errors?.name?.message} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Tipo</Label>
                    <Controller
                      name={`locations.${index}.type` as const}
                      control={form.control}
                      render={({ field }) => (
                        <Select value={field.value} onValueChange={field.onChange}>
                          <SelectTrigger>
                            <SelectValue placeholder="Selecione" />
                          </SelectTrigger>
                          <SelectContent>
                            {COMPANY_LOCATION_TYPES.map((option) => (
                              <SelectItem key={option.value} value={option.value}>
                                {option.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Contato responsável
                    </Label>
                    <Controller
                      name={`locations.${index}.responsibleContactId` as const}
                      control={form.control}
                      render={({ field }) => (
                        <Select
                          value={field.value ?? NO_CONTACT_VALUE}
                          onValueChange={(value) =>
                            field.onChange(value === NO_CONTACT_VALUE ? null : value)
                          }
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="Selecione" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value={NO_CONTACT_VALUE}>Nenhum</SelectItem>
                            {contacts.map((contact) => (
                              <SelectItem key={contact.id} value={contact.id}>
                                {contact.fullName}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                    />
                  </div>
                  <div className="md:col-span-2 space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Notas
                    </Label>
                    <Textarea {...form.register(`locations.${index}.notes` as const)} />
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        <div className="flex flex-col gap-3 sm:flex-row sm:justify-end">
          <Button type="button" variant="ghost" className="whitespace-nowrap sm:w-auto" onClick={onCancel}>
            Cancelar
          </Button>
          <Button type="submit" className="whitespace-nowrap sm:w-auto">
            <IconPencil className="mr-2 size-4" />
            Salvar localizações
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}

function ContractsEditor({
  company,
  onCancel,
  onSubmit,
}: {
  company: NormalizedCompany
  onCancel(): void
  onSubmit(contracts: CompanyContract[]): void
}) {
  const form = useForm<{ contracts: CompanyContract[] }>({
    resolver: zodResolver(companyFormSchema.pick({ contracts: true })),
    defaultValues: {
      contracts: company.contracts.length
        ? company.contracts
        : [
            {
              id: createId("contract"),
              contractType: COMPANY_CONTRACT_TYPES[0]?.value ?? "monthly",
              planSku: null,
              startDate: null,
              endDate: null,
              renewalDate: null,
              scope: [],
              price: null,
              costCenter: null,
              criticality: "medium",
              notes: null,
            },
          ],
    },
  })

  const fieldArray = useFieldArray({ control: form.control, name: "contracts" })

  const submit = form.handleSubmit((values) => onSubmit(values.contracts))

  return (
    <FormProvider {...form}>
      <form onSubmit={submit} className="space-y-8">
        <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
          <div className="space-y-1.5">
            <p className="text-base font-semibold text-foreground">Contratos</p>
            <p className="text-sm text-muted-foreground">
              Registre vigência, escopo e condições para este cliente.
            </p>
          </div>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="self-start sm:self-auto"
            onClick={() =>
              fieldArray.append({
                id: createId("contract"),
                contractType: COMPANY_CONTRACT_TYPES[0]?.value ?? "monthly",
                planSku: null,
                startDate: null,
                endDate: null,
                renewalDate: null,
                scope: [],
                price: null,
                costCenter: null,
                criticality: "medium",
                notes: null,
              })
            }
          >
            <IconPlus className="mr-2 size-4" />
            Novo contrato
          </Button>
        </div>

        <div className="space-y-6">
          {fieldArray.fields.map((field, index) => {
            const errors = form.formState.errors.contracts?.[index]
            return (
              <Card key={field.id} className="border border-border/60 shadow-sm">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
                  <CardTitle className="text-lg font-semibold">Contrato #{index + 1}</CardTitle>
                  <Button
                    type="button"
                    variant="ghost"
                    size="icon"
                    onClick={() => fieldArray.remove(index)}
                    className="text-destructive"
                  >
                    <IconTrash className="size-4" />
                  </Button>
                </CardHeader>
                <CardContent className="grid gap-6 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Tipo
                    </Label>
                    <Controller
                      name={`contracts.${index}.contractType` as const}
                      control={form.control}
                      render={({ field }) => (
                        <Select value={field.value} onValueChange={field.onChange}>
                          <SelectTrigger>
                            <SelectValue placeholder="Selecione" />
                          </SelectTrigger>
                          <SelectContent>
                            {COMPANY_CONTRACT_TYPES.map((option) => (
                              <SelectItem key={option.value} value={option.value}>
                                {option.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      )}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      SKU/plano
                    </Label>
                    <Input {...form.register(`contracts.${index}.planSku` as const)} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Início
                    </Label>
                    <Controller
                      name={`contracts.${index}.startDate` as const}
                      control={form.control}
                      render={({ field }) => (
                        <DatePicker
                          value={field.value}
                          onChange={(next) => field.onChange(next ?? null)}
                          placeholder="Selecione a data"
                        />
                      )}
                    />
                    <FieldError message={errors?.startDate?.message as string | undefined} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Fim
                    </Label>
                    <Controller
                      name={`contracts.${index}.endDate` as const}
                      control={form.control}
                      render={({ field }) => (
                        <DatePicker
                          value={field.value}
                          onChange={(next) => field.onChange(next ?? null)}
                          placeholder="Selecione a data"
                        />
                      )}
                    />
                    <FieldError message={errors?.endDate?.message as string | undefined} />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Renovação
                    </Label>
                    <Controller
                      name={`contracts.${index}.renewalDate` as const}
                      control={form.control}
                      render={({ field }) => (
                        <DatePicker
                          value={field.value}
                          onChange={(next) => field.onChange(next ?? null)}
                          placeholder="Selecione a data"
                          allowClear
                        />
                      )}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Valor (R$)
                    </Label>
                    <Input
                      type="number"
                      step="0.01"
                      {...form.register(`contracts.${index}.price` as const, { valueAsNumber: true })}
                    />
                  </div>
                  <div className="md:col-span-2 space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Escopo
                    </Label>
                    <Controller
                      name={`contracts.${index}.scope` as const}
                      control={form.control}
                      render={({ field }) => (
                        <MultiValueInput
                          values={field.value}
                          onChange={field.onChange}
                          placeholder="Adicionar item de escopo"
                          validate={(value) =>
                            COMPANY_CONTRACT_SCOPES.includes(
                              value as (typeof COMPANY_CONTRACT_SCOPES)[number],
                            )
                              ? null
                              : "Escopo fora do catálogo"
                          }
                        />
                      )}
                    />
                  </div>
                  <div className="md:col-span-2 space-y-2">
                    <Label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                      Observações
                    </Label>
                    <Textarea {...form.register(`contracts.${index}.notes` as const)} />
                  </div>
                </CardContent>
              </Card>
            )
          })}
        </div>

        <div className="flex flex-col gap-3 sm:flex-row sm:justify-end">
          <Button type="button" variant="ghost" className="whitespace-nowrap sm:w-auto" onClick={onCancel}>
            Cancelar
          </Button>
          <Button type="submit" className="whitespace-nowrap sm:w-auto">
            <IconPencil className="mr-2 size-4" />
            Salvar contratos
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
