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

interface LanItem {
  en: string;
  key: string;
  ["zh-CN"]: string;
}
export default function LangInputTextarea({
  value,
  onChange,
}: {
  value?: Record<string, string>[];
  onChange?: (value: Record<string, string>[], key?: string) => void;
}) {
  const [lanOptions, setLanOptions] = React.useState<any[]>([]);
  const [formModel, setFormModel] = React.useState({
    langText: "",
    en: value?.find(item => item.name === 'en')?.value || "",
    ["zh-CN"]: value?.find(item => item.name === 'zh-CN')?.value || "",
  });
  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
          options={lanOptions}
          onSearch={(val) => handleSearch(val, "zh-CN")}
          value={formModel["zh-CN"]}
          onChange={(val) => handleChange("zh-CN", val)}
          onSelect={(_val, opt) => handleSelectLang(opt)}
        >
          <Input.TextArea placeholder="中文..." value={formModel["zh-CN"]}/>
        </AutoComplete>
      </div>
      <div>
        <AutoComplete
          allowClear
          style={{ width: "100%" }}
          options={lanOptions}
          onSearch={(val) => handleSearch(val, "en")}
          value={formModel.en}
          onChange={(val) => handleChange("en", val)}
          onSelect={(_val, opt) => handleSelectLang(opt)}
        >
          <Input.TextArea placeholder="英文..." value={formModel.en}/>
        </AutoComplete>
      </div>
    </div>
  );
}
