import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/theme/app_colors.dart';
import '../shell/nav_bar_config.dart';
import '../../core/i18n/app_localizations.dart';
import '../../shared/widgets/status_tag.dart';

class AdminPermissionsPage extends ConsumerStatefulWidget {
  const AdminPermissionsPage({super.key});
  @override
  ConsumerState<AdminPermissionsPage> createState() =>
      _AdminPermissionsPageState();
}

class _AdminPermissionsPageState extends ConsumerState<AdminPermissionsPage> {
  final _employees = <Employee>[
    Employee(
      name: '张三',
      avatarText: '张',
      employeeId: '工号:0048',
      department: '销售部',
      roles: ['普通员工', '审批人'],
      isActive: true,
    ),
    Employee(
      name: '王经理',
      avatarText: '王',
      employeeId: '工号:0012',
      department: '销售部',
      roles: ['审批人', '系统管理员'],
      isActive: true,
    ),
    Employee(
      name: '李会计',
      avatarText: '李',
      employeeId: '工号:0025',
      department: '财务部',
      roles: ['财务人员'],
      isActive: true,
    ),
    Employee(
      name: '赵管理员',
      avatarText: '赵',
      employeeId: '工号:0001',
      department: '信息技术部',
      roles: ['系统管理员'],
      isActive: true,
    ),
    Employee(
      name: '钱六',
      avatarText: '钱',
      employeeId: '工号:0052',
      department: '财务部',
      roles: ['财务人员'],
      isActive: false,
    ),
    Employee(
      name: '孙七',
      avatarText: '孙',
      employeeId: '工号:0078',
      department: '行政部',
      roles: ['普通员工'],
      isActive: true,
    ),
  ];

  String _searchQuery = '';

  List<Employee> get _filteredEmployees {
    if (_searchQuery.isEmpty) return _employees;
    final q = _searchQuery.toLowerCase();
    return _employees.where((e) {
      return e.name.toLowerCase().contains(q) ||
          e.employeeId.toLowerCase().contains(q);
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    final l10n = AppLocalizations.of(context);
    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('adminPermissions'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    return Column(
      children: [
        // 搜索栏
        Container(
          width: double.infinity,
          padding: const EdgeInsets.fromLTRB(16, 10, 16, 10),
          color: AppColors.bgCard,
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: AppColors.bgPage,
              borderRadius: BorderRadius.circular(18),
            ),
            child: Row(
              children: [
                const Icon(
                  Icons.search,
                  size: 16,
                  color: AppColors.textPlaceholder,
                ),
                const SizedBox(width: 6),
                Expanded(
                  child: TextField(
                    onChanged: (v) => setState(() => _searchQuery = v),
                    decoration: const InputDecoration(
                      hintText: '输入姓名或工号进行检索...',
                      hintStyle: TextStyle(
                        fontSize: 14,
                        color: AppColors.textPlaceholder,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.zero,
                      isDense: true,
                    ),
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.textPrimary,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),

        // 员工列表
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: _filteredEmployees.length,
            itemBuilder: (_, i) => _buildEmpCard(_filteredEmployees[i]),
          ),
        ),
      ],
    );
  }

  Widget _buildEmpCard(Employee emp) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 16),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: emp.isActive ? AppColors.bgCard : const Color(0xFFF9F9F9),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 头像
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: AppColors.primary,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Center(
                child: Text(
                  emp.avatarText,
                  style: const TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
            const SizedBox(width: 10),

            // 信息区
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 姓名 + 工号
                  Row(
                    children: [
                      Text(
                        emp.name,
                        style: const TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w600,
                          color: AppColors.textPrimary,
                        ),
                      ),
                      const SizedBox(width: 6),
                      Text(
                        emp.employeeId,
                        style: const TextStyle(
                          fontSize: 12,
                          color: AppColors.textPlaceholder,
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 2),
                  // 部门
                  Text(
                    emp.department,
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.textSecondary,
                    ),
                  ),
                ],
              ),
            ),

            // 角色标签区
            Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                // 角色标签行
                ...emp.roles.map(
                  (role) => Padding(
                    padding: const EdgeInsets.only(bottom: 4),
                    child: _buildRoleTag(role),
                  ),
                ),
                // 状态标签
                if (!emp.isActive)
                  StatusTag(
                    text: '已禁用',
                    textColor: AppColors.danger,
                    backgroundColor: AppColors.dangerBg,
                  ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildRoleTag(String role) {
    Color bgColor;
    Color textColor;
    switch (role) {
      case '审批人':
        bgColor = AppColors.warningBg;
        textColor = AppColors.warning;
        break;
      case '财务人员':
        bgColor = AppColors.successBg;
        textColor = AppColors.success;
        break;
      case '系统管理员':
        bgColor = AppColors.dangerBg;
        textColor = AppColors.danger;
        break;
      default:
        bgColor = AppColors.primaryLight;
        textColor = AppColors.primary;
    }
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(3),
      ),
      child: Text(role, style: TextStyle(fontSize: 10, color: textColor)),
    );
  }
}

class Employee {
  final String name;
  final String avatarText;
  final String employeeId;
  final String department;
  final List<String> roles;
  final bool isActive;

  const Employee({
    required this.name,
    required this.avatarText,
    required this.employeeId,
    required this.department,
    required this.roles,
    this.isActive = true,
  });
}
