"use client"

import { useEffect, useMemo } from "react"
import { IconFolders, IconFolder } from "@tabler/icons-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { cn } from "@/lib/utils"
import { useTicketCategories } from "@/hooks/use-ticket-categories"
import type { TicketCategory } from "@/lib/schemas/category"

const triggerClass =
  "flex h-9 w-full items-center justify-between rounded-lg border border-slate-300 bg-white px-3 text-sm font-medium text-neutral-800 shadow-sm transition focus:ring-0 data-[state=open]:border-[#00d6eb]"
const contentClass = "rounded-xl border border-slate-200 bg-white text-neutral-800 shadow-md"
const itemClass =
  "flex items-center justify-between gap-2 rounded-md px-2 py-2 text-sm text-neutral-800 transition data-[state=checked]:bg-[#00e8ff]/15 data-[state=checked]:text-neutral-900 focus:bg-[#00e8ff]/10"

interface CategorySelectProps {
  tenantId: string
  categoryId: string | null
  subcategoryId: string | null
  onCategoryChange: (categoryId: string) => void
  onSubcategoryChange: (subcategoryId: string) => void
  autoSelectFirst?: boolean
  disabled?: boolean
  categoryLabel?: string
  subcategoryLabel?: string
  className?: string
  secondaryEmptyLabel?: string
  layout?: "grid" | "stacked"
}

function findCategory(categories: TicketCategory[], categoryId: string | null) {
  if (!categoryId) return null
  return categories.find((category) => category.id === categoryId) ?? null
}

export function CategorySelectFields({
  tenantId,
  categoryId,
  subcategoryId,
  onCategoryChange,
  onSubcategoryChange,
  autoSelectFirst = true,
  disabled = false,
  categoryLabel = "Primária",
  subcategoryLabel = "Secundária",
  secondaryEmptyLabel = "Selecione uma categoria primária",
  className,
  layout = "grid",
}: CategorySelectProps) {
  const { categories, isLoading } = useTicketCategories(tenantId)
  const activeCategory = useMemo(() => findCategory(categories, categoryId), [categories, categoryId])
  const secondaryOptions = useMemo(() => activeCategory?.secondary ?? [], [activeCategory])

  useEffect(() => {
    if (!autoSelectFirst || isLoading) return
    if (categories.length === 0) return
    if (categoryId) return
    const first = categories[0]
    if (first) {
      onCategoryChange(first.id)
      const firstSecondary = first.secondary[0]
      if (firstSecondary) {
        onSubcategoryChange(firstSecondary.id)
      }
    }
  }, [autoSelectFirst, categories, categoryId, isLoading, onCategoryChange, onSubcategoryChange])

  useEffect(() => {
    if (!categoryId || secondaryOptions.length === 0) return
    const stillValid = secondaryOptions.some((item) => item.id === subcategoryId)
    if (!stillValid) {
      const first = secondaryOptions[0]
      if (first) {
        onSubcategoryChange(first.id)
      }
    }
  }, [categoryId, secondaryOptions, subcategoryId, onSubcategoryChange])

  const containerClass = layout === "stacked" ? "flex flex-col gap-3" : "grid gap-3 sm:grid-cols-2"

  return (
    <div className={cn(containerClass, className)}>
      <div className="space-y-1.5">
        <label className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
          <IconFolders className="size-3.5" /> {categoryLabel}
        </label>
        <Select
          disabled={disabled || isLoading || categories.length === 0}
          value={categoryId ?? undefined}
          onValueChange={(value) => {
            if (!value) return
            onCategoryChange(value)
          }}
        >
          <SelectTrigger className={triggerClass}>
            <SelectValue placeholder={isLoading ? "Carregando..." : "Selecione"} />
          </SelectTrigger>
          <SelectContent className={contentClass}>
            {categories.map((category) => (
              <SelectItem key={category.id} value={category.id} className={itemClass}>
                <span className="flex items-center gap-2">
                  <IconFolders className="size-4 text-neutral-500" />
                  <span className="text-sm font-medium text-neutral-800">{category.name}</span>
                </span>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
      <div className="space-y-1.5">
        <label className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
          <IconFolder className="size-3.5" /> {subcategoryLabel}
        </label>
        <Select
          disabled={disabled || secondaryOptions.length === 0}
          value={subcategoryId ?? undefined}
          onValueChange={(value) => {
            if (!value) return
            onSubcategoryChange(value)
          }}
        >
          <SelectTrigger className={triggerClass}>
            <SelectValue placeholder={secondaryOptions.length === 0 ? secondaryEmptyLabel : "Selecione"} />
          </SelectTrigger>
          <SelectContent className={contentClass}>
            {secondaryOptions.map((option) => (
              <SelectItem key={option.id} value={option.id} className={itemClass}>
                <span className="flex items-center gap-2">
                  <IconFolder className="size-4 text-neutral-500" />
                  <span className="text-sm font-medium text-neutral-800">{option.name}</span>
                </span>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    </div>
  )
}
