import 'package:flutter/material.dart';
import 'package:qpay/models/responsive_policy.dart';
import 'package:qpay/screens/users/controllers/user_controller.dart';
import 'package:qpay/screens/users/models/managed_user_model.dart';
import 'package:qpay/widgets/app_snack_bar.dart';
import 'package:shared_preferences/shared_preferences.dart';

class UserListScreen extends StatefulWidget {
  const UserListScreen({super.key});

  @override
  State<UserListScreen> createState() => _UserListScreenState();
}

class _UserListScreenState extends State<UserListScreen> {
  late UserController controller;
  SharedPreferences? prefs;
  final _searchController = TextEditingController();
  final _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    controller = UserController(context);
    _loadData();

    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    final p = prefs;
    if (p == null) return;
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      controller.loadNextPage(workspaceId: p.getString('workspaceId') ?? '');
    }
  }

  Future<void> _loadData() async {
    prefs = await SharedPreferences.getInstance();
    final workspaceId = prefs!.getString('workspaceId') ?? '';
    await controller.listWorkspaceUsers(workspaceId: workspaceId);
  }

  void _onSearchChanged(String value) {
    final workspaceId = prefs?.getString('workspaceId') ?? '';
    controller.searchUsers(
      workspaceId: workspaceId,
      name: value.isNotEmpty ? value : null,
    );
  }

  // ── Bulk dissociate ──────────────────────────────────────────

  Future<void> _onDissociateSelected() async {
    final workspaceId = prefs?.getString('workspaceId') ?? '';
    final count = controller.model.selectedUserIds.length;

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Dissociate users'),
        content: Text(
          'Are you sure you want to dissociate $count user(s) from this workspace?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(false),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('Dissociate'),
          ),
        ],
      ),
    );

    if (confirmed == true && mounted) {
      await controller.dissociateSelectedUsers(workspaceId: workspaceId);
    }
  }

  // ── Single dissociate ────────────────────────────────────────

  Future<void> _onDissociateUser(ManagedUserModel user) async {
    final workspaceId = prefs?.getString('workspaceId') ?? '';

    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Dissociate user'),
        content: Text(
          'Are you sure you want to dissociate "${user.displayName}" from this workspace?',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(false),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(true),
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('Dissociate'),
          ),
        ],
      ),
    );

    if (confirmed == true && mounted) {
      final result = await controller.dissociateUser(
        workspaceId: workspaceId,
        userId: user.id,
      );
      if (mounted) {
        if (result.error == null) {
          AppSnackBar.showSuccess(
            context,
            '${user.displayName} dissociated from workspace',
          );
        } else {
          AppSnackBar.showError(context, result.error ?? 'Dissociation failed');
        }
      }
    }
  }

  // ── Associate bottom sheet ───────────────────────────────────

  void _showAssociateSheet() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (sheetContext) =>
          _AssociateUserSheet(onAssociated: () => _loadData()),
    );
  }

  // ── Filter bottom sheet ──────────────────────────────────────

  void _showFilterBottomSheet() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (sheetContext) => _UserFilterBottomSheet(
        initialEmail: controller.model.filterEmail,
        initialPhone: controller.model.filterPhone,
        onApply: (email, phone) {
          final workspaceId = prefs?.getString('workspaceId') ?? '';
          controller.applyFilters(
            workspaceId: workspaceId,
            email: email,
            phone: phone,
          );
        },
        onClear: () {
          final workspaceId = prefs?.getString('workspaceId') ?? '';
          controller.clearFilters(workspaceId: workspaceId);
        },
      ),
    );
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    controller.dispose();
    super.dispose();
  }

  // ══════════════════════════════════════════════════════════════
  // BUILD
  // ══════════════════════════════════════════════════════════════

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Users',
          style: TextStyle(fontSize: 20, color: Colors.black),
        ),
        centerTitle: true,
      ),
      body: ListenableBuilder(
        listenable: controller,
        builder: (context, _) {
          return Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  controller: _scrollController,
                  child: Center(
                    child: LayoutBuilder(
                      builder: (context, constraints) {
                        final width = constraints.maxWidth > ResponsivePolicy.md
                            ? ResponsivePolicy.md.toDouble()
                            : constraints.maxWidth;
                        return SizedBox(
                          width: width,
                          child: Padding(
                            padding: const EdgeInsets.all(16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildSearchRow(),
                                const SizedBox(height: 16),
                                _buildContent(),
                              ],
                            ),
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
              if (controller.model.selectMode) _buildSelectionBottomBar(),
            ],
          );
        },
      ),
    );
  }

  Widget _buildSearchRow() {
    final hasActiveFilters =
        controller.model.filterEmail != null ||
        controller.model.filterPhone != null;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Expanded(
              child: TextFormField(
                controller: _searchController,
                decoration: InputDecoration(
                  hintText: 'Search users by username...',
                  prefixIcon: const Icon(Icons.search),
                  suffixIcon: _searchController.text.isNotEmpty
                      ? IconButton(
                          icon: const Icon(Icons.clear),
                          onPressed: () {
                            _searchController.clear();
                            _onSearchChanged('');
                          },
                        )
                      : null,
                  filled: true,
                  fillColor: Colors.grey.shade100,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: BorderSide.none,
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                    borderSide: BorderSide(
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                ),
                onChanged: _onSearchChanged,
              ),
            ),
            const SizedBox(width: 8),
            _buildIconButton(
              icon: Icons.filter_list,
              tooltip: 'Filter users',
              isActive: hasActiveFilters,
              onPressed: _showFilterBottomSheet,
            ),
            const SizedBox(width: 8),
            _buildIconButton(
              icon: controller.model.selectMode
                  ? Icons.checklist
                  : Icons.checklist_outlined,
              tooltip: 'Select users',
              isActive: controller.model.selectMode,
              onPressed: () => controller.toggleSelectMode(),
            ),
            const SizedBox(width: 8),
            _buildIconButton(
              icon: Icons.refresh,
              tooltip: 'Refresh users',
              isActive: false,
              onPressed: _loadData,
            ),
            const SizedBox(width: 8),
            _buildIconButton(
              icon: Icons.person_add_alt,
              tooltip: 'Add user to workspace',
              isActive: false,
              onPressed: _showAssociateSheet,
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildIconButton({
    required IconData icon,
    required String tooltip,
    required bool isActive,
    required VoidCallback onPressed,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: isActive
            ? Theme.of(context).colorScheme.primary
            : Colors.grey.shade100,
        borderRadius: BorderRadius.circular(12),
      ),
      child: IconButton(
        icon: Icon(icon, color: isActive ? Colors.white : Colors.grey.shade700),
        tooltip: tooltip,
        onPressed: onPressed,
      ),
    );
  }

  Widget _buildContent() {
    if (controller.model.isLoading) {
      return const Center(
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 60),
          child: CircularProgressIndicator(),
        ),
      );
    }

    if (controller.model.errorMessage != null &&
        controller.model.users.isEmpty) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(vertical: 60),
          child: Column(
            children: [
              Icon(Icons.error_outline, size: 48, color: Colors.grey.shade400),
              const SizedBox(height: 16),
              Text(
                controller.model.errorMessage!,
                style: TextStyle(color: Colors.grey.shade600),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 16),
              ElevatedButton.icon(
                onPressed: _loadData,
                icon: const Icon(Icons.refresh),
                label: const Text('Retry'),
              ),
            ],
          ),
        ),
      );
    }

    if (controller.model.users.isEmpty) {
      return Center(child: _buildEmptyState());
    }

    return Column(
      children: [
        if (controller.model.filterEmail != null ||
            controller.model.filterPhone != null)
          _buildActiveFilterChips(),

        if (controller.model.selectMode)
          Padding(
            padding: const EdgeInsets.only(bottom: 8),
            child: Row(
              children: [
                Text(
                  '${controller.model.selectedUserIds.length} selected',
                  style: TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
        ListView.separated(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: controller.model.users.length,
          separatorBuilder: (_, __) => const SizedBox(height: 8),
          itemBuilder: (context, index) {
            return _buildUserCard(controller.model.users[index]);
          },
        ),
        if (controller.model.isLoadingMore)
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 16),
            child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
          ),
        if (controller.model.totalElements > 0)
          Padding(
            padding: const EdgeInsets.only(top: 12),
            child: Text(
              '${controller.model.totalElements} user(s) total',
              style: TextStyle(fontSize: 12, color: Colors.grey.shade500),
            ),
          ),
      ],
    );
  }

  Widget _buildActiveFilterChips() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Wrap(
        spacing: 8,
        runSpacing: 4,
        children: [
          if (controller.model.filterEmail != null)
            Chip(
              label: Text(
                'Email: ${controller.model.filterEmail}',
                style: const TextStyle(fontSize: 12),
              ),
              deleteIcon: const Icon(Icons.close, size: 16),
              onDeleted: () {
                final workspaceId = prefs?.getString('workspaceId') ?? '';
                controller.applyFilters(
                  workspaceId: workspaceId,
                  email: null,
                  phone: controller.model.filterPhone,
                );
              },
              backgroundColor: Theme.of(
                context,
              ).colorScheme.primary.withAlpha(20),
              side: BorderSide.none,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
          if (controller.model.filterPhone != null)
            Chip(
              label: Text(
                'Phone: ${controller.model.filterPhone}',
                style: const TextStyle(fontSize: 12),
              ),
              deleteIcon: const Icon(Icons.close, size: 16),
              onDeleted: () {
                final workspaceId = prefs?.getString('workspaceId') ?? '';
                controller.applyFilters(
                  workspaceId: workspaceId,
                  email: controller.model.filterEmail,
                  phone: null,
                );
              },
              backgroundColor: Theme.of(
                context,
              ).colorScheme.primary.withAlpha(20),
              side: BorderSide.none,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Column(
      children: [
        const SizedBox(height: 40),
        Icon(Icons.people_outline, size: 64, color: Colors.grey.shade400),
        const SizedBox(height: 16),
        const Text(
          'No users yet.',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 8),
        Text(
          'Tap "Associate" to add users to this workspace.',
          style: TextStyle(fontSize: 14, color: Colors.grey.shade600),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildUserCard(ManagedUserModel user) {
    final isSelected = controller.model.selectedUserIds.contains(user.id);
    final inSelectMode = controller.model.selectMode;

    return Card(
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(
          color: inSelectMode && isSelected
              ? Theme.of(context).colorScheme.primary
              : Colors.black12.withAlpha(30),
          width: inSelectMode && isSelected ? 2 : 1,
        ),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: inSelectMode
            ? () => controller.toggleUserSelection(user.id)
            : null,
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  if (inSelectMode)
                    Padding(
                      padding: const EdgeInsets.only(right: 12),
                      child: Icon(
                        isSelected
                            ? Icons.check_box
                            : Icons.check_box_outline_blank,
                        color: isSelected
                            ? Theme.of(context).colorScheme.primary
                            : Colors.grey.shade400,
                      ),
                    ),
                  CircleAvatar(
                    backgroundColor: Theme.of(
                      context,
                    ).colorScheme.primary.withAlpha(30),
                    child: Text(
                      user.initials,
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.primary,
                        fontWeight: FontWeight.w600,
                        fontSize: 16,
                      ),
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          user.displayName,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        if (user.username != user.displayName)
                          Padding(
                            padding: const EdgeInsets.only(top: 2),
                            child: Text(
                              '@${user.username}',
                              style: TextStyle(
                                fontSize: 13,
                                color: Colors.grey.shade600,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              Wrap(
                spacing: 8,
                runSpacing: 6,
                children: [
                  _buildInfoChip(Icons.email_outlined, user.email),
                  _buildInfoChip(Icons.phone_outlined, user.phone),
                  if (user.roleNames.isNotEmpty)
                    _buildInfoChip(Icons.shield_outlined, user.roleNames),
                ],
              ),
              if (!inSelectMode) ...[
                const SizedBox(height: 12),
                Align(
                  alignment: Alignment.centerRight,
                  child: TextButton.icon(
                    onPressed: () => _onDissociateUser(user),
                    icon: const Icon(Icons.link_off, size: 18),
                    label: const Text('Dissociate'),
                    style: TextButton.styleFrom(
                      foregroundColor: Colors.red.shade600,
                    ),
                  ),
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInfoChip(IconData icon, String text) {
    if (text.isEmpty) return const SizedBox.shrink();
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: Colors.grey.shade600),
          const SizedBox(width: 4),
          Text(
            text,
            style: TextStyle(fontSize: 12, color: Colors.grey.shade700),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectionBottomBar() {
    final selectedCount = controller.model.selectedUserIds.length;
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.08),
            blurRadius: 8,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: SafeArea(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          child: Row(
            children: [
              Text(
                '$selectedCount selected',
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
              const Spacer(),
              TextButton.icon(
                onPressed: selectedCount > 0 ? _onDissociateSelected : null,
                icon: const Icon(Icons.link_off, size: 20),
                label: const Text('Dissociate'),
                style: TextButton.styleFrom(foregroundColor: Colors.red),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// ASSOCIATE USER BOTTOM SHEET
// ═══════════════════════════════════════════════════════════════════════════

class _AssociateUserSheet extends StatefulWidget {
  final VoidCallback onAssociated;

  const _AssociateUserSheet({required this.onAssociated});

  @override
  State<_AssociateUserSheet> createState() => _AssociateUserSheetState();
}

class _AssociateUserSheetState extends State<_AssociateUserSheet> {
  final _searchController = TextEditingController();
  final _scrollController = ScrollController();
  final UserController _userController = UserController.forSheet();

  List<ManagedUserModel> _results = [];
  bool _isSearching = false;

  Future<void> _search(String query) async {
    if (query.trim().isEmpty) {
      setState(() {
        _results = [];
        _isSearching = false;
      });
      return;
    }

    setState(() => _isSearching = true);

    final response = await _userController.listUsers(username: query.trim());

    if (mounted) {
      setState(() {
        _isSearching = false;
        if (response.isSuccess) {
          _results = _userController.model.users;
        }
      });
    }
  }

  Future<void> _associate(ManagedUserModel user) async {
    final prefs = await SharedPreferences.getInstance();
    final workspaceId = prefs.getString('workspaceId') ?? '';

    if (!mounted) return;

    // Confirm
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Associate user'),
        content: Text('Associate "${user.displayName}" to this workspace?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(ctx).pop(false),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(ctx).pop(true),
            child: const Text('Associate'),
          ),
        ],
      ),
    );

    if (confirmed != true) return;

    final result = await _userController.associateUser(
      workspaceId: workspaceId,
      userId: user.id,
    );

    if (mounted) {
      if (result.error == null) {
        AppSnackBar.showSuccess(
          context,
          '${user.displayName} associated to workspace',
        );
        widget.onAssociated();
        Navigator.of(context).pop();
      } else {
        AppSnackBar.showError(context, result.error ?? 'Association failed');
      }
    }
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    _userController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    final bottomInset = MediaQuery.of(context).viewInsets.bottom;

    return Container(
      height: MediaQuery.of(context).size.height * 0.75,
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1A1A2E) : Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
      ),
      padding: EdgeInsets.fromLTRB(20, 12, 20, bottomInset + 16),
      child: Column(
        children: [
          // Drag handle
          Center(
            child: Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.only(bottom: 16),
              decoration: BoxDecoration(
                color: Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
          ),
          // Header
          Text(
            'Associate User',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
              color: isDark ? Colors.white : Colors.black87,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            'Search for a platform user to add to this workspace.',
            style: TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.w500,
              color: Colors.grey.shade500,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: 16),
          // Search field
          TextFormField(
            controller: _searchController,
            autofocus: true,
            decoration: InputDecoration(
              hintText: 'Search by username...',
              prefixIcon: const Icon(Icons.search),
              suffixIcon: _searchController.text.isNotEmpty
                  ? IconButton(
                      icon: const Icon(Icons.clear),
                      onPressed: () {
                        _searchController.clear();
                        _search('');
                      },
                    )
                  : null,
              filled: true,
              fillColor: Colors.grey.shade100,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide.none,
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide(
                  color: Theme.of(context).colorScheme.primary,
                ),
              ),
            ),
            onChanged: (value) {
              if (value.length >= 2 || value.isEmpty) {
                _search(value);
              }
            },
          ),
          const SizedBox(height: 12),
          // Results
          Expanded(
            child: _isSearching
                ? const Center(child: CircularProgressIndicator())
                : _results.isEmpty
                ? Center(
                    child: Text(
                      _searchController.text.isNotEmpty
                          ? 'No users found.'
                          : 'Type at least 2 characters to search.',
                      style: TextStyle(
                        color: Colors.grey.shade500,
                        fontSize: 14,
                      ),
                    ),
                  )
                : ListView.separated(
                    controller: _scrollController,
                    itemCount: _results.length,
                    separatorBuilder: (_, __) => const SizedBox(height: 8),
                    itemBuilder: (context, index) {
                      final user = _results[index];
                      return _buildSearchResultCard(user);
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchResultCard(ManagedUserModel user) {
    return Card(
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: BorderSide(color: Colors.black12.withAlpha(30)),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: () => _associate(user),
        child: Padding(
          padding: const EdgeInsets.all(14),
          child: Row(
            children: [
              CircleAvatar(
                backgroundColor: Theme.of(
                  context,
                ).colorScheme.primary.withAlpha(30),
                child: Text(
                  user.initials,
                  style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    fontWeight: FontWeight.w600,
                    fontSize: 14,
                  ),
                ),
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      user.displayName,
                      style: const TextStyle(
                        fontSize: 15,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    if (user.username != user.displayName)
                      Text(
                        '@${user.username}',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade500,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    const SizedBox(height: 4),
                    Text(
                      user.email.isNotEmpty ? user.email : user.phone,
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade500,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
              ),
              Icon(Icons.add_circle_outline, color: Colors.grey.shade400),
            ],
          ),
        ),
      ),
    );
  }
}

// ═══════════════════════════════════════════════════════════════════════════
// FILTER BOTTOM SHEET
// ═══════════════════════════════════════════════════════════════════════════

class _UserFilterBottomSheet extends StatefulWidget {
  final String? initialEmail;
  final String? initialPhone;
  final void Function(String? email, String? phone) onApply;
  final VoidCallback onClear;

  const _UserFilterBottomSheet({
    required this.initialEmail,
    required this.initialPhone,
    required this.onApply,
    required this.onClear,
  });

  @override
  State<_UserFilterBottomSheet> createState() => _UserFilterBottomSheetState();
}

class _UserFilterBottomSheetState extends State<_UserFilterBottomSheet> {
  late TextEditingController _emailController;
  late TextEditingController _phoneController;

  @override
  void initState() {
    super.initState();
    _emailController = TextEditingController(text: widget.initialEmail ?? '');
    _phoneController = TextEditingController(text: widget.initialPhone ?? '');
  }

  @override
  void dispose() {
    _emailController.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  void _apply() {
    final email = _emailController.text.trim().isNotEmpty
        ? _emailController.text.trim()
        : null;
    final phone = _phoneController.text.trim().isNotEmpty
        ? _phoneController.text.trim()
        : null;
    widget.onApply(email, phone);
    Navigator.of(context).pop();
  }

  void _clear() {
    widget.onClear();
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Container(
      decoration: BoxDecoration(
        color: isDark ? const Color(0xFF1A1A2E) : Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
      ),
      padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Center(
            child: Container(
              width: 40,
              height: 4,
              margin: const EdgeInsets.only(bottom: 16),
              decoration: BoxDecoration(
                color: Colors.grey.shade300,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Filter Users',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w700,
                  color: isDark ? Colors.white : Colors.black87,
                ),
              ),
              TextButton(onPressed: _clear, child: const Text('Clear all')),
            ],
          ),
          const SizedBox(height: 6),
          Text(
            'Filter users by the fields below.',
            style: TextStyle(
              fontSize: 13,
              fontWeight: FontWeight.w500,
              color: Colors.grey.shade500,
            ),
          ),
          const SizedBox(height: 20),
          _buildFilterField(
            label: 'Email',
            hint: 'e.g. user@example.com',
            controller: _emailController,
            icon: Icons.email_outlined,
          ),
          const SizedBox(height: 16),
          _buildFilterField(
            label: 'Phone',
            hint: 'e.g. 263773591219',
            controller: _phoneController,
            icon: Icons.phone_outlined,
          ),
          const SizedBox(height: 24),
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: _apply,
              child: const Text('Apply Filters'),
            ),
          ),
          const SizedBox(height: 8),
        ],
      ),
    );
  }

  Widget _buildFilterField({
    required String label,
    required String hint,
    required TextEditingController controller,
    required IconData icon,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w600,
            color: Colors.black87,
          ),
        ),
        const SizedBox(height: 8),
        TextFormField(
          controller: controller,
          decoration: InputDecoration(
            hintText: hint,
            prefixIcon: Icon(icon, size: 20),
            filled: true,
            fillColor: Colors.grey.shade100,
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(
                color: Theme.of(context).colorScheme.primary,
              ),
            ),
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 14,
            ),
          ),
        ),
      ],
    );
  }
}
