import {FilterGroupMap} from '@components';
import {FormEventHandler, useEffect, useMemo, useState} from 'react';

export function useTransfer(
  map: FilterGroupMap<any>,
  data: string,
  options: {onConfirm: (val: string) => void; onClose: () => void},
) {
  const {onConfirm, onClose} = options;

  const [selected, setSelected] = useState<string[]>(data.split(','));

  useEffect(
    function () {
      setSelected(data.split(','));
    },
    [data],
  );

  const dataSourece = useMemo(
    function () {
      const data: {id: string; label: string}[] = [];

      map.forEach(function ({label}, id) {
        data.push({id: String(id), label});
      });

      return data;
    },
    [map],
  );

  const onSubmit: FormEventHandler<HTMLFormElement> = function (e) {
    e.preventDefault();
    onConfirm(selected.join(','));
    onClose();
  };

  return [
    {selected, dataSourece},
    {onChange: setSelected, onSubmit},
  ] as const;
}
