"use client";

import * as React from "react";
import { ReactSelect } from "@/components/ui/react-select";
import { cn } from "@/lib/utils";
import { useDivisionsCatalog } from "@/hooks/use-divisions-catalog";

const formTriggerClass =
  "h-10 min-h-10 flex-1 bg-gray-50 border-gray-200 rounded-xl text-[14px] font-medium";

export interface DivisionSelectProps {
  value: string;
  onValueChange: (value: string) => void;
  label?: React.ReactNode;
  required?: boolean;
  placeholder?: string;
  allowEmpty?: boolean;
  emptyOptionLabel?: string;
  disabled?: boolean;
  skip?: boolean;
  triggerClassName?: string;
  "aria-label"?: string;
}

export function DivisionSelect({
  value,
  onValueChange,
  label,
  required,
  placeholder = "Select division",
  allowEmpty = false,
  emptyOptionLabel = "All divisions",
  disabled = false,
  skip = false,
  triggerClassName,
  "aria-label": ariaLabel = "Division",
}: DivisionSelectProps) {
  const { items: divisions, isLoading } = useDivisionsCatalog({ skip });

  const options = React.useMemo(
    () => divisions.map((division) => ({ value: division.id, label: division.name })),
    [divisions],
  );

  return (
    <div>
      {label != null && (
        <label className="block text-[10px] font-bold text-gray-400 uppercase tracking-[0.09em] font-['Lexend_Deca'] mb-1.5 select-none">
          {label}
          {required && <span className="text-red-500 ml-0.5">*</span>}
        </label>
      )}
      <ReactSelect
        value={value}
        onValueChange={onValueChange}
        options={options}
        placeholder={isLoading ? "Loading…" : placeholder}
        allowEmpty={allowEmpty}
        emptyOptionLabel={emptyOptionLabel}
        disabled={disabled || isLoading}
        triggerClassName={cn(formTriggerClass, triggerClassName)}
        contentClassName="rounded-xl"
        aria-label={ariaLabel}
      />
    </div>
  );
}
