/**
 * KRA - Authority Management Page
 * Manage system roles/authorities with CRUD operations
 */
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Button, Table, message, Popconfirm, Drawer, Tabs, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { PlusOutlined, SettingOutlined, CopyOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  updateAuthority,
  copyAuthority,
} from '@/services/kratos/authority';
import WarningBar from '@/components/WarningBar/WarningBar';
import AuthorityForm from './components/AuthorityForm';
import MenuPermission from './components/MenuPermission';
import ApiPermission from './components/ApiPermission';
import DataPermission from './components/DataPermission';

interface Authority {
  authorityId: string;
  authorityName: string;
  parentId: string;
  defaultRouter?: string;
  children?: Authority[];
  dataAuthorityId?: Authority[];
}

const AuthorityPage: React.FC = () => {
  const [tableData, setTableData] = useState<Authority[]>([]);
  const [loading, setLoading] = useState(false);
  const [formVisible, setFormVisible] = useState(false);
  const [dialogType, setDialogType] = useState<'add' | 'edit' | 'copy'>('add');
  const [currentRow, setCurrentRow] = useState<Authority | null>(null);
  const [parentId, setParentId] = useState<string>('0');
  
  // 权限配置抽屉
  const [permissionDrawerVisible, setPermissionDrawerVisible] = useState(false);
  const [activeRow, setActiveRow] = useState<Authority | null>(null);
  const [activeTab, setActiveTab] = useState('menu');

  // 获取角色列表
  const fetchTableData = async () => {
    setLoading(true);
    try {
      const res = await getAuthorityList();
      if (res.code === 0) {
        // GVA接口直接返回树形数组，不是分页格式
        setTableData(res.data || []);
      }
    } catch (error) {
      console.error('Failed to fetch authority list:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTableData();
  }, []);

  // 新增角色
  const handleAdd = (pid: string = '0') => {
    setDialogType('add');
    setParentId(pid);
    setCurrentRow(null);
    setFormVisible(true);
  };

  // 编辑角色
  const handleEdit = (record: Authority) => {
    setDialogType('edit');
    setCurrentRow(record);
    setFormVisible(true);
  };

  // 拷贝角色
  const handleCopy = (record: Authority) => {
    setDialogType('copy');
    setCurrentRow(record);
    setFormVisible(true);
  };

  // 删除角色
  const handleDelete = async (record: Authority) => {
    try {
      const res = await deleteAuthority({ authorityId: record.authorityId });
      if (res.code === 0) {
        message.success('删除成功');
        fetchTableData();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 打开权限配置抽屉
  const handleOpenPermission = (record: Authority) => {
    setActiveRow(record);
    setActiveTab('menu');
    setPermissionDrawerVisible(true);
  };

  // 表单提交成功
  const handleFormSuccess = () => {
    setFormVisible(false);
    setCurrentRow(null);
    fetchTableData();
  };

  // 更新 activeRow
  const handleChangeRow = (key: string, value: any) => {
    if (activeRow) {
      setActiveRow({ ...activeRow, [key]: value });
    }
  };

  // 表格列定义
  const columns: ColumnsType<Authority> = [
    {
      title: '角色ID',
      dataIndex: 'authorityId',
      width: 180,
    },
    {
      title: '角色名称',
      dataIndex: 'authorityName',
      width: 180,
    },
    {
      title: '操作',
      width: 460,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<SettingOutlined />}
            onClick={() => handleOpenPermission(record)}
          >
            设置权限
          </Button>
          <Button
            type="link"
            icon={<PlusOutlined />}
            onClick={() => handleAdd(record.authorityId)}
          >
            新增子角色
          </Button>
          <Button
            type="link"
            icon={<CopyOutlined />}
            onClick={() => handleCopy(record)}
          >
            拷贝
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="此操作将永久删除该角色, 是否继续?"
            onConfirm={() => handleDelete(record)}
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <WarningBar title="注：右上角头像下拉可切换角色" type="info" />
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => handleAdd('0')}>
          新增角色
        </Button>
      </div>
      <Table<Authority>
        columns={columns}
        dataSource={tableData}
        rowKey="authorityId"
        loading={loading}
        pagination={false}
        expandable={{
          childrenColumnName: 'children',
        }}
      />

      {/* 角色表单抽屉 */}
      <AuthorityForm
        visible={formVisible}
        onClose={() => {
          setFormVisible(false);
          setCurrentRow(null);
        }}
        onSuccess={handleFormSuccess}
        dialogType={dialogType}
        initialValues={currentRow}
        parentId={parentId}
        authorityOptions={tableData}
      />

      {/* 权限配置抽屉 */}
      <Drawer
        title="角色配置"
        width={600}
        open={permissionDrawerVisible}
        onClose={() => setPermissionDrawerVisible(false)}
        destroyOnClose
      >
        <Tabs
          activeKey={activeTab}
          onChange={setActiveTab}
          type="card"
          items={[
            {
              key: 'menu',
              label: '角色菜单',
              children: activeRow && (
                <MenuPermission
                  row={activeRow}
                  onChangeRow={handleChangeRow}
                />
              ),
            },
            {
              key: 'api',
              label: '角色API',
              children: activeRow && (
                <ApiPermission row={activeRow} />
              ),
            },
            {
              key: 'data',
              label: '资源权限',
              children: activeRow && (
                <DataPermission
                  row={activeRow}
                  authority={tableData}
                  onChangeRow={handleChangeRow}
                />
              ),
            },
          ]}
        />
      </Drawer>
    </PageContainer>
  );
};

export default AuthorityPage;
