import React, { useEffect } from "react";
import { ListLangBySearchKey, ListLangByKey } from "@/api";
import { useRequest } from "umi";
import { AutoComplete } from "antd";

interface LanItem {
  en: string;
  key: string;
  ["zh-CN"]: string;
}
export default function LangInput({
  value,
  onChange,
  disabled,
  style,
}: {
  value?: Record<string, string>[] | string;
  onChange?: (value: Record<string, string>[], key?: string) => void;
  disabled?: boolean;
  style?: React.CSSProperties;
}) {
  const [lanOptions, setLanOptions] = React.useState<any[]>([]);

  const [formModel, setFormModel] = React.useState(
    Array.isArray(value)
      ? {
          langText: "",
          en: value.find((item) => item.name === "en")?.value || "",
          ["zh-CN"]: value.find((item) => item.name === "zh-CN")?.value || "",
        }
      : {
          langText: "",
          en: "",
          ["zh-CN"]: "",
        }
  );

  useEffect(() => {
    if (formModel.langText || formModel.en || formModel["zh-CN"]) return;

    if (typeof value === "string" && value) {
      ListLangByKey({ key: value }).then((res) => {
        if (res?.result) {
          setFormModel({
            langText: res.result.key,
            en: res.result?.en,
            ["zh-CN"]: res.result?.["zh-CN"],
          });
        }
      });
    }
  }, [value, formModel]);

  const { run } = useRequest(ListLangBySearchKey, {
    manual: true,
    onSuccess(data, params) {
      setLanOptions(
        (data.result || []).map((item: LanItem) => ({
          ...item,
          label: `${item.en || ""}[zh-CN:${item["zh-CN"]}]`,
          value: item[params[0].searchLan],
        }))
      );
    },
  });

  const handleSearch = (serchKey: string, searchLan: "en" | "zh-CN") => {
    run({
      maxCount: 10,
      searchKey: serchKey,
      searchLan,
    });
  };

  const handleSelectLang = (option: LanItem) => {
    setFormModel(() => {
      return {
        ...formModel,
        langText: option.key,
        en: option?.en,
        ["zh-CN"]: option?.["zh-CN"],
      };
    });
  };

  const handleChange = (key: "en" | "zh-CN", val: string) => {
    setFormModel(() => {
      return {
        ...formModel,
        langText: "",
        [key]: val,
      };
    });
  };

  useEffect(() => {
    onChange?.(
      [
        { name: "en", value: formModel.en },
        { name: "zh-CN", value: formModel["zh-CN"] },
      ],
      formModel.langText
    );
  }, [formModel]);

  return (
    <div>
      <div>
        <AutoComplete
          allowClear
          placeholder="中文"
          options={lanOptions}
          onSearch={(val) => handleSearch(val, "zh-CN")}
          value={formModel["zh-CN"]}
          onChange={(val) => handleChange("zh-CN", val)}
          onSelect={(_val, opt) => handleSelectLang(opt)}
          disabled={disabled}
          style={style}
        />
      </div>
      <div>
        <AutoComplete
          allowClear
          style={{ width: "100%", ...(style || {}) }}
          placeholder="英文"
          options={lanOptions}
          onSearch={(val) => handleSearch(val, "en")}
          value={formModel.en}
          onChange={(val) => handleChange("en", val)}
          onSelect={(_val, opt) => handleSelectLang(opt)}
          disabled={disabled}
        />
      </div>
    </div>
  );
}
