import React, { useState, useEffect } from 'react';
import { Input, Select, Table, Button } from '@arco-design/web-react';
import { IconDelete } from '@arco-design/web-react/icon';
import { useSelector } from 'react-redux';

interface TableDataItem {
  key: number | string;
  id: string;
  dataType: string;
  arrayType: string;
  desc: string;
  defaultValue: string;

  [key: string]: any; // 允许其他自定义字段
}

interface ParamsTableProps {
  initialData: TableDataItem[];
  onUpdateData: (data: TableDataItem[]) => void;
}

const ParamsTable: React.FC<ParamsTableProps> = ({
                                                   initialData,
                                                   onUpdateData
                                                 }) => {
  const [data, setData] = useState<TableDataItem[]>([]);
  const { gloBalVarList } = useSelector((state: any) => state.ideContainer);

  useEffect(() => {
    // 为现有数据添加key属性（如果不存在）
    const dataWithKeys = initialData?.map((item, index) => ({
      ...item,
      key: item.key ?? index
    })) || [];
    setData(dataWithKeys);
  }, [initialData]);

  const dataTypeOptions = [
    { label: 'STRING', value: 'STRING' },
    { label: 'INTEGER', value: 'INTEGER' },
    { label: 'BOOLEAN', value: 'BOOLEAN' },
    { label: 'ARRAY', value: 'ARRAY' },
    { label: 'OBJECT', value: 'OBJECT' },
    { label: 'JSON', value: 'JSON' },
    { label: 'DOUBLE', value: 'DOUBLE' }
  ];

  const arrayTypeOptions = [
    { label: 'STRING', value: 'STRING' },
    { label: 'INTEGER', value: 'INTEGER' },
    { label: 'DOUBLE', value: 'DOUBLE' },
    { label: 'BOOLEAN', value: 'BOOLEAN' },
    { label: 'JSON', value: 'JSON' },
    { label: 'OBJECT', value: 'OBJECT' }
  ];

  // 根据数据类型获取对应的选项列表
  const getOptionsByDataType = (dataType: string) => {
    // 这里可以根据数据类型从gloBalVarList中筛选出对应的选项
    if (gloBalVarList[dataType]) {
      return gloBalVarList[dataType].map((item: any) => ({
        label: item.name,
        value: item.id
      }));
    }
    return [];
  };

  const columns = [
    {
      title: '标识',
      dataIndex: 'id',
      render: (_: any, record: TableDataItem) => (
        record.id === 'maxTime' ? (
          <span>{record.id}</span>
        ) : (
          <Input
            value={record.id}
            autoWidth={{ minWidth: 50, maxWidth: 100 }}
            onChange={(value) => handleSave({ ...record, id: value })}
          />
        )
      )
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
      render: (_: any, record: TableDataItem) => (
        record.id === 'maxTime' ? (
          <span>{record.dataType === 'INTEGER' ? '整数' : record.dataType}</span>
        ) : (
          <Select
            autoWidth={{ minWidth: 150, maxWidth: 200 }}
            options={dataTypeOptions}
            value={record.dataType}
            onChange={(value) => handleSave({ ...record, dataType: value })}
            placeholder="请选择数据类型"
          />
        )
      )
    },
    {
      title: '数组类型',
      dataIndex: 'arrayType',
      render: (_: any, record: TableDataItem) => (
        record.dataType === 'ARRAY' ? (
          <Select
            autoWidth={{ minWidth: 150, maxWidth: 200 }}
            options={arrayTypeOptions}
            value={record.arrayType}
            onChange={(value) => handleSave({ ...record, arrayType: value })}
            placeholder="请选择数组类型"
          />
        ) : (
          <div style={{ minWidth: 70, maxWidth: 100 }}>-</div>
        )
      )
    },
    {
      title: '描述',
      dataIndex: 'desc',
      render: (_: any, record: TableDataItem) => (
        record.id === 'maxTime' ? (
          <span>{record.desc}</span>
        ) : (
          <Input
            value={record.desc}
            onChange={(value) => handleSave({ ...record, desc: value })}
          />
        )
      )
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      render: (_: any, record: TableDataItem) => {
        // 获取当前数据类型对应的选项
        const options = getOptionsByDataType(record.dataType);

        // 如果有选项则显示下拉选择框，否则显示输入框
        if (options.length > 0) {
          return (
            <>
              <Select
                value={record.refValue}
                onChange={(value) => {
                  const refValue = options.find((option) => option.value === value)?.label || null;
                  handleSave({ ...record, refId: value, refValue });
                }}
                placeholder="请选择默认值"
                // showSearch
                allowClear
                options={options}
                style={{ width: '100%', minWidth: 100 }}
                autoWidth={{ minWidth: 150, maxWidth: 200 }}
              />
              <Input
                style={{ width: '100%', minWidth: 150, maxWidth: 200, marginTop: 10 }}
                value={record.defaultValue}
                onChange={(value) => handleSave({ ...record, defaultValue: value })}
                placeholder="请输入默认值"
              />
            </>
          );
        }
        else {
          // 特殊处理maxTime的情况
          if (record.id === 'maxTime') {
            return (
              <Input
                style={{ width: '100%', minWidth: 150, maxWidth: 200, marginTop: 10 }}
                type="number"
                min="1"
                step="1"
                value={record.defaultValue}
                onChange={(value) => handleSave({ ...record, defaultValue: value })}
              />
            );
          }

          return (
            <Input
              style={{ width: '100%', minWidth: 150, maxWidth: 200, marginTop: 10 }}
              value={record.defaultValue}
              onChange={(value) => handleSave({ ...record, defaultValue: value })}
              placeholder="请输入默认值"
            />
          );
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'op',
      render: (_: any, record: TableDataItem) => (
        record.id !== 'maxTime' &&
        <Button onClick={() => removeRow(record.key)} type="text" status="danger" style={{ maxWidth: 40 }}>
          <IconDelete />
        </Button>
      )
    }
  ];

  const handleSave = (row: TableDataItem) => {
    const newData = [...data];
    const index = newData.findIndex((item) => row.key === item.key);
    if (index >= 0) {
      newData.splice(index, 1, { ...newData[index], ...row });
    }
    else {
      newData.push(row);
    }
    setData(newData);
    onUpdateData(newData);
  };

  const removeRow = (key: number | string) => {
    const newData = data.filter((item) => item.key !== key);
    setData(newData);
    onUpdateData(newData);
  };

  const addRow = () => {
    const newKey = Date.now();
    const newRow = {
      key: newKey,
      id: '',
      dataType: '',
      arrayType: '',
      desc: '',
      defaultValue: ''
    };
    const newData = [...data, newRow];
    setData(newData);
    onUpdateData(newData);
  };

  return (
    <>
      <Table columns={columns} data={data} pagination={false} />
      <Button
        style={{ height: 45 }}
        long
        type="outline"
        onClick={addRow}
      >
        + 添加
      </Button>
    </>
  );
};

export default ParamsTable;