import React, { useContext, useMemo, useState } from "react";
import { StarFilled, StarOutlined } from "@easyv/react-icons";
import { FontContext } from "config-provider";
import { Select } from "easy-design";
import styles from "./index.less";

const defaultFonts = [
  {
    name: "微软雅黑",
    value: "Microsoft Yahei",
  },
  {
    name: "宋体",
    value: "SimSun",
  },
  {
    name: "黑体",
    value: "SimHei",
  },
  {
    name: "楷体",
    value: "KaiTi",
  },
  {
    name: "隶书",
    value: "LiSu",
  },
  {
    name: "幼圆",
    value: "YouYuan",
  },
  {
    name: "Tahoma",
    value: "Tahoma",
  },
  {
    name: "Arial",
    value: "Arial",
  },
  {
    name: "sans-serif",
    value: "sans-serif",
  },
  {
    name: "Helvetica",
    value: "Helvetica",
  },
];

const { Option } = Select;

export default function EasyFont(props) {
  const { value, onChange } = props;
  const [search, setSearch] = useState("");
  const { fonts, onFavoriteFont } = useContext(FontContext);
  const options = useMemo(() => {
    if (onFavoriteFont) {
      return fonts || defaultFonts;
    }
    return fonts ? defaultFonts.concat(fonts) : defaultFonts;
  }, [fonts, onFavoriteFont]);

  const resultOptions = useMemo(
    () => (search ? options.filter((d) => d.name.includes(search)) : options),
    [search, options],
  );

  const handleSearch = (value) => {
    setSearch(value);
  };

  const handleChange = (value) => {
    onChange(value);
    setSearch("");
  };

  return (
    <Select
      value={value}
      showSearch={options.length > 10}
      onSearch={options.length > 10 && handleSearch}
      placeholder="请选择字体"
      dropdownMatchSelectWidth={210}
      dropdownClassName={styles.fonts}
      filterOption={false}
      onChange={handleChange}
    >
      {resultOptions?.map((o) => (
        <Option value={o.value} key={o.value} label={o.name}>
          {onFavoriteFont ? (
            <div className={styles.iconOption}>
              <div className={styles.optionName} title={o.name}>
                {o.name}
              </div>
              <div
                className={styles.collect}
                onClick={(e) => {
                  e.stopPropagation();
                  onFavoriteFont?.(o);
                }}
              >
                {o.collect ? (
                  <StarFilled className={styles.icon} />
                ) : (
                  <StarOutlined className={styles.unIcon} />
                )}
              </div>
            </div>
          ) : (
            o.name
          )}
        </Option>
      ))}
    </Select>
  );
}
