import React, { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getTemplates, getCategorys } from 'models/template';
import { PreviewModal } from './PreviewModal';
import OftenTemplates, { oftenTemplates } from './OftenTemplates';
import TemplateItem from './TemplateItem';
import { Select } from '@easyv/antd';
import { Input, ConfigProvider } from '@easyv/react-gui';

import styles from './TemplateList.less';

const { Search } = Input;
const { Option } = Select;

export default function TemplateList({ userId, onClick }) {
  const [previewIndex, setPreviewIndex] = useState<number | null>(null);
  const [searchType, setSearchType] = useState<number>(0);
  const [searchText, setSearchText] = useState<string>('');
  const dispatch = useDispatch();

  const { categorys, templates } = useSelector((state: any) => ({
    categorys: [{ id: 0, name: '所有模板' }].concat(state.templates.categorys),
    templates: state.templates.list.filter((d) => d.published),
  }));

  useEffect(() => {
    dispatch(getTemplates());
    dispatch(getCategorys());
  }, []);

  const handleClick = (templateId) => {
    if (templateId) {
      oftenTemplates.add(userId, templateId);
    }
    onClick(templateId);
  };

  const filterTemplate = (filterParam: number) => {
    if (filterParam === 0) {
      return templates;
    }
    return templates.filter((item) => item.categoryId === filterParam);
  };

  const renderTemplate = useCallback(() => {
    const data = filterTemplate(searchType);

    return data
      .filter((d) => d.name.toLowerCase().includes(searchText?.toLowerCase()))
      .map((item) => {
        return (
          <TemplateItem
            category={item.category}
            key={item.id}
            thumb={item.thumb}
            name={item.name}
            info={item.info}
            purchased={item.purchased}
            onCreate={() => handleClick(item.id)}
            onPreview={() => {
              setPreviewIndex(templates.findIndex((p) => p.id === item.id));
            }}
            type={item.measureType}
          />
        );
      });
  }, [searchType, searchText, templates]);

  const renderSearchText = useCallback(() => {
    const data = filterTemplate(searchType);
    const length = data.filter((d) =>
      d.name.toLowerCase().includes(searchText?.toLowerCase()),
    ).length;
    return (
      <>
        <span style={{ marginLeft: '11px' }}>搜索</span>
        <a
          style={{
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            maxWidth: '300px',
            display: 'inline-block',
          }}>{`"${searchText}"`}</a>
        <span>
          {length}
          个结果
        </span>
      </>
    );
  }, [searchType, searchText, templates]);
  return (
    <ConfigProvider>
      <div className={styles.container}>
        <OftenTemplates userId={userId} list={templates} onClick={handleClick} />
        {templates.length > 0 && (
          <>
            <div className={styles.title}>
              <div className={styles.sort_wrapper} id="sort_wrapper">
                <span>我的模板</span>
                {searchText ? (
                  renderSearchText()
                ) : (
                  <Select
                    dropdownClassName={styles.dropClass}
                    className={styles.option}
                    getPopupContainer={() =>
                      document.getElementById('sort_wrapper') || document.body
                    }
                    onChange={(e) => {
                      setSearchType(e);
                    }}
                    defaultValue={searchType}
                    value={searchType}
                    style={{ display: 'inline-block' }}
                    bordered={false}>
                    {categorys.map((item) => (
                      <Option label={item.name} key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </div>
              <div>
                <Search
                  onBlur={(e) => setSearchText(e.target.value)}
                  onSearch={(e) => setSearchText(e)}
                  className={styles.search_input}
                  placeholder="搜索"
                  style={{ width: 226 }}
                />
              </div>
            </div>
            <div className={styles.group}>{renderTemplate()}</div>
          </>
        )}

        {previewIndex !== null && (
          <PreviewModal
            list={templates}
            current={previewIndex}
            visible
            onClick={handleClick}
            onClose={() => setPreviewIndex(null)}
          />
        )}
      </div>
    </ConfigProvider>
  );
}
