import React, { useEffect, useState } from 'react';
import { Card, Tag, Input, Space, Spin } from 'antd';
import api from '../../api';

interface PermissionItem {
  id: number;
  code: string;
  name: string;
  group: string;
  description: string;
}

const PermissionsPage: React.FC = () => {
  const [permTree, setPermTree] = useState<{ group: string; permissions: PermissionItem[] }[]>([]);
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState('');

  const groupNames: Record<string, string> = {
    dashboard: '数据面板',
    student: '学生管理',
    room: '宿舍管理',
    occupancy: '入住管理',
    expense: '费用管理',
    bill: '账单管理',
    deposit: '押金管理',
    classroom: '教室管理',
    tenant: '租赁方',
    rental: '租赁订单',
    log: '操作日志',
    user: '用户管理',
    role: '角色管理',
  };

  useEffect(() => {
    setLoading(true);
    api
      .get('/rbac/permissions/tree')
      .then((res: any) => setPermTree(res))
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  const filteredTree = search
    ? permTree
        .map((g) => ({
          ...g,
          permissions: g.permissions.filter(
            (p) => p.name.includes(search) || p.code.includes(search),
          ),
        }))
        .filter((g) => g.permissions.length > 0)
    : permTree;

  if (loading) return <Spin style={{ display: 'block', margin: '40px auto' }} />;

  return (
    <div>
      <div
        style={{
          marginBottom: 16,
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: 8,
        }}
      >
        <h2 style={{ margin: 0 }}>权限一览</h2>
        <Input.Search
          placeholder="搜索权限名称或编码"
          allowClear
          style={{ width: 280 }}
          onSearch={setSearch}
          onChange={(e) => !e.target.value && setSearch('')}
        />
      </div>
      <Space direction="vertical" style={{ width: '100%' }} size={16}>
        {filteredTree.map((group) => (
          <Card
            key={group.group}
            title={
              <span style={{ fontWeight: 600 }}>
                {groupNames[group.group] || group.group} ({group.permissions.length})
              </span>
            }
            size="small"
          >
            <Space wrap>
              {group.permissions.map((p) => (
                <Tag key={p.id} color="blue" style={{ marginBottom: 8 }}>
                  {p.name}{' '}
                  <Tag color="geekblue" style={{ marginLeft: 4 }}>
                    {p.code}
                  </Tag>
                </Tag>
              ))}
            </Space>
          </Card>
        ))}
      </Space>
    </div>
  );
};

export default PermissionsPage;
