"use client"

import * as React from "react"
import { ReactSelect } from "@/components/ui/react-select"
import { cn } from "@/lib/utils"
import { useGetProjectTypesQuery } from "@/api/rtk/deal-meta-api"

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

export interface DealTypeSelectProps {
  value: string
  onValueChange: (value: string) => void
  label?: React.ReactNode
  required?: boolean
  placeholder?: string
  allowEmpty?: boolean
  disabled?: boolean
  skip?: boolean
  triggerClassName?: string
}

export function DealTypeSelect({
  value,
  onValueChange,
  label,
  required,
  placeholder = "Select deal type",
  allowEmpty = false,
  disabled = false,
  skip = false,
  triggerClassName,
}: DealTypeSelectProps) {
  const { data: types = [] } = useGetProjectTypesQuery(undefined, { skip })

  const selectedValueMissing = React.useMemo(
    () => Boolean(value) && !types.some((type) => type.name === value),
    [types, value],
  )

  const options = React.useMemo(() => {
    const base = types.map((t) => ({ value: t.name, label: t.name }))
    if (selectedValueMissing) {
      return [{ value, label: value }, ...base]
    }
    return base
  }, [types, selectedValueMissing, value])

  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>
      )}
      <div className="flex items-center gap-2">
        <ReactSelect
          value={value}
          onValueChange={onValueChange}
          options={options}
          placeholder={placeholder}
          allowEmpty={allowEmpty}
          disabled={disabled}
          triggerClassName={cn(formTriggerClass, triggerClassName)}
          contentClassName="rounded-xl"
        />
      </div>
    </div>
  )
}
