// src/components/TagEditor/index.tsx

import { PlusOutlined } from '@ant-design/icons';
import type { TagProps } from 'antd';
import { Input, Space, Tag } from 'antd';
import React, { useMemo, useState } from 'react';

interface TagEditorProps {
  value?: string[];
  onChange?: (value: string[], active?: number) => void;
  placeholder?: string;
  maxCount?: number;
  tagProps?: TagProps;
  disabled?: boolean;
  editable?: boolean;
}

const TagEditor: React.FC<TagEditorProps> = ({
  value = [],
  onChange,
  placeholder = '请输入标签',
  maxCount,
  tagProps,
  editable = true,
  disabled = false,
}) => {
  // const [tags, setTags] = useState<string[]>(value);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');

  const tags = useMemo(() => {
    console.log(value);

    return value || [];
  }, [value]);

  const handleClose = (removedTag: string) => {
    const active = tags.indexOf(removedTag);
    const newTags = tags.filter((tag) => tag !== removedTag);
    onChange?.(newTags, active);
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && !tags.includes(inputValue)) {
      const newTags = [...tags, inputValue];
      onChange?.(newTags);
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleInputBlur = () => {
    handleInputConfirm();
  };

  const canAddMore = !maxCount || tags.length < maxCount;

  return (
    <Space wrap style={{ width: '100%' }}>
      {tags.map((tag) => (
        <Tag
          key={tag}
          closable={!disabled}
          onClose={() => handleClose(tag)}
          {...tagProps}
        >
          {tag}
        </Tag>
      ))}

      {inputVisible ? (
        <Input
          type="text"
          size="small"
          style={{ width: 110 }}
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputBlur}
          onPressEnter={handleInputConfirm}
          placeholder={placeholder}
          autoFocus
        />
      ) : (
        canAddMore &&
        editable &&
        !disabled && (
          <Tag
            onClick={showInput}
            style={{
              background: '#fff',
              borderStyle: 'dashed',
              cursor: 'pointer',
            }}
          >
            <PlusOutlined /> 添加标签
          </Tag>
        )
      )}
    </Space>
  );
};

export default TagEditor;
