/**
 * KRA - Menu Buttons Configuration Component
 * Configure controllable buttons for menu
 */
import React from 'react';
import { Table, Button, Input, Space, Tooltip } from 'antd';
import { PlusOutlined, DeleteOutlined, QuestionCircleOutlined } from '@ant-design/icons';

export interface MenuButton {
  ID?: number;
  name: string;
  desc: string;
}

interface MenuButtonsProps {
  value?: MenuButton[];
  onChange?: (value: MenuButton[]) => void;
}

const MenuButtons: React.FC<MenuButtonsProps> = ({ value = [], onChange }) => {
  // 添加按钮
  const handleAdd = () => {
    const newBtns = [...value, { name: '', desc: '' }];
    onChange?.(newBtns);
  };

  // 删除按钮
  const handleDelete = (index: number) => {
    const newBtns = [...value];
    newBtns.splice(index, 1);
    onChange?.(newBtns);
  };

  // 更新按钮
  const handleUpdate = (index: number, field: keyof MenuButton, fieldValue: string) => {
    const newBtns = [...value];
    newBtns[index] = { ...newBtns[index], [field]: fieldValue };
    onChange?.(newBtns);
  };

  const columns = [
    {
      title: '按钮名称',
      dataIndex: 'name',
      width: 150,
      render: (_: any, record: MenuButton, index: number) => (
        <Input
          value={record.name}
          onChange={(e) => handleUpdate(index, 'name', e.target.value)}
          placeholder="请输入按钮名称"
          size="small"
        />
      ),
    },
    {
      title: '备注',
      dataIndex: 'desc',
      render: (_: any, record: MenuButton, index: number) => (
        <Input
          value={record.desc}
          onChange={(e) => handleUpdate(index, 'desc', e.target.value)}
          placeholder="请输入按钮备注"
          size="small"
        />
      ),
    },
    {
      title: '操作',
      width: 80,
      render: (_: any, __: MenuButton, index: number) => (
        <Button
          type="text"
          danger
          size="small"
          icon={<DeleteOutlined />}
          onClick={() => handleDelete(index)}
        />
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <span style={{ fontWeight: 600 }}>可控按钮配置</span>
          <Button type="primary" size="small" icon={<PlusOutlined />} onClick={handleAdd}>
            新增可控按钮
          </Button>
          <Tooltip title="按钮权限用于控制页面内按钮的显示与隐藏，需要在角色管理中配置按钮权限">
            <QuestionCircleOutlined style={{ color: '#1890ff', cursor: 'pointer' }} />
          </Tooltip>
        </Space>
      </div>
      <Table
        dataSource={value}
        columns={columns}
        rowKey={(_, index) => `btn-${index}`}
        pagination={false}
        size="small"
        bordered
        locale={{ emptyText: '暂无按钮配置' }}
      />
    </div>
  );
};

export default MenuButtons;
