"use client";

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

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

export type LeadChannelValueField = "id" | "name";

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

export function LeadChannelSelect({
  value,
  onValueChange,
  valueField = "name",
  label,
  required,
  placeholder = "Select channel",
  allowEmpty = false,
  emptyOptionLabel = "All channels",
  disabled = false,
  skip = false,
  triggerClassName,
  "aria-label": ariaLabel = "Channel",
}: LeadChannelSelectProps) {
  const { items: leadChannels, isLoading } = useLeadChannelsCatalog({ skip });

  const options = React.useMemo(
    () =>
      leadChannels.map((channel) => ({
        value: valueField === "id" ? channel.id : channel.name,
        label: channel.name,
      })),
    [leadChannels, valueField],
  );

  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>
  );
}
