"use client"

import { useState, useMemo, useCallback } from "react"
import { useMutation, useQuery } from "convex/react"
import { format } from "date-fns"
import { ptBR } from "date-fns/locale"
import { toast } from "sonner"
import {
  IconPlus,
  IconPackage,
  IconCircleCheck,
  IconClock,
  IconAlertTriangle,
  IconSearch,
  IconRefresh,
  IconBuilding,
  IconUser,
  IconTrash,
} from "@tabler/icons-react"

import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { useAuth } from "@/lib/auth-client"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Skeleton } from "@/components/ui/skeleton"
import { SearchableCombobox, type SearchableComboboxOption } from "@/components/ui/searchable-combobox"
import { DateRangeButton, type DateRangeValue } from "@/components/date-range-button"
import { DatePicker } from "@/components/ui/date-picker"
import { Textarea } from "@/components/ui/textarea"
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
import { Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription } from "@/components/ui/empty"
import { Plus } from "lucide-react"

const EQUIPAMENTO_TIPOS = [
  "NOTEBOOK",
  "DESKTOP",
  "MONITOR",
  "TECLADO",
  "MOUSE",
  "HEADSET",
  "WEBCAM",
  "IMPRESSORA",
  "SCANNER",
  "PROJETOR",
  "TABLET",
  "CELULAR",
  "ROTEADOR",
  "SWITCH",
  "OUTRO",
] as const

type Equipamento = {
  id: string
  tipo: string
  marca: string
  modelo: string
  serialNumber?: string
  patrimonio?: string
}

type EmprestimoListItem = {
  id: string
  reference: number
  clienteId: string
  clienteNome: string
  responsavelNome: string
  responsavelContato?: string
  tecnicoId: string
  tecnicoNome: string
  tecnicoEmail?: string
  equipamentos: Equipamento[]
  quantidade: number
  valor?: number
  dataEmprestimo: number
  dataFimPrevisto: number
  dataDevolucao?: number
  status: string
  observacoes?: string
  observacoesDevolucao?: string
  multaDiaria?: number
  multaCalculada?: number
  createdAt: number
  updatedAt: number
}

function getStatusText(status: string, dataFimPrevisto: number, size: "sm" | "base" = "sm") {
  const now = Date.now()
  const isAtrasado = status === "ATIVO" && now > dataFimPrevisto
  const sizeClass = size === "sm" ? "text-sm" : "text-base"

  if (isAtrasado) {
    return <span className={`${sizeClass} font-semibold text-red-600`}>Atrasado</span>
  }

  switch (status) {
    case "ATIVO":
      return <span className={`${sizeClass} font-semibold text-amber-700`}>Ativo</span>
    case "DEVOLVIDO":
      return <span className={`${sizeClass} font-semibold text-emerald-600`}>Devolvido</span>
    case "CANCELADO":
      return <span className={`${sizeClass} font-semibold text-slate-500`}>Cancelado</span>
    default:
      return null
  }
}

const ALL_VALUE = "ALL"

export function EmprestimosPageClient() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user?.tenantId ?? null
  const [searchQuery, setSearchQuery] = useState("")
  const [statusFilter, setStatusFilter] = useState<string>("all")
  const [clienteFilter, setClienteFilter] = useState<string | null>(null)
  const [dateRange, setDateRange] = useState<DateRangeValue>({ from: null, to: null })
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [isDevolverDialogOpen, setIsDevolverDialogOpen] = useState(false)
  const [isDetailsDialogOpen, setIsDetailsDialogOpen] = useState(false)
  const [selectedEmprestimoId, setSelectedEmprestimoId] = useState<string | null>(null)
  const [selectedEmprestimoForDetails, setSelectedEmprestimoForDetails] = useState<EmprestimoListItem | null>(null)

  // Form states
  const [formClienteId, setFormClienteId] = useState<string | null>(null)
  const [formResponsavelNome, setFormResponsavelNome] = useState("")
  const [formResponsavelContato, setFormResponsavelContato] = useState("")
  const [formTecnicoId, setFormTecnicoId] = useState<string | null>(null)
  const [formDataEmprestimo, setFormDataEmprestimo] = useState<string | null>(format(new Date(), "yyyy-MM-dd"))
  const [formDataFim, setFormDataFim] = useState<string | null>(null)
  const [formValor, setFormValor] = useState("")
  const [formMultaDiaria, setFormMultaDiaria] = useState("")
  const [formObservacoes, setFormObservacoes] = useState("")
  const [formEquipamentos, setFormEquipamentos] = useState<Array<{
    id: string
    tipo: string
    marca: string
    modelo: string
    serialNumber?: string
    patrimonio?: string
  }>>([])
  const [isSubmitting, setIsSubmitting] = useState(false)

  // Queries
  const emprestimos = useQuery(
    api.emprestimos.list,
    tenantId && convexUserId
      ? {
          tenantId,
          viewerId: convexUserId as Id<"users">,
          status: statusFilter !== "all" ? statusFilter : undefined,
          clienteId: clienteFilter ? (clienteFilter as Id<"companies">) : undefined,
        }
      : "skip"
  )

  const stats = useQuery(
    api.emprestimos.getStats,
    tenantId && convexUserId
      ? { tenantId, viewerId: convexUserId as Id<"users"> }
      : "skip"
  )

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

  const agents = useQuery(
    api.users.listAgents,
    tenantId ? { tenantId } : "skip"
  )

  // Mutations
  const createEmprestimo = useMutation(api.emprestimos.create)
  const devolverEmprestimo = useMutation(api.emprestimos.devolver)

  const companyOptions = useMemo<SearchableComboboxOption[]>(() => {
    return (companies ?? []).map((c) => ({
      value: c.id,
      label: c.name,
    }))
  }, [companies])

  const userOptions = useMemo<SearchableComboboxOption[]>(() => {
    return (agents ?? []).map((u: { _id: string; name: string }) => ({
      value: u._id,
      label: u.name,
    }))
  }, [agents])

  const filteredEmprestimos = useMemo<EmprestimoListItem[]>(() => {
    if (!emprestimos) return []
    let list = emprestimos as EmprestimoListItem[]

    // Filtro por busca
    const q = searchQuery.toLowerCase().trim()
    if (q) {
      list = list.filter((e) => {
        const searchFields = [
          e.clienteNome,
          e.responsavelNome,
          e.tecnicoNome,
          String(e.reference),
          ...e.equipamentos.map((eq) => `${eq.tipo} ${eq.marca} ${eq.modelo}`),
        ]
          .join(" ")
          .toLowerCase()
        return searchFields.includes(q)
      })
    }

    // Filtro por data
    if (dateRange.from) {
      const fromDate = new Date(dateRange.from).getTime()
      list = list.filter((e) => e.dataEmprestimo >= fromDate)
    }
    if (dateRange.to) {
      const toDate = new Date(dateRange.to).getTime() + 86400000 // +1 dia para incluir o dia todo
      list = list.filter((e) => e.dataEmprestimo <= toDate)
    }

    return list
  }, [emprestimos, searchQuery, dateRange])

  const handleAddEquipamento = useCallback(() => {
    setFormEquipamentos((prev) => [
      ...prev,
      {
        id: crypto.randomUUID(),
        tipo: "NOTEBOOK",
        marca: "",
        modelo: "",
      },
    ])
  }, [])

  const handleRemoveEquipamento = useCallback((id: string) => {
    setFormEquipamentos((prev) => prev.filter((eq) => eq.id !== id))
  }, [])

  const handleEquipamentoChange = useCallback(
    (id: string, field: string, value: string) => {
      setFormEquipamentos((prev) =>
        prev.map((eq) => (eq.id === id ? { ...eq, [field]: value } : eq))
      )
    },
    []
  )

  const resetForm = useCallback(() => {
    setFormClienteId(null)
    setFormResponsavelNome("")
    setFormResponsavelContato("")
    setFormTecnicoId(null)
    setFormDataEmprestimo(format(new Date(), "yyyy-MM-dd"))
    setFormDataFim(null)
    setFormValor("")
    setFormMultaDiaria("")
    setFormObservacoes("")
    setFormEquipamentos([])
  }, [])

  const handleCreate = useCallback(async () => {
    if (!tenantId || !convexUserId) return
    if (!formClienteId || !formTecnicoId || !formDataFim || formEquipamentos.length === 0) {
      toast.error("Preencha todos os campos obrigatórios.")
      return
    }
    if (!formResponsavelNome.trim()) {
      toast.error("Informe o nome do responsável.")
      return
    }

    setIsSubmitting(true)
    try {
      const result = await createEmprestimo({
        tenantId,
        createdBy: convexUserId as Id<"users">,
        clienteId: formClienteId as Id<"companies">,
        responsavelNome: formResponsavelNome,
        responsavelContato: formResponsavelContato || undefined,
        tecnicoId: formTecnicoId as Id<"users">,
        equipamentos: formEquipamentos,
        valor: formValor ? parseFloat(formValor) : undefined,
        dataEmprestimo: formDataEmprestimo ? new Date(formDataEmprestimo).getTime() : Date.now(),
        dataFimPrevisto: new Date(formDataFim).getTime(),
        observacoes: formObservacoes || undefined,
        multaDiaria: formMultaDiaria ? parseFloat(formMultaDiaria) : undefined,
      })
      toast.success(`Empréstimo #${result.reference} criado com sucesso.`)
      setIsCreateDialogOpen(false)
      resetForm()
    } catch (error) {
      console.error("[emprestimos] Falha ao criar", error)
      toast.error("Falha ao criar empréstimo.")
    } finally {
      setIsSubmitting(false)
    }
  }, [
    tenantId,
    convexUserId,
    formClienteId,
    formTecnicoId,
    formDataFim,
    formEquipamentos,
    formResponsavelNome,
    formResponsavelContato,
    formDataEmprestimo,
    formValor,
    formMultaDiaria,
    formObservacoes,
    createEmprestimo,
    resetForm,
  ])

  const handleDevolver = useCallback(async () => {
    if (!selectedEmprestimoId || !convexUserId) return

    // Fechamento otimista - fecha dialog imediatamente
    const emprestimoId = selectedEmprestimoId
    const observacoes = formObservacoes
    setIsDevolverDialogOpen(false)
    setSelectedEmprestimoId(null)
    setFormObservacoes("")

    // Executa mutacao em background com toast de loading
    toast.promise(
      devolverEmprestimo({
        id: emprestimoId as Id<"emprestimos">,
        updatedBy: convexUserId as Id<"users">,
        observacoes: observacoes || undefined,
      }),
      {
        loading: "Registrando devolução...",
        success: (result) => {
          if (result.multaCalculada) {
            return `Empréstimo devolvido com multa de R$ ${result.multaCalculada.toFixed(2)}.`
          }
          return "Empréstimo devolvido com sucesso."
        },
        error: "Falha ao registrar devolução.",
      }
    )
  }, [selectedEmprestimoId, convexUserId, formObservacoes, devolverEmprestimo])

  const openDevolverDialog = useCallback((id: string) => {
    setSelectedEmprestimoId(id)
    setFormObservacoes("")
    setIsDevolverDialogOpen(true)
  }, [])

  const openDetailsDialog = useCallback((emp: EmprestimoListItem) => {
    setSelectedEmprestimoForDetails(emp)
    setIsDetailsDialogOpen(true)
  }, [])

  const handleClearFilters = useCallback(() => {
    setSearchQuery("")
    setStatusFilter("all")
    setClienteFilter(null)
    setDateRange({ from: null, to: null })
  }, [])

  const isLoading = !tenantId || !convexUserId

  const fieldWrap = "min-w-[180px] flex-1"
  const fieldTrigger =
    "h-10 w-full rounded-2xl border border-slate-300 bg-slate-50/80 px-3 text-left text-sm font-semibold text-neutral-700 focus:ring-neutral-300 flex items-center gap-2"
  const segmentedRoot =
    "flex h-10 min-w-[220px] flex-1 items-stretch rounded-full border border-slate-200 bg-slate-50/70 p-1 gap-1"
  const segmentedItem =
    "inline-flex h-full flex-1 items-center justify-center rounded-full first:rounded-full last:rounded-full px-4 text-sm font-semibold text-neutral-600 transition-colors hover:bg-slate-100 data-[state=on]:bg-neutral-900 data-[state=on]:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-300"

  return (
    <div className="mx-auto max-w-7xl space-y-6 px-4 lg:px-6">
      {/* Stats Cards */}
      <div className="grid gap-4 md:grid-cols-4">
        <div className="rounded-2xl border border-slate-200 bg-white/90 p-4 shadow-sm transition-colors hover:border-cyan-200/60 hover:bg-cyan-50/30">
          <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Total</p>
          {isLoading || stats === undefined ? (
            <Skeleton className="mt-2 h-7 w-12" />
          ) : (
            <p className="mt-1 text-2xl font-bold text-neutral-900">{stats.total}</p>
          )}
        </div>
        <div className="rounded-2xl border border-cyan-200/60 bg-cyan-50/40 p-4 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-cyan-600">Ativos</p>
          {isLoading || stats === undefined ? (
            <Skeleton className="mt-2 h-7 w-10" />
          ) : (
            <p className="mt-1 text-2xl font-bold text-cyan-700">{stats.ativos}</p>
          )}
        </div>
        <div className="rounded-2xl border border-red-200/60 bg-red-50/40 p-4 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-red-600">Atrasados</p>
          {isLoading || stats === undefined ? (
            <Skeleton className="mt-2 h-7 w-8" />
          ) : (
            <p className="mt-1 text-2xl font-bold text-red-700">{stats.atrasados}</p>
          )}
        </div>
        <div className="rounded-2xl border border-emerald-200/60 bg-emerald-50/40 p-4 shadow-sm">
          <p className="text-xs font-medium uppercase tracking-wide text-emerald-600">Valor ativo</p>
          {isLoading || stats === undefined ? (
            <Skeleton className="mt-2 h-7 w-24" />
          ) : (
            <p className="mt-1 text-2xl font-bold text-emerald-700">
              R$ {stats.valorTotalAtivo.toLocaleString("pt-BR", { minimumFractionDigits: 2 })}
            </p>
          )}
        </div>
      </div>

      {/* Action Button */}
      <div className="flex justify-end">
        <Button size="sm" onClick={() => setIsCreateDialogOpen(true)}>
          <Plus className="size-4" />
          Novo empréstimo
        </Button>
      </div>

      {/* Filters Section */}
      <section className="rounded-3xl border border-slate-200 bg-white/90 p-4 shadow-sm">
        <div className="flex flex-col gap-4">
          {/* Search and Date Range */}
          <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:gap-4">
            <div className="flex flex-1 flex-col gap-2">
              <div className="relative">
                <IconSearch className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-neutral-400" />
                <Input
                  placeholder="Buscar por cliente, responsável, equipamento..."
                  value={searchQuery}
                  onChange={(event) => setSearchQuery(event.target.value)}
                  className="w-full rounded-2xl border-slate-300 bg-white/95 pl-9"
                />
              </div>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <DateRangeButton
                from={dateRange.from}
                to={dateRange.to}
                onChange={setDateRange}
                className="w-full min-w-[200px] rounded-2xl border-slate-300 bg-white/95 text-left text-sm font-semibold text-neutral-700 lg:w-auto"
                align="center"
              />
              <Button
                variant="ghost"
                className="h-10 gap-2 rounded-full text-sm font-medium text-neutral-700 hover:bg-slate-100"
                onClick={handleClearFilters}
              >
                <IconRefresh className="size-4" />
                Limpar
              </Button>
            </div>
          </div>

          {/* Additional Filters */}
          <div className="flex flex-wrap gap-3">
            <div className={fieldWrap}>
              <SearchableCombobox
                value={clienteFilter}
                onValueChange={setClienteFilter}
                options={companyOptions}
                placeholder="Cliente"
                allowClear
                clearLabel="Todos os clientes"
                triggerClassName={fieldTrigger}
                prefix={<IconBuilding className="size-4 text-neutral-400" />}
                align="center"
              />
            </div>
            <ToggleGroup
              type="single"
              value={statusFilter}
              onValueChange={(value) => value && setStatusFilter(value)}
              className={segmentedRoot}
            >
              <ToggleGroupItem value="all" className={segmentedItem}>
                Todos
              </ToggleGroupItem>
              <ToggleGroupItem value="ATIVO" className={segmentedItem}>
                Ativos
              </ToggleGroupItem>
              <ToggleGroupItem value="DEVOLVIDO" className={segmentedItem}>
                Devolvidos
              </ToggleGroupItem>
            </ToggleGroup>
          </div>
        </div>
      </section>

      {/* Table Section */}
      <section className="rounded-3xl border border-slate-200 bg-white/90 shadow-sm overflow-hidden">
        <div className="overflow-x-auto">
          <Table className="w-full" style={{ tableLayout: "fixed", minWidth: "900px" }}>
            <colgroup>
              <col style={{ width: "60px" }} />
              <col style={{ width: "140px" }} />
              <col style={{ width: "120px" }} />
              <col style={{ width: "180px" }} />
              <col style={{ width: "100px" }} />
              <col style={{ width: "100px" }} />
              <col style={{ width: "90px" }} />
              <col style={{ width: "100px" }} />
              <col style={{ width: "120px" }} />
            </colgroup>
            <TableHeader className="bg-slate-100/80">
              <TableRow className="bg-transparent text-[11px] uppercase tracking-wide text-neutral-600 hover:bg-transparent">
                <TableHead className="px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Ref</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Cliente</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Responsável</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Equipamentos</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Empréstimo</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Prevista</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Status</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Valor</TableHead>
                <TableHead className="border-l border-slate-200 px-3 py-3 text-center text-[11px] font-semibold uppercase tracking-wide text-neutral-600">Ações</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading || !emprestimos ? (
                // Skeleton rows durante o loading
                Array.from({ length: 5 }).map((_, idx) => (
                  <TableRow key={`skeleton-${idx}`} className="animate-pulse">
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-8" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-24" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-20" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-28" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-16" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-16" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-14" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-4 w-16" /></TableCell>
                    <TableCell className="text-center"><Skeleton className="mx-auto h-8 w-20 rounded-full" /></TableCell>
                  </TableRow>
                ))
              ) : filteredEmprestimos.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={9} className="py-12">
                    <Empty className="border-dashed">
                      <EmptyHeader>
                        <EmptyMedia variant="icon" className="bg-slate-100 text-slate-600">
                          <IconPackage className="size-5" />
                        </EmptyMedia>
                        <EmptyTitle>Nenhum empréstimo encontrado</EmptyTitle>
                        <EmptyDescription>
                          Ajuste os filtros ou crie um novo empréstimo para começar.
                        </EmptyDescription>
                      </EmptyHeader>
                    </Empty>
                  </TableCell>
                </TableRow>
              ) : filteredEmprestimos.map((emp) => (
                  <TableRow
                    key={emp.id}
                    className="cursor-pointer transition-colors hover:bg-cyan-50/30"
                    onClick={() => openDetailsDialog(emp)}
                  >
                    <TableCell className="text-center font-semibold text-neutral-900 truncate">#{emp.reference}</TableCell>
                    <TableCell className="text-center font-medium truncate" title={emp.clienteNome}>{emp.clienteNome}</TableCell>
                    <TableCell className="text-center truncate" title={emp.responsavelNome}>{emp.responsavelNome}</TableCell>
                    <TableCell className="text-center truncate">
                      <span className="text-sm text-neutral-600">
                        {emp.quantidade} item(s):{" "}
                        {emp.equipamentos
                          .slice(0, 2)
                          .map((eq) => eq.tipo)
                          .join(", ")}
                        {emp.equipamentos.length > 2 && "..."}
                      </span>
                    </TableCell>
                    <TableCell className="text-center truncate">
                      {format(new Date(emp.dataEmprestimo), "dd/MM/yyyy", { locale: ptBR })}
                    </TableCell>
                    <TableCell className="text-center truncate">
                      {format(new Date(emp.dataFimPrevisto), "dd/MM/yyyy", { locale: ptBR })}
                    </TableCell>
                    <TableCell className="text-center truncate">{getStatusText(emp.status, emp.dataFimPrevisto)}</TableCell>
                    <TableCell className="text-center truncate">
                      {emp.valor
                        ? `R$ ${emp.valor.toLocaleString("pt-BR", { minimumFractionDigits: 2 })}`
                        : "—"}
                    </TableCell>
                    <TableCell className="text-center">
                      {emp.status === "ATIVO" ? (
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation()
                            openDevolverDialog(emp.id)
                          }}
                          className="inline-flex h-9 items-center gap-2 rounded-full border border-[#00e8fc]/30 bg-[#00e8fc]/10 px-3 text-sm font-semibold text-neutral-900 transition hover:border-[#00e8fc]/50 hover:bg-[#00e8fc]/20"
                        >
                          <IconCircleCheck className="size-4" />
                          Devolver
                        </button>
                      ) : (
                        <span className="text-neutral-400">—</span>
                      )}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
      </section>

      {/* Create Dialog */}
      <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Novo empréstimo</DialogTitle>
            <DialogDescription>
              Registre um novo empréstimo de equipamentos.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Cliente *</label>
                <SearchableCombobox
                  value={formClienteId}
                  onValueChange={setFormClienteId}
                  options={companyOptions}
                  placeholder="Selecione o cliente"
                  prefix={<IconBuilding className="size-4 text-neutral-400" />}
                />
              </div>
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Técnico responsável *</label>
                <SearchableCombobox
                  value={formTecnicoId}
                  onValueChange={setFormTecnicoId}
                  options={userOptions}
                  placeholder="Selecione o técnico"
                  prefix={<IconUser className="size-4 text-neutral-400" />}
                />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Nome do responsável (cliente) *</label>
                <Input
                  value={formResponsavelNome}
                  onChange={(e) => setFormResponsavelNome(e.target.value)}
                  placeholder="Nome do responsável"
                />
              </div>
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Contato do responsável</label>
                <Input
                  value={formResponsavelContato}
                  onChange={(e) => setFormResponsavelContato(e.target.value)}
                  placeholder="Telefone ou e-mail"
                />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Data do empréstimo</label>
                <DatePicker value={formDataEmprestimo} onChange={setFormDataEmprestimo} />
              </div>
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Data prevista devolução *</label>
                <DatePicker value={formDataFim} onChange={setFormDataFim} />
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Valor total (R$)</label>
                <Input
                  type="number"
                  step="0.01"
                  value={formValor}
                  onChange={(e) => setFormValor(e.target.value)}
                  placeholder="0,00"
                />
              </div>
              <div className="space-y-2.5">
                <label className="mb-1 block text-sm font-medium">Multa diária por atraso (R$)</label>
                <Input
                  type="number"
                  step="0.01"
                  value={formMultaDiaria}
                  onChange={(e) => setFormMultaDiaria(e.target.value)}
                  placeholder="0,00"
                />
              </div>
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <label className="text-sm font-medium">Equipamentos *</label>
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  onClick={handleAddEquipamento}
                  className="h-8 gap-1.5 rounded-full"
                >
                  <IconPlus className="size-3.5" />
                  Adicionar
                </Button>
              </div>
              {formEquipamentos.length === 0 ? (
                <div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-slate-200 py-8">
                  <IconPackage className="mb-2 size-8 text-neutral-300" />
                  <p className="text-sm text-neutral-500">Nenhum equipamento adicionado.</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {formEquipamentos.map((eq, idx) => (
                    <div key={eq.id} className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-semibold text-neutral-700">Equipamento {idx + 1}</span>
                        <Button
                          type="button"
                          size="sm"
                          variant="ghost"
                          className="h-7 gap-1 text-red-600 hover:bg-red-50 hover:text-red-700"
                          onClick={() => handleRemoveEquipamento(eq.id)}
                        >
                          <IconTrash className="size-3.5" />
                          Remover
                        </Button>
                      </div>
                      <div className="grid gap-2 md:grid-cols-4">
                        <Select
                          value={eq.tipo}
                          onValueChange={(v) => handleEquipamentoChange(eq.id, "tipo", v)}
                        >
                          <SelectTrigger className="h-9">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {EQUIPAMENTO_TIPOS.map((t) => (
                              <SelectItem key={t} value={t}>
                                {t}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <Input
                          placeholder="Marca"
                          value={eq.marca}
                          onChange={(e) => handleEquipamentoChange(eq.id, "marca", e.target.value)}
                          className="h-9"
                        />
                        <Input
                          placeholder="Modelo"
                          value={eq.modelo}
                          onChange={(e) => handleEquipamentoChange(eq.id, "modelo", e.target.value)}
                          className="h-9"
                        />
                        <Input
                          placeholder="Serial/Patrimônio"
                          value={eq.serialNumber ?? ""}
                          onChange={(e) =>
                            handleEquipamentoChange(eq.id, "serialNumber", e.target.value)
                          }
                          className="h-9"
                        />
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            <div className="space-y-2">
              <label className="text-sm font-medium">Observações</label>
              <Textarea
                value={formObservacoes}
                onChange={(e) => setFormObservacoes(e.target.value)}
                placeholder="Observações sobre o empréstimo..."
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
              Cancelar
            </Button>
            <Button onClick={handleCreate} disabled={isSubmitting}>
              {isSubmitting ? (
                <>
                  <IconRefresh className="size-4 animate-spin" />
                  Criando...
                </>
              ) : (
                "Criar empréstimo"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Devolver Dialog */}
      <Dialog open={isDevolverDialogOpen} onOpenChange={setIsDevolverDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Registrar devolução</DialogTitle>
            <DialogDescription>
              Confirme a devolução dos equipamentos emprestados.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-2">
              <label className="text-sm font-medium">Observações da devolução</label>
              <Textarea
                value={formObservacoes}
                onChange={(e) => setFormObservacoes(e.target.value)}
                placeholder="Condição dos equipamentos, observações..."
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDevolverDialogOpen(false)}>
              Cancelar
            </Button>
            <Button onClick={handleDevolver}>
              <IconCircleCheck className="size-4" />
              Confirmar devolução
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Details Dialog */}
      <Dialog open={isDetailsDialogOpen} onOpenChange={setIsDetailsDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-3">
              <span>Empréstimo #{selectedEmprestimoForDetails?.reference}</span>
              {selectedEmprestimoForDetails && getStatusText(selectedEmprestimoForDetails.status, selectedEmprestimoForDetails.dataFimPrevisto, "base")}
            </DialogTitle>
            <DialogDescription>
              Detalhes completos do empréstimo.
            </DialogDescription>
          </DialogHeader>

          {selectedEmprestimoForDetails && (
            <div className="space-y-5">
              {/* Cliente e Responsável */}
              <div className="grid gap-4 md:grid-cols-2">
                <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-2">
                  <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
                    <IconBuilding className="size-3.5" />
                    Cliente
                  </div>
                  <p className="text-sm font-medium text-neutral-900">{selectedEmprestimoForDetails.clienteNome}</p>
                </div>
                <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-2">
                  <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
                    <IconUser className="size-3.5" />
                    Responsável
                  </div>
                  <p className="text-sm font-medium text-neutral-900">{selectedEmprestimoForDetails.responsavelNome}</p>
                  {selectedEmprestimoForDetails.responsavelContato && (
                    <p className="text-xs text-muted-foreground">{selectedEmprestimoForDetails.responsavelContato}</p>
                  )}
                </div>
              </div>

              {/* Técnico */}
              <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-2">
                <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Técnico responsável</div>
                <p className="text-sm font-medium text-neutral-900">{selectedEmprestimoForDetails.tecnicoNome}</p>
                {selectedEmprestimoForDetails.tecnicoEmail && (
                  <p className="text-xs text-muted-foreground">{selectedEmprestimoForDetails.tecnicoEmail}</p>
                )}
              </div>

              {/* Datas */}
              <div className="grid gap-4 md:grid-cols-3">
                <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-1">
                  <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Data do empréstimo</div>
                  <p className="text-sm font-medium text-neutral-900">
                    {format(new Date(selectedEmprestimoForDetails.dataEmprestimo), "dd/MM/yyyy", { locale: ptBR })}
                  </p>
                </div>
                <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-1">
                  <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Devolução prevista</div>
                  <p className="text-sm font-medium text-neutral-900">
                    {format(new Date(selectedEmprestimoForDetails.dataFimPrevisto), "dd/MM/yyyy", { locale: ptBR })}
                  </p>
                </div>
                {selectedEmprestimoForDetails.dataDevolucao && (
                  <div className="rounded-xl border border-emerald-200 bg-emerald-50/50 p-3 space-y-1">
                    <div className="text-xs font-semibold uppercase tracking-wide text-emerald-600">Data da devolução</div>
                    <p className="text-sm font-medium text-emerald-700">
                      {format(new Date(selectedEmprestimoForDetails.dataDevolucao), "dd/MM/yyyy", { locale: ptBR })}
                    </p>
                  </div>
                )}
              </div>

              {/* Valores */}
              <div className="grid gap-4 md:grid-cols-3">
                {selectedEmprestimoForDetails.valor && (
                  <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-1">
                    <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Valor total</div>
                    <p className="text-sm font-medium text-neutral-900">
                      R$ {selectedEmprestimoForDetails.valor.toLocaleString("pt-BR", { minimumFractionDigits: 2 })}
                    </p>
                  </div>
                )}
                {selectedEmprestimoForDetails.multaDiaria && (
                  <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-1">
                    <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Multa diária</div>
                    <p className="text-sm font-medium text-neutral-900">
                      R$ {selectedEmprestimoForDetails.multaDiaria.toLocaleString("pt-BR", { minimumFractionDigits: 2 })}
                    </p>
                  </div>
                )}
                {selectedEmprestimoForDetails.multaCalculada && (
                  <div className="rounded-xl border border-red-200 bg-red-50/50 p-3 space-y-1">
                    <div className="text-xs font-semibold uppercase tracking-wide text-red-600">Multa aplicada</div>
                    <p className="text-sm font-medium text-red-700">
                      R$ {selectedEmprestimoForDetails.multaCalculada.toLocaleString("pt-BR", { minimumFractionDigits: 2 })}
                    </p>
                  </div>
                )}
              </div>

              {/* Equipamentos */}
              <div className="space-y-2">
                <div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-slate-500">
                  <IconPackage className="size-3.5" />
                  Equipamentos ({selectedEmprestimoForDetails.quantidade})
                </div>
                <div className="space-y-2">
                  {selectedEmprestimoForDetails.equipamentos.map((eq, idx) => (
                    <div key={eq.id} className="rounded-xl border border-slate-200 bg-white p-3">
                      <div className="flex items-start justify-between gap-3">
                        <div className="space-y-1">
                          <div className="flex items-center gap-2">
                            <Badge variant="outline" className="text-xs font-medium">
                              {eq.tipo}
                            </Badge>
                            <span className="text-sm font-medium text-neutral-900">
                              {eq.marca} {eq.modelo}
                            </span>
                          </div>
                          <div className="flex flex-wrap gap-3 text-xs text-muted-foreground">
                            {eq.serialNumber && <span>S/N: {eq.serialNumber}</span>}
                            {eq.patrimonio && <span>Patrimônio: {eq.patrimonio}</span>}
                          </div>
                        </div>
                        <span className="text-xs font-medium text-slate-400">#{idx + 1}</span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Observações */}
              {selectedEmprestimoForDetails.observacoes && (
                <div className="rounded-xl border border-slate-200 bg-slate-50/50 p-3 space-y-2">
                  <div className="text-xs font-semibold uppercase tracking-wide text-slate-500">Observações do empréstimo</div>
                  <p className="text-sm text-neutral-700 whitespace-pre-wrap">{selectedEmprestimoForDetails.observacoes}</p>
                </div>
              )}

              {/* Observações da devolução */}
              {selectedEmprestimoForDetails.observacoesDevolucao && (
                <div className="rounded-xl border border-emerald-200 bg-emerald-50/50 p-3 space-y-2">
                  <div className="text-xs font-semibold uppercase tracking-wide text-emerald-600">Observações da devolução</div>
                  <p className="text-sm text-emerald-700 whitespace-pre-wrap">{selectedEmprestimoForDetails.observacoesDevolucao}</p>
                </div>
              )}

              {/* Metadados */}
              <div className="border-t border-slate-200 pt-3 text-xs text-muted-foreground">
                <p>Criado em: {format(new Date(selectedEmprestimoForDetails.createdAt), "dd/MM/yyyy 'às' HH:mm", { locale: ptBR })}</p>
                <p>Última atualização: {format(new Date(selectedEmprestimoForDetails.updatedAt), "dd/MM/yyyy 'às' HH:mm", { locale: ptBR })}</p>
              </div>
            </div>
          )}

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDetailsDialogOpen(false)}>
              Fechar
            </Button>
            {selectedEmprestimoForDetails?.status === "ATIVO" && (
              <Button
                onClick={() => {
                  setIsDetailsDialogOpen(false)
                  openDevolverDialog(selectedEmprestimoForDetails.id)
                }}
              >
                <IconCircleCheck className="size-4" />
                Registrar devolução
              </Button>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
