import React, { useEffect, useState, useCallback } from "react";
import Select from "../common/Select";
import Option from "../common/option";
import { GeneralIdRef, MakeGeneralIdRef } from "../../utils/GeneralIdRef";
import formsService from "../../modules/manager/forms/services/formsService";

interface FormTemplatePickerProps {
  includeLabel?: boolean;
  name: string;
  label: string;
  error?: string;
  value?: GeneralIdRef;
  onChange?: (name: string, value: GeneralIdRef) => void;
}

export default function FormTemplatePicker({
  includeLabel,
  name,
  label,
  error,
  value,
  onChange,
}: FormTemplatePickerProps) {
  const [options, setOptions] = useState<Option[]>([]);

  useEffect(() => {
    async function load() {
      const formTemplates = await formsService.getForms(0, 10, "name", true);
      if (formTemplates) {
        const opts: Option[] = (formTemplates.data as any[]).map((x) => ({
          _id: x.id,
          name: x.name,
        }));
        setOptions(opts);
      }
    }

    load();
  }, []);

  const doOnChange = useCallback(
    (n: string, v: bigint) => {
      const generalIdRef = MakeGeneralIdRef(v);
      if (onChange) onChange(n, generalIdRef);
    },
    [onChange],
  );

  const handleChange = useCallback(
    (e: React.ChangeEvent<HTMLSelectElement>) => {
      const input = e.currentTarget;
      doOnChange(input.name, BigInt(input.value));
    },
    [doOnChange],
  );

  let id = "";
  if (value !== undefined && !Number.isNaN(value.id)) {
    id = String(value.id);
  }

  return (
    <Select
      includeLabel={includeLabel}
      name={name}
      label={label}
      error={error}
      value={id}
      options={options}
      includeBlankFirstEntry={true}
      onChange={handleChange}
    />
  );
}
