// Libs
// -----------------------------------------------------------------------------
import React, { FC, useState, useEffect, useMemo } from 'react';
import { Select, SelectProps } from 'antd';

// App
// -----------------------------------------------------------------------------
import { InterfaceWithIdAndName } from 'types/default';

// Props
// -----------------------------------------------------------------------------
type SelectWithObjectValueProps = Omit<
  SelectProps,
  'value' | 'onChange' | 'options'
> & {
  value?: InterfaceWithIdAndName | undefined;
  onChange?: (value: InterfaceWithIdAndName | undefined) => void;
  options?: Array<InterfaceWithIdAndName>;
};

/**
 * Компонент на базе Ant Select для полей со значением-объектом
 */
export const SelectWithObjectValue: FC<SelectWithObjectValueProps> = ({
  value,
  onChange,
  options = [],
  ...selectProps
}) => {
  const [optionId, setOptionId] = useState<string | undefined>();

  const selectOptions = useMemo<
    Array<{ value: string | undefined; label: string }>
  >(
    () => [
      { value: undefined, label: '----' },
      ...options.map((option) => ({
        value: option.id.toString(),
        label: option.name,
      })),
    ],
    [options],
  );

  const externalOptionId = value?.id?.toString();

  useEffect(() => {
    setOptionId(externalOptionId);
  }, [externalOptionId]);

  return (
    <Select<string>
      value={optionId}
      onChange={(newValue: string) => {
        setOptionId(newValue);
        if (onChange) {
          onChange(
            options.find((option) => option.id.toString() === newValue) ??
              undefined,
          );
        }
      }}
      options={selectOptions}
      {...selectProps}
    />
  );
};
