"use client"

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

import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { useAuth } from "@/lib/auth-client"
import type { TicketCategory, TicketSubcategory } from "@/lib/schemas/category"
import type { Id } from "@/convex/_generated/dataModel"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"

type DeleteState<T extends "category" | "subcategory"> =
  | { type: T; targetId: string; reason: string }
  | null

export function CategoriesManager() {
  const { session, convexUserId } = useAuth()
  const tenantId = session?.user.tenantId ?? DEFAULT_TENANT_ID
  const categories = useQuery(api.categories.list, { tenantId }) as TicketCategory[] | undefined
  const [categoryName, setCategoryName] = useState("")
  const [categoryDescription, setCategoryDescription] = useState("")
  const [subcategoryDraft, setSubcategoryDraft] = useState("")
  const [subcategoryList, setSubcategoryList] = useState<string[]>([])
  const [deleteState, setDeleteState] = useState<DeleteState<"category" | "subcategory">>(null)
  const createCategory = useMutation(api.categories.createCategory)
  const deleteCategory = useMutation(api.categories.deleteCategory)
  const updateCategory = useMutation(api.categories.updateCategory)
  const createSubcategory = useMutation(api.categories.createSubcategory)
  const updateSubcategory = useMutation(api.categories.updateSubcategory)
  const deleteSubcategory = useMutation(api.categories.deleteSubcategory)

  const isCreatingCategory = useMemo(
    () => categoryName.trim().length < 2,
    [categoryName]
  )

  function addSubcategory() {
    const value = subcategoryDraft.trim()
    if (value.length < 2) {
      toast.error("Informe um nome válido para a subcategoria")
      return
    }
    const normalized = value.toLowerCase()
    const exists = subcategoryList.some((item) => item.toLowerCase() === normalized)
    if (exists) {
      toast.error("Essa subcategoria já foi adicionada")
      return
    }
    setSubcategoryList((items) => [...items, value])
    setSubcategoryDraft("")
  }

  function removeSubcategory(target: string) {
    setSubcategoryList((items) => items.filter((item) => item !== target))
  }

  async function handleCreateCategory() {
    if (!convexUserId) return
    const name = categoryName.trim()
    if (name.length < 2) {
      toast.error("Informe um nome válido para a categoria")
      return
    }
    toast.loading("Criando categoria...", { id: "category:create" })
    try {
      await createCategory({
        tenantId,
        actorId: convexUserId as Id<"users">,
        name,
        description: categoryDescription.trim() || undefined,
        secondary: subcategoryList,
      })
      toast.success("Categoria criada!", { id: "category:create" })
      setCategoryName("")
      setCategoryDescription("")
      setSubcategoryDraft("")
      setSubcategoryList([])
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível criar a categoria", { id: "category:create" })
    }
  }

  async function handleDeleteCategory(id: string) {
    if (!convexUserId) return
    toast.loading("Removendo categoria...", { id: "category:delete" })
    try {
      await deleteCategory({
        tenantId,
        actorId: convexUserId as Id<"users">,
        categoryId: id as Id<"ticketCategories">,
      })
      toast.success("Categoria removida", { id: "category:delete" })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível remover a categoria", { id: "category:delete" })
    }
  }

  async function handleUpdateCategory(target: TicketCategory, next: { name: string; description: string }) {
    if (!convexUserId) return
    const name = next.name.trim()
    if (name.length < 2) {
      toast.error("Informe um nome válido")
      return
    }
    toast.loading("Atualizando categoria...", { id: `category:update:${target.id}` })
    try {
      await updateCategory({
        tenantId,
        actorId: convexUserId as Id<"users">,
        categoryId: target.id as Id<"ticketCategories">,
        name,
        description: next.description.trim() || undefined,
      })
      toast.success("Categoria atualizada", { id: `category:update:${target.id}` })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível atualizar a categoria", { id: `category:update:${target.id}` })
    }
  }

  async function handleCreateSubcategory(categoryId: string, payload: { name: string }) {
    if (!convexUserId) return
    const name = payload.name.trim()
    if (name.length < 2) {
      toast.error("Informe um nome válido para a subcategoria")
      return
    }
    toast.loading("Adicionando subcategoria...", { id: `subcategory:create:${categoryId}` })
    try {
      await createSubcategory({
        tenantId,
        actorId: convexUserId as Id<"users">,
        categoryId: categoryId as Id<"ticketCategories">,
        name,
      })
      toast.success("Subcategoria criada", { id: `subcategory:create:${categoryId}` })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível criar a subcategoria", { id: `subcategory:create:${categoryId}` })
    }
  }

  async function handleUpdateSubcategory(target: TicketSubcategory, name: string) {
    if (!convexUserId) return
    const trimmed = name.trim()
    if (trimmed.length < 2) {
      toast.error("Informe um nome válido")
      return
    }
    toast.loading("Atualizando subcategoria...", { id: `subcategory:update:${target.id}` })
    try {
      await updateSubcategory({
        tenantId,
        actorId: convexUserId as Id<"users">,
        subcategoryId: target.id as Id<"ticketSubcategories">,
        name: trimmed,
      })
      toast.success("Subcategoria atualizada", { id: `subcategory:update:${target.id}` })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível atualizar a subcategoria", { id: `subcategory:update:${target.id}` })
    }
  }

  async function handleDeleteSubcategory(id: string) {
    if (!convexUserId) return
    toast.loading("Removendo subcategoria...", { id: `subcategory:delete:${id}` })
    try {
      await deleteSubcategory({
        tenantId,
        actorId: convexUserId as Id<"users">,
        subcategoryId: id as Id<"ticketSubcategories">,
      })
      toast.success("Subcategoria removida", { id: `subcategory:delete:${id}` })
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível remover a subcategoria", { id: `subcategory:delete:${id}` })
    }
  }

  const pendingDelete = deleteState
  const isDisabled = !convexUserId

  return (
    <div className="space-y-6">
      <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="space-y-1">
          <h3 className="text-lg font-semibold text-neutral-900">Categorias</h3>
          <p className="text-sm text-neutral-600">
            Organize a classificação primária e secundária utilizada nos tickets. Todas as alterações entram em vigor
            imediatamente para novos atendimentos.
          </p>
        </div>
        <div className="mt-4 grid gap-4 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
          <div className="space-y-3 rounded-xl border border-dashed border-slate-200 bg-white/80 p-4">
            <div className="space-y-2">
              <Label htmlFor="category-name">Nome da categoria</Label>
              <Input
                id="category-name"
                value={categoryName}
                onChange={(event) => setCategoryName(event.target.value)}
                placeholder="Ex.: Incidentes"
                disabled={isDisabled}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="category-description">Descrição (opcional)</Label>
              <Textarea
                id="category-description"
                value={categoryDescription}
                onChange={(event) => setCategoryDescription(event.target.value)}
                placeholder="Contextualize quando usar esta categoria"
                rows={3}
                disabled={isDisabled}
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="subcategory-name">Subcategorias (opcional)</Label>
              <div className="flex flex-col gap-2">
                <div className="flex flex-col gap-2 sm:flex-row">
                  <Input
                    id="subcategory-name"
                    value={subcategoryDraft}
                    onChange={(event) => setSubcategoryDraft(event.target.value)}
                    placeholder="Ex.: Lentidão"
                    disabled={isDisabled}
                    onKeyDown={(event) => {
                      if (event.key === "Enter") {
                        event.preventDefault()
                        addSubcategory()
                      }
                    }}
                  />
                  <Button
                    type="button"
                    variant="outline"
                    onClick={addSubcategory}
                    disabled={isDisabled || subcategoryDraft.trim().length < 2}
                    className="shrink-0"
                  >
                    Adicionar subcategoria
                  </Button>
                </div>
                {subcategoryList.length ? (
                  <div className="flex flex-wrap gap-2">
                    {subcategoryList.map((item) => (
                      <div
                        key={item}
                        className="group inline-flex items-center gap-2 rounded-full border border-slate-200 bg-slate-100 px-3 py-1 text-xs text-neutral-700"
                      >
                        <span>{item}</span>
                        <button
                          type="button"
                          onClick={() => removeSubcategory(item)}
                          className="rounded-full p-1 text-neutral-500 transition hover:bg-white hover:text-neutral-900"
                          disabled={isDisabled}
                        >
                          ×
                        </button>
                      </div>
                    ))}
                  </div>
                ) : null}
              </div>
            </div>
            <Button
              onClick={handleCreateCategory}
              disabled={isDisabled || isCreatingCategory}
              className="w-full sm:w-auto"
            >
              Adicionar categoria
            </Button>
          </div>
          <div className="space-y-3 rounded-xl border border-slate-200 bg-slate-50/60 p-4 text-sm text-neutral-600">
            <p className="font-medium text-neutral-800">Boas práticas</p>
            <ul className="list-disc space-y-1 pl-4">
              <li>Mantenha nomes concisos e fáceis de entender.</li>
              <li>Use a descrição para orientar a equipe sobre quando aplicar cada categoria.</li>
              <li>Subcategorias devem ser específicas e mutuamente exclusivas.</li>
            </ul>
          </div>
        </div>
      </section>

      <div className="space-y-4">
        {categories?.length ? (
          categories.map((category) => (
            <CategoryItem
              key={category.id}
              category={category}
              onUpdate={handleUpdateCategory}
              onDelete={() => setDeleteState({ type: "category", targetId: category.id, reason: "" })}
              onCreateSubcategory={handleCreateSubcategory}
              onUpdateSubcategory={handleUpdateSubcategory}
              onDeleteSubcategory={(subcategoryId) =>
                setDeleteState({ type: "subcategory", targetId: subcategoryId, reason: "" })
              }
              disabled={isDisabled}
            />
          ))
        ) : (
          <div className="rounded-xl border border-dashed border-slate-200 bg-white/60 p-6 text-center text-sm text-neutral-600">
            Nenhuma categoria cadastrada ainda.
          </div>
        )}
      </div>

      <Dialog
        open={Boolean(pendingDelete)}
        onOpenChange={(open) => {
          if (!open) setDeleteState(null)
        }}
      >
        <DialogContent className="sm:max-w-lg">
          <DialogHeader>
            <DialogTitle>Confirmar remoção</DialogTitle>
            <DialogDescription>
              A remoção é permanente. Certifique-se de que não há tickets em aberto associados.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 pt-2">
            <Label htmlFor="delete-reason">Motivo (opcional)</Label>
            <Textarea
              id="delete-reason"
              rows={3}
              placeholder="Descreva o motivo da remoção"
              value={pendingDelete?.reason ?? ""}
              onChange={(event) =>
                setDeleteState((current) =>
                  current ? { ...current, reason: event.target.value } : current
                )
              }
            />
            <p className="text-xs text-neutral-500">
              Caso existam tickets vinculados, será necessário mover para outra categoria antes de continuar.
            </p>
          </div>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setDeleteState(null)}>
              Cancelar
            </Button>
            <Button
              variant="destructive"
              onClick={async () => {
                const target = pendingDelete
                if (!target) return
                if (target.type === "category") {
                  await handleDeleteCategory(target.targetId)
                } else {
                  await handleDeleteSubcategory(target.targetId)
                }
                setDeleteState(null)
              }}
            >
              Remover
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

interface CategoryItemProps {
  category: TicketCategory
  disabled?: boolean
  onUpdate: (category: TicketCategory, next: { name: string; description: string }) => Promise<void>
  onDelete: () => void
  onCreateSubcategory: (categoryId: string, payload: { name: string }) => Promise<void>
  onUpdateSubcategory: (subcategory: TicketSubcategory, name: string) => Promise<void>
  onDeleteSubcategory: (subcategoryId: string) => void
}

function CategoryItem({
  category,
  disabled,
  onUpdate,
  onDelete,
  onCreateSubcategory,
  onUpdateSubcategory,
  onDeleteSubcategory,
}: CategoryItemProps) {
  const [isEditing, setIsEditing] = useState(false)
  const [name, setName] = useState(category.name)
  const [description, setDescription] = useState(category.description ?? "")
  const [subcategoryDraft, setSubcategoryDraft] = useState("")
  const hasSubcategories = category.secondary.length > 0

  async function handleSave() {
    await onUpdate(category, { name, description })
    setIsEditing(false)
  }

  return (
    <div className="space-y-4 rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="space-y-1">
          {isEditing ? (
            <div className="flex flex-col gap-2">
              <Input value={name} onChange={(event) => setName(event.target.value)} disabled={disabled} />
              <Textarea
                value={description}
                onChange={(event) => setDescription(event.target.value)}
                rows={2}
                placeholder="Descrição"
                disabled={disabled}
              />
            </div>
          ) : (
            <>
              <h4 className="text-base font-semibold text-neutral-900">{category.name}</h4>
              {category.description ? (
                <p className="text-sm text-neutral-600">{category.description}</p>
              ) : null}
            </>
          )}
        </div>
        <div className="flex items-center gap-2">
          {hasSubcategories ? (
            <Badge variant="outline" className="rounded-full border-slate-200 px-3 py-1 text-xs text-neutral-600">
              {category.secondary.length} subcategorias
            </Badge>
          ) : null}
          {isEditing ? (
            <div className="flex items-center gap-2">
              <Button size="sm" onClick={handleSave} disabled={disabled}>
                Salvar
              </Button>
              <Button size="sm" variant="outline" onClick={() => setIsEditing(false)}>
                Cancelar
              </Button>
            </div>
          ) : (
            <div className="flex items-center gap-2">
              <Button size="sm" variant="outline" onClick={() => setIsEditing(true)} disabled={disabled}>
                Editar
              </Button>
              <Button size="sm" variant="destructive" onClick={onDelete} disabled={disabled}>
                Remover
              </Button>
            </div>
          )}
        </div>
      </div>
      <div className="space-y-3">
        <p className="text-xs font-semibold uppercase tracking-wide text-neutral-500">Subcategorias</p>
        <div className="space-y-2">
          {category.secondary.length ? (
            category.secondary.map((subcategory) => (
              <SubcategoryItem
                key={subcategory.id}
                subcategory={subcategory}
                disabled={disabled}
                onUpdate={(value) => onUpdateSubcategory(subcategory, value)}
                onDelete={() => onDeleteSubcategory(subcategory.id)}
              />
            ))
          ) : (
            <div className="rounded-lg border border-dashed border-slate-200 bg-slate-50/60 p-3 text-sm text-neutral-600">
              Nenhuma subcategoria cadastrada.
            </div>
          )}
        </div>
        <div className="flex flex-col gap-2 rounded-lg border border-dashed border-slate-200 bg-white p-3">
          <Label className="text-xs uppercase tracking-wide text-neutral-500">Nova subcategoria</Label>
          <div className="flex flex-col gap-2 sm:flex-row">
            <Input
              value={subcategoryDraft}
              onChange={(event) => setSubcategoryDraft(event.target.value)}
              placeholder="Ex.: Configuração"
              disabled={disabled}
            />
            <Button
              size="sm"
              className="sm:w-auto"
              onClick={async () => {
                if (!subcategoryDraft.trim()) return
                await onCreateSubcategory(category.id, { name: subcategoryDraft })
                setSubcategoryDraft("")
              }}
              disabled={disabled || subcategoryDraft.trim().length < 2}
            >
              Adicionar
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}

interface SubcategoryItemProps {
  subcategory: TicketSubcategory
  disabled?: boolean
  onUpdate: (nextValue: string) => Promise<void>
  onDelete: () => void
}

function SubcategoryItem({ subcategory, disabled, onUpdate, onDelete }: SubcategoryItemProps) {
  const [isEditing, setIsEditing] = useState(false)
  const [name, setName] = useState(subcategory.name)

  async function handleSave() {
    await onUpdate(name)
    setIsEditing(false)
  }

  return (
    <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-slate-200 bg-white px-3 py-2 shadow-sm">
      {isEditing ? (
        <Input value={name} onChange={(event) => setName(event.target.value)} disabled={disabled} className="max-w-sm" />
      ) : (
        <span className="text-sm font-medium text-neutral-800">{subcategory.name}</span>
      )}
      <div className="flex items-center gap-2">
        {isEditing ? (
          <>
            <Button size="sm" onClick={handleSave} disabled={disabled}>
              Salvar
            </Button>
            <Button size="sm" variant="outline" onClick={() => setIsEditing(false)}>
              Cancelar
            </Button>
          </>
        ) : (
          <>
            <Button size="sm" variant="outline" onClick={() => setIsEditing(true)} disabled={disabled}>
              Renomear
            </Button>
            <Button size="sm" variant="destructive" onClick={onDelete} disabled={disabled}>
              Remover
            </Button>
          </>
        )}
      </div>
    </div>
  )
}
