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

interface TableDataItem {
  key: number | string;
  label: string;
  url: string;

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

interface ConfigTableProps {
  configUrls?: TableDataItem[];
  onChange?: (data: TableDataItem[]) => void;
}

const ConfigTable: React.FC<ConfigTableProps> = ({ configUrls = [], onChange }) => {
  const [tableData, setTableData] = useState<TableDataItem[]>([]);

  useEffect(() => {
    setTableData(configUrls);
  }, [configUrls]);

  const columns: TableColumnProps[] = [
    {
      title: '标签',
      dataIndex: 'label',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.label}
          onChange={(value) => handleSave({ ...record, label: value })}
        />
      )
    },
    {
      title: 'url',
      dataIndex: 'url',
      render: (_: any, record: TableDataItem) => (
        <Input
          value={record.url}
          onChange={(value) => handleSave({ ...record, url: value })}
        />
      )
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_: any, record: TableDataItem) => (
        <Button onClick={() => removeRow(record.key)} type="text" status="danger">
          <IconDelete />
        </Button>
      )
    }
  ];

  const newKey = Date.now();
  const addRow = () => {
    const newRow = {
      key: newKey,
      label: '',
      url: ''
    };
    const newData = [...tableData, newRow];
    setTableData(newData);
    if (onChange) {
      onChange(newData);
    }
  };

  const removeRow = (key: number | string) => {
    const newData = tableData.filter((item) => item.key !== key);
    setTableData(newData);
    if (onChange) {
      onChange(newData);
    }
  };

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

  return (
    <>
      {!!tableData.length && (
        <>
          <Table columns={columns} data={tableData} />
          <Button
            style={{ height: 45, marginTop: 5 }}
            long
            type="outline"
            onClick={addRow}
          >
            + 添加
          </Button>
        </>
      )}

      {!tableData.length && (
        <div className={'add-icon'}>
          <IconPlusCircle style={{ fontSize: 24, color: 'rgb(0, 117, 255)', cursor: 'pointer' }} onClick={addRow} />
        </div>
      )}
    </>
  );
};

export default ConfigTable;