"use client"

import { useEffect, useMemo, useState } from "react"
import { useMutation, useQuery } from "convex/react"
import { toast } from "sonner"
import type { Id } from "@/convex/_generated/dataModel"
import { api } from "@/convex/_generated/api"

import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Checkbox } from "@/components/ui/checkbox"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { Spinner } from "@/components/ui/spinner"

type QuickCreateDeviceDialogProps = {
  open: boolean
  tenantId: string
  viewerId: string | null
  onOpenChange(open: boolean): void
  initialCompanySlug?: string | null
  onSuccess?(payload: { companySlug?: string | null }): void
}

const DEVICE_TYPE_OPTIONS = [
  { value: "mobile", label: "Celular" },
  { value: "desktop", label: "Desktop" },
  { value: "tablet", label: "Tablet" },
] as const

type DeviceTypeOption = (typeof DEVICE_TYPE_OPTIONS)[number]["value"]

export function QuickCreateDeviceDialog({
  open,
  tenantId,
  viewerId,
  onOpenChange,
  initialCompanySlug = null,
  onSuccess,
}: QuickCreateDeviceDialogProps) {
  const [name, setName] = useState("")
  const [identifier, setIdentifier] = useState("")
  const [deviceType, setDeviceType] = useState<DeviceTypeOption>("mobile")
  const [platform, setPlatform] = useState("")
  const [companySlug, setCompanySlug] = useState<string | null>(null)
  const [serials, setSerials] = useState("")
  const [notes, setNotes] = useState("")
  const [isActive, setIsActive] = useState(true)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const saveDeviceProfile = useMutation(api.devices.saveDeviceProfile)
  const canQueryCompanies = open && Boolean(viewerId)
  const companies = useQuery(
    api.companies.list,
    canQueryCompanies ? { tenantId, viewerId: viewerId as Id<"users"> } : "skip"
  ) as Array<{ id: string; name: string; slug?: string }> | undefined

  const companyOptions = useMemo<SearchableComboboxOption[]>(() => {
    if (!companies) return []
    return companies
      .map((company) => ({
        value: company.slug ?? company.id,
        label: company.name,
      }))
      .sort((a, b) => a.label.localeCompare(b.label, "pt-BR"))
  }, [companies])

  useEffect(() => {
    if (open) {
      setCompanySlug(initialCompanySlug ?? null)
    }
  }, [initialCompanySlug, open])

  const resetForm = () => {
    setName("")
    setIdentifier("")
    setDeviceType("mobile")
    setPlatform("")
    setCompanySlug(initialCompanySlug ?? null)
    setSerials("")
    setNotes("")
    setIsActive(true)
  }

  const handleClose = () => {
    if (isSubmitting) return
    resetForm()
    onOpenChange(false)
  }

  const handleSubmit = async () => {
    if (!viewerId) {
      toast.error("Não foi possível identificar o usuário atual.")
      return
    }
    const trimmedName = name.trim()
    if (trimmedName.length < 3) {
      toast.error("Informe um nome com ao menos 3 caracteres.")
      return
    }
    const identifierValue = (identifier.trim() || trimmedName).trim()
    const platformValue = platform.trim()
    const serialList = serials
      .split(/\r?\n|,|;/)
      .map((entry) => entry.trim())
      .filter(Boolean)
    const selectedCompany = (companies ?? []).find((company) => (company.slug ?? company.id) === companySlug) ?? null

    try {
      setIsSubmitting(true)
      await saveDeviceProfile({
        tenantId,
        actorId: viewerId as Id<"users">,
        displayName: trimmedName,
        hostname: identifierValue,
        deviceType,
        devicePlatform: platformValue || undefined,
        osName: platformValue || undefined,
        serialNumbers: serialList.length > 0 ? serialList : undefined,
        companyId: selectedCompany ? (selectedCompany.id as Id<"companies">) : undefined,
        companySlug: selectedCompany?.slug ?? undefined,
        status: "unknown",
        isActive,
        profile: notes.trim() ? { notes: notes.trim() } : undefined,
      })
      toast.success("Dispositivo criado com sucesso.")
      onSuccess?.({ companySlug: selectedCompany?.slug ?? null })
      resetForm()
      onOpenChange(false)
    } catch (error) {
      console.error("Failed to create quick device", error)
      toast.error("Não foi possível criar o dispositivo.")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(next) : handleClose())}>
      <DialogContent className="max-w-lg space-y-4">
        <DialogHeader>
          <DialogTitle>Novo dispositivo</DialogTitle>
          <DialogDescription>
            Registre celulares, tablets ou outros ativos sem agente instalado. Você continuará nesta página até concluir.
          </DialogDescription>
        </DialogHeader>
        <div className="grid gap-4">
          <div className="grid gap-2">
            <label htmlFor="quick-device-name" className="text-sm font-medium text-slate-700">
              Nome do dispositivo
            </label>
            <Input
              id="quick-device-name"
              value={name}
              onChange={(event) => setName(event.target.value)}
              placeholder="iPhone da Ana"
              autoFocus
              disabled={isSubmitting}
            />
          </div>
          <div className="grid gap-2">
            <label htmlFor="quick-device-identifier" className="text-sm font-medium text-slate-700">
              Identificador (hostname)
            </label>
            <Input
              id="quick-device-identifier"
              value={identifier}
              onChange={(event) => setIdentifier(event.target.value)}
              placeholder="ana-iphone"
              disabled={isSubmitting}
            />
            <p className="text-xs text-slate-500">Caso vazio, usaremos o nome como identificador.</p>
          </div>
          <div className="grid gap-2 sm:grid-cols-2 sm:gap-4">
            <div className="grid gap-2">
              <label className="text-sm font-medium text-slate-700">Tipo</label>
              <Select value={deviceType} onValueChange={(value) => setDeviceType(value as DeviceTypeOption)} disabled={isSubmitting}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {DEVICE_TYPE_OPTIONS.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-2">
              <label htmlFor="quick-device-platform" className="text-sm font-medium text-slate-700">
                Plataforma
              </label>
              <Input
                id="quick-device-platform"
                value={platform}
                onChange={(event) => setPlatform(event.target.value)}
                placeholder="iOS 18, Android 15, Windows 11"
                disabled={isSubmitting}
              />
            </div>
          </div>
          <div className="grid gap-2">
            <label className="text-sm font-medium text-slate-700">Empresa</label>
            <SearchableCombobox
              value={companySlug}
              onValueChange={setCompanySlug}
              options={companyOptions}
              placeholder="Sem empresa"
              searchPlaceholder="Buscar empresa..."
              emptyText={companies && companies.length === 0 ? "Nenhuma empresa cadastrada" : "Nenhum resultado"}
              allowClear
              clearLabel="Sem empresa"
              disabled={isSubmitting || !companies}
            />
          </div>
          <div className="grid gap-2">
            <label htmlFor="quick-device-serials" className="text-sm font-medium text-slate-700">
              Seriais / IMEI
            </label>
            <Textarea
              id="quick-device-serials"
              value={serials}
              onChange={(event) => setSerials(event.target.value)}
              placeholder="Separe múltiplos valores com quebra de linha"
              disabled={isSubmitting}
            />
          </div>
          <div className="grid gap-2">
            <label htmlFor="quick-device-notes" className="text-sm font-medium text-slate-700">
              Observações
            </label>
            <Textarea
              id="quick-device-notes"
              value={notes}
              onChange={(event) => setNotes(event.target.value)}
              placeholder="Informações adicionais para a equipe"
              disabled={isSubmitting}
            />
          </div>
          <label className="flex items-center gap-2 text-sm text-slate-700">
            <Checkbox
              checked={isActive}
              onCheckedChange={(value) => setIsActive(value === true || value === "indeterminate")}
              disabled={isSubmitting}
            />
            <span>Ativo</span>
          </label>
        </div>
        <DialogFooter className="gap-2 sm:gap-2">
          <Button type="button" variant="outline" onClick={handleClose} disabled={isSubmitting}>
            Cancelar
          </Button>
          <Button type="button" onClick={handleSubmit} disabled={isSubmitting || name.trim().length < 3} className="gap-2">
            {isSubmitting ? (
              <>
                <Spinner className="size-4" />
                Salvando...
              </>
            ) : (
              "Cadastrar dispositivo"
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
