"use client"

import { useEffect, useState } from "react"
import { ChevronDown, Loader2 } from "lucide-react"

interface CategoryOption {
  id: string
  name: string
}

interface CategorySelectProps {
  value: string
  onChange: (categoryId: string) => void
  invalid?: boolean
  disabled?: boolean
  placeholder?: string
  /** When false, the native `required` attribute is omitted (e.g. hospital form where category is optional). */
  nativeRequired?: boolean
}

export function CategorySelect({
  value,
  onChange,
  invalid = false,
  disabled = false,
  placeholder,
  nativeRequired = true,
}: CategorySelectProps) {
  const [categories, setCategories] = useState<CategoryOption[]>([])
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false
    async function load() {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await fetch("/api/admin/categories", { cache: "no-store" })
        const json = await res.json().catch(() => ({}))
        if (!res.ok) {
          throw new Error(typeof json?.error === "string" ? json.error : "Failed to load categories")
        }
        const list = Array.isArray(json?.categories) ? json.categories : []
        if (!cancelled) {
          setCategories(
            list.map((c: { id: string; name: string }) => ({
              id: c.id,
              name: c.name,
            }))
          )
        }
      } catch (e) {
        if (!cancelled) {
          setLoadError(e instanceof Error ? e.message : "Could not load categories")
          setCategories([])
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    }
    void load()
    return () => {
      cancelled = true
    }
  }, [])

  return (
    <div className="flex flex-col gap-1.5">
      <label
        htmlFor="article-category"
        className="text-xs font-bold text-foreground font-sans uppercase tracking-wider"
      >
        Category
      </label>
      {loadError && (
        <p className="text-xs text-red-500 font-sans" role="alert">
          {loadError}
        </p>
      )}
      <div className="relative">
        <select
          id="article-category"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          required={nativeRequired}
          disabled={loading || !!loadError || disabled}
          className={`w-full appearance-none bg-card border rounded-xl px-4 py-2.5 text-sm text-foreground font-sans outline-none transition-colors pr-10 cursor-pointer disabled:opacity-60 ${
            invalid
              ? "border-red-500 focus:ring-2 focus:ring-red-200 focus:border-red-500"
              : "border-border focus:ring-2 focus:ring-[#2BB673]/30 focus:border-[#2BB673]"
          }`}
        >
        <option value="">
            {loading ? "Loading categories…" : placeholder ?? "Select a category..."}
          </option>
          {categories.map((cat) => (
            <option key={cat.id} value={cat.id}>
              {cat.name}
            </option>
          ))}
        </select>
        {loading ? (
          <Loader2
            className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground animate-spin pointer-events-none"
            aria-hidden="true"
          />
        ) : (
          <ChevronDown
            className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none"
            aria-hidden="true"
          />
        )}
      </div>
      {invalid && (
        <p className="text-xs text-red-500 font-sans">Category is required.</p>
      )}
    </div>
  )
}
