"use client"

import { useState } from "react"
import { useQuery } from "convex/react"
import { formatDistanceToNow } from "date-fns"
import { ptBR } from "date-fns/locale"
import { Package, Search, ChevronLeft, ChevronRight, Eraser } from "lucide-react"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Skeleton } from "@/components/ui/skeleton"

type DeviceSoftwareListProps = {
  machineId: Id<"machines">
}

export function DeviceSoftwareList({ machineId }: DeviceSoftwareListProps) {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const viewerId = convexUserId as Id<"users"> | undefined

  const [search, setSearch] = useState("")
  const [cursorHistory, setCursorHistory] = useState<(string | null)[]>([null])
  const [pageIndex, setPageIndex] = useState(0)

  const currentCursor = cursorHistory[pageIndex] ?? null

  const result = useQuery(
    api.machineSoftware.listByMachine,
    viewerId
      ? {
          tenantId,
          viewerId,
          machineId,
          search: search.trim() || undefined,
          limit: 30,
          cursor: currentCursor ?? undefined,
        }
      : "skip"
  )

  const count = useQuery(api.machineSoftware.countByMachine, { machineId })

  const handleSearch = (value: string) => {
    setSearch(value)
    setCursorHistory([null])
    setPageIndex(0)
  }

  const handleNextPage = () => {
    if (result?.nextCursor) {
      const nextIndex = pageIndex + 1
      setCursorHistory((prev) => {
        const updated = [...prev]
        updated[nextIndex] = result.nextCursor
        return updated
      })
      setPageIndex(nextIndex)
    }
  }

  const handlePrevPage = () => {
    if (pageIndex > 0) {
      setPageIndex(pageIndex - 1)
    }
  }

  if (!viewerId) {
    return null
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-3">
        <div className="flex items-center gap-2">
          <Package className="size-5 text-neutral-600" />
          <h3 className="text-sm font-semibold text-neutral-900">Softwares instalados</h3>
          {count?.count !== undefined && (
            <Badge variant="secondary" className="rounded-full">
              {count.count}
            </Badge>
          )}
        </div>
      </div>

      <div className="flex items-center gap-2">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 size-4 -translate-y-1/2 text-neutral-400" />
          <Input
            placeholder="Buscar por nome, versão ou fabricante..."
            value={search}
            onChange={(e) => handleSearch(e.target.value)}
            className="pl-9"
          />
        </div>
        {search && (
          <Button
            type="button"
            variant="outline"
            size="icon"
            onClick={() => handleSearch("")}
            className="size-10 shrink-0"
          >
            <Eraser className="size-4" />
          </Button>
        )}
      </div>

      {result === undefined ? (
        <div className="space-y-2">
          {Array.from({ length: 5 }).map((_, index) => (
            <Skeleton key={`software-skeleton-${index}`} className="h-14 rounded-lg" />
          ))}
        </div>
      ) : result.items.length === 0 ? (
        <div className="rounded-xl border border-dashed border-slate-300 bg-slate-50/80 p-6 text-center">
          <Package className="mx-auto size-8 text-slate-400" />
          <p className="mt-2 text-sm font-medium text-neutral-700">
            {search ? "Nenhum software encontrado" : "Nenhum software detectado"}
          </p>
          <p className="mt-1 text-xs text-neutral-500">
            {search
              ? `Nenhum resultado para "${search}".`
              : "O agente ainda não enviou dados de softwares instalados."}
          </p>
        </div>
      ) : (
        <>
          <div className="divide-y divide-slate-100 rounded-xl border border-slate-200 bg-white">
            {result.items.map((software) => (
              <div
                key={software.id}
                className="flex items-center justify-between gap-3 px-4 py-3 first:rounded-t-xl last:rounded-b-xl hover:bg-slate-50"
              >
                <div className="min-w-0 flex-1 space-y-0.5">
                  <p className="truncate text-sm font-medium text-neutral-900">{software.name}</p>
                  <div className="flex flex-wrap items-center gap-2 text-xs text-neutral-500">
                    {software.version && <span>v{software.version}</span>}
                    {software.publisher && (
                      <>
                        <span className="text-neutral-300">|</span>
                        <span>{software.publisher}</span>
                      </>
                    )}
                    {software.source && (
                      <Badge variant="outline" className="rounded text-[10px] px-1.5 py-0">
                        {software.source}
                      </Badge>
                    )}
                  </div>
                </div>
                <div className="shrink-0 text-right">
                  <p className="text-xs text-neutral-400">
                    Visto {formatDistanceToNow(software.lastSeenAt, { addSuffix: true, locale: ptBR })}
                  </p>
                </div>
              </div>
            ))}
          </div>

          <div className="flex items-center justify-between text-xs text-neutral-500">
            <span>
              Mostrando {pageIndex * 30 + 1}-{Math.min((pageIndex + 1) * 30, result.total)} de {result.total} softwares
            </span>
            <div className="flex gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={handlePrevPage}
                disabled={pageIndex === 0}
                className="h-8 w-8 p-0"
              >
                <ChevronLeft className="size-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleNextPage}
                disabled={!result.nextCursor}
                className="h-8 w-8 p-0"
              >
                <ChevronRight className="size-4" />
              </Button>
            </div>
          </div>
        </>
      )}
    </div>
  )
}
