import { FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { MultiSelect } from '@/components/ui/multi-select';
import { UnknownRecord } from '@/types';

type ClientCountryFieldProps = {
  field: UnknownRecord;
  clientCountries: any[];
  clearErrors: (name: string) => void;
  prev: any[];
};

export const ClientCountryField: React.FC<ClientCountryFieldProps> = ({
  field,
  clientCountries,
  clearErrors,
  prev,
}) => {
  return (
    <FormItem className="w-full md:w-1/2 lg:w-1/4 p-2">
      <FormLabel className="font-bold">
        <span className="text-red-600 pl-1">*</span>
        Client Country
      </FormLabel>
      <MultiSelect
        options={clientCountries || []}
        defaultValue={Array.isArray(prev) ? prev.map(String) : []}
        value={field.value || []}
        onValueChange={(value) => {
          const validValues = value.filter((v) =>
            clientCountries.some(
              (c: UnknownRecord) => String(c.value) === String(v),
            ),
          );
          field.onChange(validValues);
          clearErrors('client_from_countries');
        }}
        placeholder="Choose Client Country"
        maxCount={1}
      />
      <FormMessage />
    </FormItem>
  );
};
