"use client";

import * as React from "react";
import { ReactSelect } from "@/components/ui/react-select";
import { useGetMarketingCampaignsQuery } from "@/api/rtk/marketing-api";
import { cn } from "@/lib/utils";

type CampaignSelectProps = {
  value: string;
  onValueChange: (value: string) => void;
  label?: string;
  placeholder?: string;
  allowEmpty?: boolean;
  skip?: boolean;
  triggerClassName?: string;
  disabled?: boolean;
};

export function CampaignSelect({
  value,
  onValueChange,
  label = "Marketing campaign",
  placeholder = "Select campaign",
  allowEmpty = true,
  skip = false,
  triggerClassName,
  disabled,
}: CampaignSelectProps) {
  const { data, isLoading } = useGetMarketingCampaignsQuery(undefined, {
    skip,
  });
  const campaigns = Array.isArray(data) ? data : data?.data ?? [];

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

  return (
    <div className="flex flex-col gap-1.5">
      {label ? (
        <span className="text-[12px] font-semibold text-gray-700">{label}</span>
      ) : null}
      <ReactSelect
        value={value ?? ""}
        onValueChange={onValueChange}
        options={options}
        allowEmpty={allowEmpty}
        emptyOptionLabel="None"
        placeholder={isLoading ? "Loading…" : placeholder}
        disabled={disabled || isLoading}
        triggerClassName={cn("h-10 rounded-xl bg-gray-50", triggerClassName)}
      />
    </div>
  );
}
