import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:developer' as developer;
import '../blocs/organization/organization_state.dart';
import '../blocs/permission/permission_state.dart';
import '../models/organization.dart';
import '../models/user.dart';
import '../services/org_api.dart';
import '../theme/app_theme.dart';
import '../theme/modern_glass_button.dart';

class OrganizationSettingsDialog extends StatefulWidget {
  final Organization organization;
  final PermissionState permissionState;
  final OrgApi orgApi;

  const OrganizationSettingsDialog({
    super.key,
    required this.organization,
    required this.permissionState,
    required this.orgApi,
  });

  @override
  State<OrganizationSettingsDialog> createState() =>
      _OrganizationSettingsDialogState();
}

class _OrganizationSettingsDialogState
    extends State<OrganizationSettingsDialog> {
  int _selectedTabIndex = 0;
  List<Member> _members = [];
  List<Invitation> _invitations = [];
  List<JoinRequest> _joinRequests = [];
  String? _inviteLink;
  bool _isLoading = false;
  String? _error;
  List<User> _userSuggestions = [];
  late final TextEditingController usernameController;
  final LayerLink _layerLink = LayerLink();

  @override
  void initState() {
    super.initState();
    usernameController = TextEditingController();
    _loadData();
  }

  @override
  void dispose() {
    usernameController.dispose();
    super.dispose();
  }

  Future<void> _loadData() async {
    if (!mounted) return;
    setState(() => _isLoading = true);

    String? error;
    List<Member> members = [];
    List<Invitation> invitations = [];
    List<JoinRequest> joinRequests = [];
    String? inviteLink;

    try {
      members = await widget.orgApi.getMembers(widget.organization.id);
    } catch (e) {
      developer.log(
        'Error loading members: $e',
        name: 'OrganizationSettingsDialog',
      );
      error ??= 'Failed to load members: $e';
    }

    try {
      invitations = await widget.orgApi.getInvitations(widget.organization.id);
    } catch (e) {
      developer.log(
        'Error loading invitations: $e',
        name: 'OrganizationSettingsDialog',
      );
      error ??= 'Failed to load invitations: $e';
    }

    try {
      joinRequests = await widget.orgApi.getJoinRequests(
        widget.organization.id,
      );
    } catch (e) {
      developer.log(
        'Error loading join requests: $e',
        name: 'OrganizationSettingsDialog',
      );
      error ??= 'Failed to load join requests: $e';
    }

    try {
      inviteLink = await widget.orgApi.getInviteLink(widget.organization.id);
    } catch (e) {
      developer.log(
        'Error loading invite link: $e',
        name: 'OrganizationSettingsDialog',
      );
      error ??= 'Failed to load invite link: $e';
    }

    if (!mounted) return;
    setState(() {
      _members = members;
      _invitations = invitations;
      _joinRequests = joinRequests;
      _inviteLink = inviteLink;
      _isLoading = false;
      _error = error;
    });
  }

  Future<void> _updateMemberRole(String userId, String newRole) async {
    try {
      await widget.orgApi.updateMemberRole(
        widget.organization.id,
        userId,
        newRole,
      );
      await _loadData(); // Refresh
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to update role: $e')));
    }
  }

  Future<void> _removeMember(String userId) async {
    try {
      await widget.orgApi.removeMember(widget.organization.id, userId);
      await _loadData(); // Refresh
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to remove member: $e')));
    }
  }

  Future<void> _inviteUser(String username, String role) async {
    try {
      await widget.orgApi.createInvitation(
        widget.organization.id,
        username,
        role,
      );
      await _loadData(); // Refresh
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to send invitation: $e')));
    }
  }

  Future<void> _cancelInvitation(String invitationId) async {
    try {
      await widget.orgApi.cancelInvitation(
        widget.organization.id,
        invitationId,
      );
      await _loadData(); // Refresh
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Failed to cancel invitation: $e')),
      );
    }
  }

  Future<void> _acceptJoinRequest(String requestId, String role) async {
    try {
      await widget.orgApi.acceptJoinRequest(
        widget.organization.id,
        requestId,
        role,
      );
      await _loadData(); // Refresh
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to accept request: $e')));
    }
  }

  Future<void> _rejectJoinRequest(String requestId) async {
    try {
      await widget.orgApi.rejectJoinRequest(widget.organization.id, requestId);
      await _loadData(); // Refresh
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to reject request: $e')));
    }
  }

  Future<void> _regenerateInviteLink() async {
    try {
      final newLink = await widget.orgApi.regenerateInviteLink(
        widget.organization.id,
      );
      setState(() => _inviteLink = newLink);
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('Failed to regenerate link: $e')));
    }
  }

  void _copyInviteLink() {
    if (_inviteLink != null) {
      Clipboard.setData(
        ClipboardData(text: 'https://b0esche.cloud/join?token=$_inviteLink'),
      );
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Invite link copied to clipboard')),
      );
    }
  }

  bool get _canManage =>
      widget.permissionState is PermissionLoaded &&
      (widget.permissionState as PermissionLoaded).capabilities.canAdmin;

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: AppTheme.primaryBackground,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
      child: Container(
        width: 600,
        height: 500,
        padding: const EdgeInsets.all(24),
        child: Column(
          children: [
            // Header
            Row(
              children: [
                Text(
                  'Manage ${widget.organization.name}',
                  style: TextStyle(
                    color: AppTheme.primaryText,
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () => Navigator.of(context).pop(),
                  icon: Icon(Icons.close, color: AppTheme.secondaryText),
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                ),
              ],
            ),
            const SizedBox(height: 16),

            // Custom Tabs
            Row(
              children: [
                _buildTabButton('Members', 0),
                _buildTabButton('Invite', 1),
                _buildTabButton('Requests', 2),
              ],
            ),
            const SizedBox(height: 16),

            // Tab content
            Expanded(
              child: _isLoading
                  ? Center(
                      child: CircularProgressIndicator(
                        color: AppTheme.accentColor,
                      ),
                    )
                  : _error != null
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            _error!,
                            style: TextStyle(color: AppTheme.errorColor),
                          ),
                          const SizedBox(height: 16),
                          ModernGlassButton(
                            onPressed: _loadData,
                            child: const Text('Retry'),
                          ),
                        ],
                      ),
                    )
                  : _buildTabContent(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTabButton(String text, int index) {
    final isSelected = _selectedTabIndex == index;
    return Expanded(
      child: GestureDetector(
        onTap: () => setState(() => _selectedTabIndex = index),
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
          margin: const EdgeInsets.symmetric(horizontal: 2),
          decoration: BoxDecoration(
            color: isSelected
                ? AppTheme.accentColor.withValues(alpha: 0.15)
                : Colors.transparent,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: isSelected
                  ? AppTheme.accentColor
                  : AppTheme.secondaryText.withValues(alpha: 0.3),
              width: 1.5,
            ),
            boxShadow: isSelected
                ? [
                    BoxShadow(
                      color: AppTheme.accentColor.withValues(alpha: 0.3),
                      blurRadius: 8,
                      spreadRadius: 1,
                    ),
                  ]
                : null,
          ),
          child: AnimatedDefaultTextStyle(
            duration: const Duration(milliseconds: 200),
            style: TextStyle(
              color: isSelected ? AppTheme.accentColor : AppTheme.secondaryText,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              fontSize: 14,
            ),
            child: Text(text, textAlign: TextAlign.center),
          ),
        ),
      ),
    );
  }

  Widget _buildTabContent() {
    switch (_selectedTabIndex) {
      case 0:
        return _buildMembersTab();
      case 1:
        return _buildInviteTab();
      case 2:
        return _buildRequestsTab();
      default:
        return _buildMembersTab();
    }
  }

  Widget _buildMembersTab() {
    return ListView.builder(
      itemCount: _members.length,
      itemBuilder: (context, index) {
        final member = _members[index];
        return ListTile(
          title: Text(
            member.user.displayName ?? member.user.username,
            style: TextStyle(color: AppTheme.primaryText),
          ),
          subtitle: Text(
            member.role,
            style: TextStyle(color: AppTheme.secondaryText),
          ),
          trailing: _canManage
              ? Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (member.role != 'owner')
                      DropdownButton<String>(
                        value: member.role,
                        items: ['admin', 'member'].map((role) {
                          return DropdownMenuItem(
                            value: role,
                            child: Text(role),
                          );
                        }).toList(),
                        onChanged: (newRole) {
                          if (newRole != null && newRole != member.role) {
                            _updateMemberRole(member.userId, newRole);
                          }
                        },
                      ),
                    if (member.role != 'owner')
                      IconButton(
                        icon: Icon(
                          Icons.remove_circle,
                          color: AppTheme.errorColor,
                        ),
                        onPressed: () => _removeMember(member.userId),
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                      ),
                  ],
                )
              : null,
        );
      },
    );
  }

  Widget _buildInviteTab() {
    String selectedRole = 'member';

    return Stack(
      children: [
        Column(
          children: [
            // Pending invitations
            if (_invitations.isNotEmpty) ...[
              Text(
                'Pending Invitations',
                style: TextStyle(
                  color: AppTheme.primaryText,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              SizedBox(
                height: 150,
                child: ListView.builder(
                  itemCount: _invitations.length,
                  itemBuilder: (context, index) {
                    final inv = _invitations[index];
                    return ListTile(
                      title: Text(
                        inv.username,
                        style: TextStyle(color: AppTheme.primaryText),
                      ),
                      subtitle: Text(
                        'Role: ${inv.role}',
                        style: TextStyle(color: AppTheme.secondaryText),
                      ),
                      trailing: IconButton(
                        icon: Icon(Icons.cancel, color: AppTheme.errorColor),
                        onPressed: () => _cancelInvitation(inv.id),
                        splashColor: Colors.transparent,
                        highlightColor: Colors.transparent,
                      ),
                    );
                  },
                ),
              ),
            ],

            // Invite link section
            if (_inviteLink != null) ...[
              const Divider(),
              Text(
                'Invite Link',
                style: TextStyle(
                  color: AppTheme.primaryText,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              Row(
                children: [
                  Expanded(
                    child: Text(
                      'https://b0esche.cloud/join?token=${_inviteLink ?? ''}',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: AppTheme.secondaryText),
                    ),
                  ),
                  const SizedBox(width: 16),
                  ModernGlassButton(
                    onPressed: _copyInviteLink,
                    child: const Icon(Icons.content_copy),
                  ),
                  if (_canManage) ...[
                    const SizedBox(width: 16),
                    ModernGlassButton(
                      onPressed: _regenerateInviteLink,
                      child: const Icon(Icons.refresh),
                    ),
                  ],
                ],
              ),
            ] else if (_canManage) ...[
              const Divider(),
              const Text('No invite link available'),
            ],

            // Invite form
            const Divider(),
            Text(
              'Invite New User',
              style: TextStyle(
                color: AppTheme.primaryText,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            CompositedTransformTarget(
              link: _layerLink,
              child: TextField(
                controller: usernameController,
                cursorColor: AppTheme.accentColor,
                decoration: InputDecoration(
                  hintText: 'username',
                  hintStyle: TextStyle(color: AppTheme.secondaryText),
                  contentPadding: const EdgeInsets.all(12),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: AppTheme.accentColor.withValues(alpha: 0.3),
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: AppTheme.accentColor.withValues(alpha: 0.3),
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: AppTheme.accentColor),
                  ),
                ),
                style: TextStyle(color: AppTheme.primaryText),
                onChanged: (value) async {
                  if (value.length > 2) {
                    try {
                      _userSuggestions = await widget.orgApi.searchUsers(
                        widget.organization.id,
                        value,
                      );
                    } catch (e) {
                      _userSuggestions = [];
                    }
                    setState(() {});
                  } else {
                    _userSuggestions = [];
                    setState(() {});
                  }
                },
              ),
            ),
            const SizedBox(height: 16),
            Theme(
              data: Theme.of(context).copyWith(
                splashFactory: NoSplash.splashFactory,
                buttonTheme: ButtonThemeData(splashColor: Colors.transparent),
                materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                highlightColor: Colors.transparent,
                splashColor: Colors.transparent,
              ),
              child: DropdownButtonFormField<String>(
                initialValue: selectedRole,
                items: ['admin', 'member'].map((role) {
                  return DropdownMenuItem(
                    value: role,
                    child: Material(
                      type: MaterialType.transparency,
                      child: Text(role),
                    ),
                  );
                }).toList(),
                dropdownColor: AppTheme.primaryBackground,
                onChanged: (value) => selectedRole = value ?? 'member',
                decoration: InputDecoration(
                  labelText: 'Role',
                  labelStyle: TextStyle(color: AppTheme.secondaryText),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: AppTheme.accentColor.withValues(alpha: 0.3),
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: AppTheme.accentColor),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: AppTheme.accentColor.withValues(alpha: 0.3),
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 16),
            SizedBox(
              width: 240,
              child: ModernGlassButton(
                onPressed: () {
                  if (_canManage) {
                    final username = usernameController.text.trim();
                    if (username.isNotEmpty) {
                      _inviteUser(username, selectedRole);
                      usernameController.clear();
                    }
                  } else {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text(
                          'You do not have permission to send invitations',
                        ),
                      ),
                    );
                  }
                },
                child: const Text('Send Invitation'),
              ),
            ),
          ],
        ),
        if (_userSuggestions.isNotEmpty)
          CompositedTransformFollower(
            link: _layerLink,
            offset: const Offset(0, 48),
            child: Container(
              width: 300,
              height: 100,
              decoration: BoxDecoration(
                color: AppTheme.primaryBackground,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: AppTheme.accentColor.withValues(alpha: 0.3),
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.2),
                    blurRadius: 8,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: ListView.builder(
                itemCount: _userSuggestions.length,
                itemBuilder: (context, index) {
                  final user = _userSuggestions[index];
                  return ListTile(
                    title: Text(
                      user.displayName ?? user.username,
                      style: TextStyle(color: AppTheme.primaryText),
                    ),
                    onTap: () {
                      usernameController.text = user.username;
                      setState(() => _userSuggestions = []);
                    },
                  );
                },
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildRequestsTab() {
    return ListView.builder(
      itemCount: _joinRequests.length,
      itemBuilder: (context, index) {
        final req = _joinRequests[index];
        return ListTile(
          title: Text(
            req.user.displayName ?? req.user.username,
            style: TextStyle(color: AppTheme.primaryText),
          ),
          subtitle: Text(
            'Requested to join',
            style: TextStyle(color: AppTheme.secondaryText),
          ),
          trailing: _canManage
              ? Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    TextButton(
                      style: ButtonStyle(
                        splashFactory: NoSplash.splashFactory,
                        overlayColor: WidgetStateProperty.resolveWith<Color?>((
                          Set<WidgetState> states,
                        ) {
                          if (states.contains(WidgetState.pressed)) {
                            return Colors.transparent;
                          }
                          return null;
                        }),
                      ),
                      onPressed: () => _acceptJoinRequest(req.id, 'member'),
                      child: const Text('Accept'),
                    ),
                    TextButton(
                      style: ButtonStyle(
                        splashFactory: NoSplash.splashFactory,
                        overlayColor: WidgetStateProperty.resolveWith<Color?>((
                          Set<WidgetState> states,
                        ) {
                          if (states.contains(WidgetState.pressed)) {
                            return Colors.transparent;
                          }
                          return null;
                        }),
                      ),
                      onPressed: () => _rejectJoinRequest(req.id),
                      child: Text(
                        'Reject',
                        style: TextStyle(color: AppTheme.errorColor),
                      ),
                    ),
                  ],
                )
              : null,
        );
      },
    );
  }
}
