/**
 * KRA - Button Permission Component
 * Configure button permissions for authority/role
 * Note: This component is integrated into MenuPermission as a modal
 * This file is kept for potential standalone use
 */
import React, { useState, useEffect } from 'react';
import { Table, Button, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getAuthorityBtn, setAuthorityBtn } from '@/services/kratos/authorityBtn';

interface Authority {
  authorityId: string;
  authorityName: string;
}

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

interface BtnPermissionProps {
  row: Authority;
  menuId: number;
  buttons: MenuButton[];
  onSuccess?: () => void;
}

const BtnPermission: React.FC<BtnPermissionProps> = ({
  row,
  menuId,
  buttons,
  onSuccess,
}) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchSelectedButtons();
  }, [row.authorityId, menuId]);

  const fetchSelectedButtons = async () => {
    try {
      const res = await getAuthorityBtn({
        menuID: menuId,
        authorityId: row.authorityId,
      });
      if (res.code === 0) {
        setSelectedRowKeys(res.data?.selected || []);
      }
    } catch (error) {
      console.error('Failed to fetch authority buttons:', error);
    }
  };

  const handleConfirm = async () => {
    setLoading(true);
    try {
      const res = await setAuthorityBtn({
        menuID: menuId,
        authorityId: row.authorityId,
        selected: selectedRowKeys as string[],
      });
      if (res.code === 0) {
        message.success('设置成功');
        onSuccess?.();
      }
    } catch (error) {
      message.error('设置失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: ColumnsType<MenuButton> = [
    {
      title: '按钮名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '按钮备注',
      dataIndex: 'desc',
      key: 'desc',
    },
  ];

  return (
    <div>
      <Table
        rowKey="ID"
        columns={columns}
        dataSource={buttons}
        pagination={false}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys),
        }}
      />
      <div style={{ marginTop: 16, textAlign: 'right' }}>
        <Button type="primary" loading={loading} onClick={handleConfirm}>
          确定
        </Button>
      </div>
    </div>
  );
};

export default BtnPermission;
