import React, { useState, useEffect } from 'react';
import { Button, Modal, Table, Input, Tag, Space } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import './CategorySelector.less';

interface CategorySelectorProps {
  value?: string | string[];
  onChange?: (value: string | string[]) => void;
  disabled?: boolean;
  multiple?: boolean; // 是否多选，默认为多选
}

interface CategoryItem {
  id: string;
  name: string;
  code: string;
}

const CategorySelector: React.FC<CategorySelectorProps> = ({
  value = [],
  onChange,
  disabled = false,
  multiple = true
}) => {
  const [visible, setVisible] = useState<boolean>(false);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [categoryData, setCategoryData] = useState<CategoryItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState<string>('');

  // 初始化数据
  useEffect(() => {
    // 将输入值转换为数组
    const valueArray = Array.isArray(value) ? value : value ? [value] : [];

    // 只有当value真正变化时才更新状态
    if (JSON.stringify(valueArray) !== JSON.stringify(selectedCategories)) {
      setSelectedCategories(valueArray);
      // 将选中的品类ID转换为rowKey数组
      const selectedKeys = valueArray.map(categoryId => {
        return categoryId;
      }).filter(Boolean);
      setSelectedRowKeys(selectedKeys);
    }
  }, [value]);

  // 模拟获取品类数据
  useEffect(() => {
    // 模拟API请求
    const mockData: CategoryItem[] = [
      { id: '1', name: '电子', code: 'DZ001' },
      { id: '2', name: '机械', code: 'JX001' },
      { id: '3', name: '化工', code: 'HG001' },
      { id: '4', name: '医药', code: 'YY001' },
      { id: '5', name: '食品', code: 'SP001' },
      { id: '6', name: '服装', code: 'FZ001' },
      { id: '7', name: '建材', code: 'JC001' },
      { id: '8', name: '家电', code: 'JD001' },
      { id: '9', name: '汽车', code: 'QC001' },
      { id: '10', name: '能源', code: 'NY001' },
    ];
    setCategoryData(mockData);

    // 初始化选中的行
    const valueArray = Array.isArray(value) ? value : value ? [value] : [];
    if (valueArray.length > 0) {
      setSelectedRowKeys(valueArray);
    }
  }, []);

  // 打开选择弹窗
  const showModal = () => {
    if (disabled) return;
    setVisible(true);
  };

  // 处理确认选择
  const handleOk = () => {
    // 根据selectedRowKeys获取对应的品类数据
    const selectedIds = selectedRowKeys as string[];

    // 只有当选择真正变化时才触发onChange
    if (JSON.stringify(selectedIds) !== JSON.stringify(selectedCategories)) {
      setSelectedCategories(selectedIds);
      if (onChange) {
        // 如果是单选模式，返回第一个选中的值，否则返回数组
        onChange(multiple ? selectedIds : selectedIds[0] || '');
      }
    }

    setVisible(false);
  };

  // 处理取消选择
  const handleCancel = () => {
    // 恢复到打开弹窗前的选择状态
    const valueArray = Array.isArray(value) ? value : value ? [value] : [];
    setSelectedRowKeys(valueArray);
    setVisible(false);
  };

  // 处理搜索
  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchValue(e.target.value);
  };

  // 过滤数据
  const filteredData = categoryData.filter(item =>
    item.name.toLowerCase().includes(searchValue.toLowerCase()) ||
    item.code.toLowerCase().includes(searchValue.toLowerCase())
  );

  // 获取已选择的品类名称
  const getSelectedCategoryNames = () => {
    if (!selectedCategories || !Array.isArray(selectedCategories)) {
      return [];
    }

    return selectedCategories.map(categoryId => {
      const category = categoryData.find(item => item.id === categoryId);
      return category ? category.name : '';
    }).filter(Boolean);
  };

  const columns = [
    {
      title: '品类编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '品类名称',
      dataIndex: 'name',
      key: 'name',
    },
  ];

  // 表格行选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      // 如果是单选模式，只保留最后选择的一项
      if (!multiple && newSelectedRowKeys.length > 0) {
        setSelectedRowKeys([newSelectedRowKeys[newSelectedRowKeys.length - 1]]);
      } else {
      setSelectedRowKeys(newSelectedRowKeys);
      }
    },
    type: multiple ? 'checkbox' as const : 'radio' as const,
  };

  return (
    <div className="category-selector">
      <div className="selector-trigger" onClick={showModal}>
        <Button disabled={disabled} type="link">选择</Button>
        <div className="selected-categories">
          {getSelectedCategoryNames().map((name, index) => (
            <Tag key={index} color="blue">{name}</Tag>
          ))}
        </div>
      </div>
      <Modal
        title="选择品类"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={700}
        destroyOnClose
      >
        <div className="search-container">
          <Input
            placeholder="搜索品类名称或编码"
            prefix={<SearchOutlined />}
            value={searchValue}
            onChange={handleSearch}
            style={{ marginBottom: 16 }}
          />
        </div>
        <Table
          rowKey="id"
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredData}
          pagination={{ pageSize: 5 }}
          size="middle"
        />
      </Modal>
    </div>
  );
};

export default CategorySelector;
