// lib/features/admin/tabs/messages/admin_messages_main_tab.dart

import 'package:flutter/material.dart';

import '../../../../core/models/user.dart';
import '../../../../core/services/database_service.dart';
import 'channels_panel.dart';
import 'chat_conversation_panel.dart';
import 'chat_list_panel.dart';
import 'chat_models.dart';
import 'communities_panel.dart';
import 'meta_ai_panel.dart';
import 'resizable_split_view.dart';
import 'status_panel.dart';
import 'whatsapp_empty_state.dart';

const Color darkGreen = Color.fromARGB(255, 2, 105, 48);
const Color standardGold = Color.fromARGB(255, 204, 117, 4);
const Color chatBackground = Color(0xFFF4F7F5);
const Color _ink = Color(0xFF17231C);
const Color _muted = Color(0xFF66756C);
const Color _border = Color(0xFFE0E8E3);

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

  @override
  State<AdminMessagesMainTab> createState() => _AdminMessagesMainTabState();
}

class _AdminMessagesMainTabState extends State<AdminMessagesMainTab> {
  ChatContact? _selectedChat;
  LocalUser? _currentUser;
  bool _isLoading = true;
  String? _loadError;

  @override
  void initState() {
    super.initState();
    _loadPostgresUser();
  }

  Future<void> _loadPostgresUser() async {
    if (mounted) {
      setState(() {
        _isLoading = true;
        _loadError = null;
      });
    }

    try {
      final user = await DatabaseService.getLocalUser();
      if (!mounted) return;
      setState(() {
        _currentUser = user;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loadError = e.toString();
        _isLoading = false;
      });
    }
  }

  void _onChatSelected(ChatContact chat) {
    if (!mounted) return;
    setState(() => _selectedChat = chat);
  }

  void _clearSelection() {
    if (!mounted) return;
    setState(() => _selectedChat = null);
  }

  Widget _loadingState() {
    return const ColoredBox(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(color: darkGreen, strokeWidth: 2.4),
            SizedBox(height: 14),
            Text(
              'Opening Connect Messages...',
              style: TextStyle(
                color: _muted,
                fontWeight: FontWeight.w600,
                fontSize: 13,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _authenticationState() {
    final detail = _loadError == null
        ? 'Your signed-in profile could not be loaded. Please sign in again.'
        : 'Your signed-in profile could not be loaded. Please try again.';

    return ColoredBox(
      color: const Color(0xFFF7F9F8),
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 430),
          child: Container(
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(20),
              border: Border.all(color: _border),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(.04),
                  blurRadius: 24,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 58,
                  height: 58,
                  decoration: BoxDecoration(
                    color: darkGreen.withOpacity(.08),
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.lock_person_outlined,
                    color: darkGreen,
                    size: 28,
                  ),
                ),
                const SizedBox(height: 16),
                const Text(
                  'Authentication required',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: _ink,
                    fontSize: 18,
                    fontWeight: FontWeight.w800,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  detail,
                  textAlign: TextAlign.center,
                  style: const TextStyle(
                    color: _muted,
                    height: 1.45,
                    fontSize: 13,
                  ),
                ),
                const SizedBox(height: 18),
                FilledButton.icon(
                  onPressed: _loadPostgresUser,
                  style: FilledButton.styleFrom(
                    backgroundColor: darkGreen,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(
                      horizontal: 18,
                      vertical: 12,
                    ),
                  ),
                  icon: const Icon(Icons.refresh_rounded, size: 18),
                  label: const Text('Try again'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  ChatContact _rockAiContact() {
    return ChatContact(
      id: 'rock_ai_assistant',
      name: 'Rock AI',
      lastMessage: 'Ask me anything about the system...',
      time: DateTime.now(),
      otherUserEmail: 'ai@rockview.edu',
      isGroup: false,
      unreadCount: 0,
    );
  }

  Widget _destinationFor({
    required ChatContact chat,
    required bool singlePane,
    required String myEmail,
    required String myName,
    required String? myPic,
  }) {
    if (chat.id == 'rock_ai_assistant') {
      return MetaAIPanel(
        key: const ValueKey('rock_ai'),
        myEmail: myEmail,
        onBack: singlePane ? _clearSelection : null,
      );
    }

    if (chat.id == 'system_posts') {
      return ChannelsPanel(
        key: const ValueKey('system_posts'),
        onBack: singlePane ? _clearSelection : null,
      );
    }

    if (chat.id == 'system_tickets') {
      return StatusPanel(
        key: const ValueKey('system_tickets'),
        onBack: singlePane ? _clearSelection : null,
        myEmail: myEmail,
        myName: myName,
        myPic: myPic,
      );
    }

    if (chat.id == 'system_groups') {
      return CommunitiesPanel(
        key: const ValueKey('system_groups'),
        onBack: singlePane ? _clearSelection : null,
      );
    }

    return ChatConversationPanel(
      key: ValueKey('chat_${chat.id}'),
      chat: chat,
      isMobile: singlePane,
      onBack: singlePane ? _clearSelection : null,
      myEmail: myEmail,
    );
  }

  Widget _singlePane({
    required double width,
    required String myEmail,
    required String myName,
    required String? myPic,
  }) {
    final selected = _selectedChat;
    final child = selected == null
        ? ChatListPanel(
            key: const ValueKey('message_list'),
            onChatSelected: _onChatSelected,
            myEmail: myEmail,
            myName: myName,
            myPic: myPic,
          )
        : _destinationFor(
            chat: selected,
            singlePane: true,
            myEmail: myEmail,
            myName: myName,
            myPic: myPic,
          );

    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 220),
      switchInCurve: Curves.easeOutCubic,
      switchOutCurve: Curves.easeInCubic,
      transitionBuilder: (child, animation) {
        final offset = Tween<Offset>(
          begin: const Offset(.025, 0),
          end: Offset.zero,
        ).animate(animation);
        return FadeTransition(
          opacity: animation,
          child: SlideTransition(position: offset, child: child),
        );
      },
      child: child,
    );
  }

  Widget _widePane({
    required double width,
    required String myEmail,
    required String myName,
    required String? myPic,
  }) {
    final selected = _selectedChat;
    final rightWidget = selected == null
        ? WhatsAppEmptyState(
            onAskRockAI: () => _onChatSelected(_rockAiContact()),
          )
        : _destinationFor(
            chat: selected,
            singlePane: false,
            myEmail: myEmail,
            myName: myName,
            myPic: myPic,
          );

    final defaultLeftWidth = width >= 1500 ? 420.0 : 380.0;
    final maxLeftWidth = width >= 1500 ? 520.0 : 460.0;

    return Container(
      margin: const EdgeInsets.fromLTRB(10, 8, 10, 10),
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        border: Border.all(color: _border),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(.035),
            blurRadius: 20,
            offset: const Offset(0, 8),
          ),
        ],
      ),
      child: ResizableSplitView(
        defaultLeftWidth: defaultLeftWidth,
        minLeftWidth: 330,
        maxLeftWidth: maxLeftWidth,
        minRightWidth: 520,
        leftWidget: ChatListPanel(
          onChatSelected: _onChatSelected,
          selectedChatId: selected?.id,
          myEmail: myEmail,
          myName: myName,
          myPic: myPic,
        ),
        rightWidget: AnimatedSwitcher(
          duration: const Duration(milliseconds: 180),
          child: rightWidget,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (_isLoading) return _loadingState();

    final user = _currentUser;
    if (user == null || user.email.trim().isEmpty) {
      return _authenticationState();
    }

    final myEmail = user.email.toLowerCase().trim();
    final myName = user.fullName.trim().isEmpty ? 'Rockview User' : user.fullName;
    final myPic = user.profilePicture;

    return Scaffold(
      backgroundColor: chatBackground,
      body: SafeArea(
        top: false,
        child: LayoutBuilder(
          builder: (context, constraints) {
            final width = constraints.maxWidth;

            // A single-pane workspace is more comfortable on phones and
            // tablets. The resizable master/detail workspace begins only when
            // both panes can retain useful working width.
            if (width < 1100) {
              return _singlePane(
                width: width,
                myEmail: myEmail,
                myName: myName,
                myPic: myPic,
              );
            }

            return _widePane(
              width: width,
              myEmail: myEmail,
              myName: myName,
              myPic: myPic,
            );
          },
        ),
      ),
    );
  }
}
