"use client"

import { useId, useMemo, useState } from "react"
import dynamic from "next/dynamic"
import { usePathname, useRouter } from "next/navigation"
import { MonitorSmartphone, Building, UserPlus, ChevronRight } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Skeleton } from "@/components/ui/skeleton"
import { NewTicketDialogDeferred } from "@/components/tickets/new-ticket-dialog.client"
import { useAuth } from "@/lib/auth-client"
import { cn } from "@/lib/utils"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { QuickCreateDeviceDialog } from "@/components/quick-actions/quick-create-device-dialog"
import { QuickCreateUserDialog } from "@/components/quick-actions/quick-create-user-dialog"
import type { CompanyEditorState } from "@/components/admin/companies/admin-companies-manager"
import type { NormalizedCompany } from "@/server/company-service"

const CompanySheetDialog = dynamic(
  () =>
    import("@/components/admin/companies/admin-companies-manager").then((mod) => ({
      default: mod.CompanySheet,
    })),
  {
    ssr: false,
    loading: () => (
      <div className="rounded-3xl border border-border/60 bg-background p-6 text-sm text-muted-foreground shadow-2xl">
        Carregando formulário de empresa...
      </div>
    ),
  }
)

type QuickLink = {
  id: "device" | "company" | "user"
  label: string
  description?: string
  icon: React.ComponentType<{ className?: string }>
  href: string
  visible: boolean
}

export function GlobalQuickActions() {
  const { convexUserId, isAdmin, isStaff, isLoading, session } = useAuth()
  const router = useRouter()
  const pathname = usePathname()
  const actionId = useId()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const [isDeviceDialogOpen, setIsDeviceDialogOpen] = useState(false)
  const [isUserDialogOpen, setIsUserDialogOpen] = useState(false)
  const [companyEditor, setCompanyEditor] = useState<CompanyEditorState | null>(null)

  const links = useMemo<QuickLink[]>(() => {
    const base: QuickLink[] = [
      {
        id: "device",
        label: "Adicionar dispositivo",
        description: "Registrar agente, serial ou ativo remoto",
        icon: MonitorSmartphone,
        href: "/admin/devices?quick=new-device",
        visible: Boolean(isAdmin),
      },
      {
        id: "company",
        label: "Adicionar empresa",
        description: "Cadastrar novo cliente",
        icon: Building,
        href: "/admin/companies?quick=new-company",
        visible: Boolean(isAdmin),
      },
      {
        id: "user",
        label: "Novo usuário",
        description: "Gestores / colaboradores",
        icon: UserPlus,
        href: "/admin/users?quick=new-user",
        visible: Boolean(isAdmin),
      },
    ]
    return base.filter((link) => link.visible)
  }, [isAdmin])

  if (!isStaff && !isAdmin) {
    return null
  }

  if (isLoading) {
    return (
      <div className="border-b border-border/60 bg-muted/30 px-4 py-3 lg:px-8">
        <div className="flex gap-3 overflow-x-auto pb-1">
          {Array.from({ length: 3 }).map((_, index) => (
            <Skeleton key={index} className="h-12 w-48 rounded-2xl" />
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="border-b border-border/60 bg-background/80 px-4 py-3 backdrop-blur lg:px-8">
      <div className="flex w-full flex-wrap gap-3 overflow-x-auto pb-1 md:overflow-visible">
        <NewTicketDialogDeferred
          triggerVariant="card"
          triggerClassName="min-w-[200px] flex-1 md:min-w-[220px]"
        />
        {links.map((link) => (
          <button
            key={link.id}
            type="button"
            onClick={() => {
              const targetPath = link.href.split("?")[0]
              const dispatchQuickEvent = () => {
                if (typeof window === "undefined") return false
                const eventName =
                  link.id === "device"
                    ? "quick-open-device"
                    : link.id === "company"
                      ? "quick-open-company"
                      : link.id === "user"
                        ? "quick-open-user"
                        : null
                if (!eventName) return false
                window.dispatchEvent(new CustomEvent(eventName))
                return true
              }
              if (pathname === targetPath && dispatchQuickEvent()) {
                return
              }
              if (link.id === "device") {
                setIsDeviceDialogOpen(true)
                return
              }
              if (link.id === "company") {
                setCompanyEditor({ mode: "create" })
                return
              }
              if (link.id === "user") {
                setIsUserDialogOpen(true)
                return
              }
              router.push(link.href)
            }}
            className="group inline-flex h-auto min-w-[200px] flex-1 flex-col items-start justify-start rounded-2xl border border-border/60 bg-card px-4 py-3 text-left shadow-sm transition hover:-translate-y-0.5 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 md:min-w-[220px]"
          >
            <div className="flex items-center justify-between gap-3">
              <div className="rounded-xl bg-muted/70 p-2 text-muted-foreground">
                <link.icon className="size-4" />
              </div>
              <ChevronRight className="size-4 text-muted-foreground transition group-hover:translate-x-1" />
            </div>
            <div className="mt-3 text-sm font-semibold text-foreground">{link.label}</div>
            {link.description ? (
              <p className="text-xs text-muted-foreground">{link.description}</p>
            ) : null}
          </button>
        ))}
        {convexUserId ? (
          <Button
            variant="outline"
            size="sm"
            onClick={() => router.push(`/tickets?assignee=${String(convexUserId)}`)}
            className="inline-flex h-auto min-w-[200px] flex-col items-start justify-start gap-1 rounded-2xl border-dashed px-4 py-3 text-left text-sm font-semibold text-muted-foreground hover:bg-muted/40 md:min-w-[220px]"
            aria-describedby={actionId}
          >
            <span id={actionId} className="text-xs font-semibold uppercase tracking-wide text-muted-foreground/80">
              Minha fila
            </span>
            <span className="text-base text-foreground">Ver tarefas atribuídas</span>
          </Button>
        ) : null}
      </div>
      <QuickCreateDeviceDialog
        open={isDeviceDialogOpen}
        onOpenChange={setIsDeviceDialogOpen}
        tenantId={tenantId}
        viewerId={convexUserId}
        onSuccess={() => {
          router.push("/admin/devices")
        }}
      />
      <QuickCreateUserDialog
        open={isUserDialogOpen}
        onOpenChange={setIsUserDialogOpen}
        tenantId={tenantId}
        viewerId={convexUserId}
        onSuccess={() => {
          router.push("/admin/users")
        }}
      />
      {companyEditor ? (
        <CompanySheetDialog
          tenantId={tenantId}
          editor={companyEditor}
          onClose={() => setCompanyEditor(null)}
          onCreated={(company: NormalizedCompany) => {
            setCompanyEditor(null)
            router.push("/admin/companies")
          }}
          onUpdated={() => {
            setCompanyEditor(null)
          }}
        />
      ) : null}
    </div>
  )
}
