"use client";

import * as React from "react";
import {
  Controller,
  type Control,
  type UseFormWatch,
  type UseFormSetValue,
} from "react-hook-form";

import { ReactSelect } from "@/components/ui/react-select";
import { FieldLabel } from "./deal-form-helpers";
import { useGetTimelineIntentsQuery } from "@/api/rtk";
import { type AddDealFormValues } from "./add-deal-form-schema";

interface TimelineIntentFieldProps {
  control: Control<AddDealFormValues>;
  watch: UseFormWatch<AddDealFormValues>;
  setValue: UseFormSetValue<AddDealFormValues>;
  isOpen: boolean;
}

export function TimelineIntentField({
  control,
  watch: _watch,
  setValue: _setValue,
  isOpen,
}: TimelineIntentFieldProps) {
  const { data: timelineIntents = [] } = useGetTimelineIntentsQuery(
    undefined,
    { skip: !isOpen },
  );

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

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