import * as React from "react";
import { useEvent } from "../../hooks/useEvent";

interface Props {
  id: string;
  default: string;
  onSelect: (value: string) => void;
  _display: (data: any) => string;
  staticlistOptions?: { [key: string]: string };
  _data: { id: string }[];
  placeholder?: string;
}

const Dynamic = React.forwardRef(function Dynamic(
  {
    id,
    default: defaultValue,
    _display,
    _data,
    staticlistOptions,
    onSelect,
    placeholder,
    ...props
  }: Props,
  ref: React.ForwardedRef<HTMLSelectElement>,
) {
  const [value, setValue] = React.useState(defaultValue);
  React.useEffect(() => {
    if (defaultValue) {
      setValue(defaultValue);
    }
  }, []);

  useEvent(
    id,
    "clear",
    React.useCallback(() => {
      setValue("");
    }, []),
  );

  return (
    <select
      ref={ref}
      id={id}
      value={value}
      onChange={(event) => {
        const value = event.target.value;
        setValue(value);
        onSelect && onSelect(value);
      }}
      {...props}
    >
      <option disabled key="__blank" value="">
        {placeholder || ""}
      </option>
      {_data.map((item, idx) => {
        return (
          <option key={item.id} value={item.id}>
            {_display({ __data: item, __index: idx })}
          </option>
        );
      })}
    </select>
  );
});

const Basic = React.forwardRef(function Basic(
  {
    id,
    default: defaultValue,
    onSelect,
    staticlistOptions,
    placeholder,
    ...props
  }: Props,
  ref: React.ForwardedRef<HTMLSelectElement>,
) {
  const [value, setValue] = React.useState(defaultValue);
  React.useEffect(() => {
    if (defaultValue) {
      setValue(defaultValue);
    }
    const handleClear = () => {
      setValue("");
    };
    document.addEventListener(`${id}:clear`, handleClear);
    return () => {
      document.removeEventListener(`${id}:clear`, handleClear);
    };
  }, []);

  return (
    <select
      ref={ref}
      id={id}
      value={value}
      onChange={(event) => {
        setValue(event.target.value);
        onSelect && onSelect(event.target.value);
      }}
      {...props}
    >
      <option disabled key="__blank" value="">
        {placeholder || ""}
      </option>
      {Object.values(staticlistOptions ?? {}).map((s, idx) => {
        return (
          <option key={idx} value={s}>
            {s}
          </option>
        );
      })}
    </select>
  );
});

export const Dropdown = React.forwardRef(function Dropdown(
  {
    type,
    ...props
  }: {
    type: "basic" | "dynamic";
  } & Props,
  ref: React.ForwardedRef<HTMLSelectElement>,
) {
  if (type === "dynamic") {
    return <Dynamic ref={ref} {...props} />;
  }
  return <Basic ref={ref} {...props} />;
});
