"use client";

import * as React from "react";
import {
  Controller,
  type Control,
  type UseFormSetValue,
  type UseFormGetValues,
} from "react-hook-form";
import { ReactSelect } from "@/components/ui/react-select";
import { FieldLabel } from "./deal-form-helpers";
import { useGetServicesQuery } from "@/api/rtk";
import { type AddDealFormValues } from "./add-deal-form-schema";

interface ServiceSelectFieldProps {
  control: Control<AddDealFormValues>;
  setValue: UseFormSetValue<AddDealFormValues>;
  getValues: UseFormGetValues<AddDealFormValues>;
  isOpen: boolean;
}

export function ServiceSelectField({
  control,
  setValue: _setValue,
  getValues: _getValues,
  isOpen,
}: ServiceSelectFieldProps) {
  const { data: services = [] } = useGetServicesQuery(undefined, {
    skip: !isOpen,
  });

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

  return (
    <div>
      <FieldLabel>Service</FieldLabel>
      <div className="flex items-center gap-2">
        <Controller
          name="serviceId"
          control={control}
          render={({ field }) => (
            <ReactSelect
              value={field.value || ""}
              onValueChange={field.onChange}
              options={options}
              placeholder="Select"
              triggerClassName="h-10 min-h-10 flex-1 bg-gray-50 border-gray-200 rounded-xl text-[14px] font-medium"
              contentClassName="rounded-xl"
            />
          )}
        />
      </div>
    </div>
  );
}
