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

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

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

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

const EndNodeTable: React.FC<EndNodeTableProps> = ({
                                                     initialData,
                                                     onUpdateData
                                                   }) => {
  const [data, setData] = useState<TableDataItem[]>([]);

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

  const dataTypeOptions = [
    { label: '字符串', value: 'string' },
    { label: '数字', value: 'number' },
    { label: '布尔值', value: 'boolean' },
    { label: '数组', value: 'array' },
    { label: '对象', value: 'object' }
  ];

  const arrayTypeOptions = [
    { label: '字符串数组', value: 'string' },
    { label: '数字数组', value: 'number' },
    { label: '布尔数组', value: 'boolean' }
  ];

  const columns = [
    {
      title: '标识',
      dataIndex: 'id',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.id}
          onChange={(value) => handleSave({ ...record, id: value })}
        />
      )
    },
    {
      title: '数据类型',
      dataIndex: 'dataType',
      render: (_: any, record: TableDataItem) => (
        <Select
          autoWidth={{ minWidth: 200, maxWidth: 500 }}
          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: 200, maxWidth: 500 }}
            options={arrayTypeOptions}
            value={record.arrayType}
            onChange={(value) => handleSave({ ...record, arrayType: value })}
            placeholder="请选择数组类型"
          />
        ) : (
          <span></span>
        )
      )
    },
    {
      title: '描述',
      dataIndex: 'desc',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.desc}
          onChange={(value) => handleSave({ ...record, desc: value })}
        />
      )
    },
    {
      title: '默认值',
      dataIndex: 'defaultValue',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.defaultValue}
          onChange={(value) => handleSave({ ...record, defaultValue: value })}
        />
      )
    },
    {
      title: '操作',
      dataIndex: 'op',
      render: (_: any, record: TableDataItem) => (
        <Button onClick={() => removeRow(record.key)} type="text" status="danger">
          <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 EndNodeTable;