"use client"

import { useMemo, useState } from "react"
import { useQuery } from "convex/react"

import { api } from "@/convex/_generated/api"
import type { TicketCategory } from "@/lib/schemas/category"
import { useAuth } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import type { Id } from "@/convex/_generated/dataModel"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"

import { CategorySlaDrawer } from "./category-sla-drawer"

export function CategorySlaManager() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const viewerId = convexUserId ? (convexUserId as Id<"users">) : null

  const categories = useQuery(api.categories.list, { tenantId }) as TicketCategory[] | undefined
  const [selectedCategory, setSelectedCategory] = useState<TicketCategory | null>(null)

  const sortedCategories = useMemo(() => {
    if (!categories) return []
    return [...categories].sort((a, b) => a.name.localeCompare(b.name, "pt-BR"))
  }, [categories])

  return (
    <>
      <Card className="border-slate-200">
        <CardHeader>
          <CardTitle className="text-lg font-semibold text-neutral-900">SLA por categoria</CardTitle>
          <CardDescription>
            Ajuste metas específicas por prioridade para cada categoria. Útil quando determinados temas exigem prazos
            diferentes das políticas gerais.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {categories === undefined ? (
            <div className="space-y-2">
              {Array.from({ length: 3 }).map((_, index) => (
                <Skeleton key={`category-sla-skeleton-${index}`} className="h-16 rounded-xl" />
              ))}
            </div>
          ) : sortedCategories.length === 0 ? (
            <p className="text-sm text-neutral-600">
              Cadastre categorias em <strong>Admin ▸ Campos personalizados</strong> para liberar esta configuração.
            </p>
          ) : (
            <div className="space-y-3">
              {sortedCategories.map((category) => (
                <div
                  key={category.id}
                  className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-200 bg-white px-4 py-3"
                >
                  <div className="space-y-1">
                    <p className="text-sm font-semibold text-neutral-900">{category.name}</p>
                    {category.description ? (
                      <p className="text-xs text-neutral-500">{category.description}</p>
                    ) : null}
                    {category.secondary.length ? (
                      <Badge variant="outline" className="rounded-full border-slate-200 px-3 py-1 text-xs font-semibold">
                        {category.secondary.length} subcategorias
                      </Badge>
                    ) : null}
                  </div>
                  <Button
                    size="sm"
                    variant="secondary"
                    onClick={() => setSelectedCategory(category)}
                    className="shrink-0"
                    disabled={!viewerId}
                  >
                    Configurar SLA
                  </Button>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      <CategorySlaDrawer
        category={selectedCategory}
        tenantId={tenantId}
        viewerId={viewerId}
        onClose={() => setSelectedCategory(null)}
      />
    </>
  )
}
