import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import 'package:messenger_app/l10n/app_localizations.dart';
import '../bloc/chat_bloc.dart';
import '../bloc/chat_event.dart';
import '../bloc/chat_state.dart';
import '../../domain/entities/chat.dart';
import '../../domain/entities/message.dart';

class ChatDetailPage extends StatefulWidget {
  final Chat chat;
  final String currentUserId;

  const ChatDetailPage({
    super.key,
    required this.chat,
    required this.currentUserId,
  });

  @override
  State<ChatDetailPage> createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  final _messageController = TextEditingController();
  final _scrollController = ScrollController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: BlocBuilder<ChatBloc, ChatState>(
          builder: (context, state) {
            final currentChat = state.maybeWhen(
              chatSelected: (chat, messages, typingUsers, lastUpdate) => chat,
              messagesLoaded: (chat, messages, typingUsers, lastUpdate) => chat,
              orElse: () => widget.chat,
            );
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(currentChat.type == 'favorites' ? AppLocalizations.of(context)!.favorites : currentChat.title),
                if (currentChat.type != 'favorites')
                  _buildPresenceStatus(currentChat, state),
              ],
            );
          },
        ),
        actions: [
          IconButton(icon: const Icon(Icons.more_vert), onPressed: () {}),
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: BlocBuilder<ChatBloc, ChatState>(
              builder: (context, state) {
                return state.maybeWhen(
                  chatSelected: (chat, messages, typingUsers, lastUpdate) => _buildMessageList(messages),
                  messagesLoaded: (chat, messages, typingUsers, lastUpdate) => _buildMessageList(messages),
                  loading: (typingUsers, lastUpdate) => const Center(child: CircularProgressIndicator()),
                  error: (msg, typingUsers, lastUpdate) => Center(child: Text('Ошибка: $msg')),
                  orElse: () => const Center(child: Text('Начните общение')),
                );
              },
            ),
          ),
          _buildMessageInput(widget.chat),
        ],
      ),
    );
  }

  Widget _buildPresenceStatus(Chat chat, ChatState state) {
    // Check typing status first
    final typingInChat = state.typingUsers[chat.id];
    final otherMemberTyping = typingInChat?.any((id) => id != widget.currentUserId) ?? false;
    
    if (otherMemberTyping) {
      return const Text(
        'печатает...',
        style: TextStyle(fontSize: 12, color: Colors.white70, fontWeight: FontWeight.normal, fontStyle: FontStyle.italic),
      );
    }

    final participants = chat.participants;
    if (participants == null || participants.isEmpty) {
      return const SizedBox.shrink();
    }

    final otherMember = participants.firstWhere(
      (m) => m.id != widget.currentUserId,
      orElse: () => participants[0],
    );

    final l10n = AppLocalizations.of(context)!;
    final locale = Localizations.localeOf(context).languageCode;
    
    if (otherMember.isOnline == true) {
      return Row(
        children: [
          Container(
            width: 6,
            height: 6,
            decoration: const BoxDecoration(
              color: Colors.greenAccent,
              shape: BoxShape.circle,
            ),
          ),
          const SizedBox(width: 4),
          Text(
            l10n.online,
            style: const TextStyle(fontSize: 12, color: Colors.white70, fontWeight: FontWeight.normal),
          ),
        ],
      );
    } else if (otherMember.lastSeen != null) {
      return Text(
        _formatLastSeen(otherMember.lastSeen!, l10n, locale),
        style: const TextStyle(fontSize: 12, color: Colors.white70, fontWeight: FontWeight.normal),
      );
    }
    return const SizedBox.shrink();
  }

  String _formatLastSeen(DateTime utcDate, AppLocalizations l10n, String locale) {
    final lastSeen = utcDate.toLocal();
    final now = DateTime.now();
    final difference = now.difference(lastSeen);
    final timeStr = DateFormat.Hm(locale).format(lastSeen);

    // Case 1: Same day (within 24h of NOW, but specifically checking calendar day is better for "yesterday")
    // Let's use difference for "relative" and calendar days for "yesterday/day before"
    
    final today = DateTime(now.year, now.month, now.day);
    final seenDay = DateTime(lastSeen.year, lastSeen.month, lastSeen.day);
    final dayDiff = today.difference(seenDay).inDays;

    if (dayDiff == 0) {
      // Same calendar day
      if (difference.inHours > 0) {
        return l10n.lastSeenRelative(difference.inHours, difference.inMinutes % 60);
      } else if (difference.inMinutes > 0) {
        return l10n.lastSeenRelativeMinutes(difference.inMinutes);
      } else {
        return l10n.lastSeenJustNow;
      }
    } else if (dayDiff == 1) {
      return l10n.lastSeenYesterday(timeStr);
    } else if (dayDiff == 2) {
      return l10n.lastSeenDayBeforeYesterday(timeStr);
    } else {
      final dateStr = DateFormat.MMMMd(locale).format(lastSeen);
      return l10n.lastSeen(dateStr, timeStr);
    }
  }

  String _formatDate(DateTime date, String locale) {
    final now = DateTime.now();
    final localDate = date.toLocal();
    if (localDate.year == now.year) {
      return DateFormat.MMMMd(locale).format(localDate);
    }
    return DateFormat.yMMMMd(locale).format(localDate);
  }

  Widget _buildMessageList(List<Message> messages) {
    final l10n = AppLocalizations.of(context)!;
    final locale = Localizations.localeOf(context).languageCode;
    
    if (messages.isEmpty) {
      return Center(child: Text(l10n.noMessages));
    }

    // Mark as read logic
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final unreadFromOthers = messages.where((m) => 
        m.senderId != widget.currentUserId && 
        m.status != MessageStatus.read
      ).toList();
      
      if (unreadFromOthers.isNotEmpty) {
        // Find the message with the highest sequenceId to mark everything up to it as read
        final latest = unreadFromOthers.reduce((a, b) => a.sequenceId > b.sequenceId ? a : b);
        context.read<ChatBloc>().add(ChatEvent.markAsRead(latest.chatId, latest.id, latest.sequenceId));
      }
    });

    final List<dynamic> items = [];
    for (int i = 0; i < messages.length; i++) {
      final message = messages[i];
      items.add(message);

      if (message.createdAt != null) {
        final localCreatedAt = message.createdAt!.toLocal();
        final currentDay = DateTime(localCreatedAt.year, localCreatedAt.month, localCreatedAt.day);
        
        if (i == messages.length - 1) {
          items.add(currentDay);
        } else {
          final nextMessage = messages[i + 1];
          if (nextMessage.createdAt != null) {
            final nextLocalCreatedAt = nextMessage.createdAt!.toLocal();
            final nextDay = DateTime(nextLocalCreatedAt.year, nextLocalCreatedAt.month, nextLocalCreatedAt.day);
            if (currentDay != nextDay) {
              items.add(currentDay);
            }
          }
        }
      }
    }

    return ListView.builder(
      controller: _scrollController,
      reverse: true,
      padding: const EdgeInsets.all(16),
      itemCount: items.length,
      itemBuilder: (context, index) {
        final item = items[index];
        
        if (item is DateTime) {
          return Center(
            child: Container(
              margin: const EdgeInsets.symmetric(vertical: 16),
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                _formatDate(item, locale),
                style: const TextStyle(fontSize: 12, color: Colors.black54),
              ),
            ),
          );
        }

        final message = item as Message;
        final isMe = message.senderId == widget.currentUserId;
        
        return Align(
          alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 2, horizontal: 8),
            constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: isMe ? const Color(0xFFE3F2FD) : Colors.white,
              borderRadius: BorderRadius.circular(16).copyWith(
                bottomRight: isMe ? const Radius.circular(2) : const Radius.circular(16),
                bottomLeft: !isMe ? const Radius.circular(2) : const Radius.circular(16),
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 2,
                  offset: const Offset(0, 1),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(
                  message.content,
                  style: const TextStyle(color: Colors.black87, fontSize: 16),
                ),
                const SizedBox(height: 2),
                Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (message.createdAt != null)
                      Text(
                        DateFormat.Hm(locale).format(message.createdAt!.toLocal()),
                        style: const TextStyle(
                          fontSize: 10,
                          color: Colors.black45,
                        ),
                      ),
                    if (isMe) ...[
                      const SizedBox(width: 4),
                      _buildStatusIcon(message),
                    ],
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildStatusIcon(Message message) {
    switch (message.status) {
      case MessageStatus.sending:
        return const Icon(Icons.access_time, size: 12, color: Colors.black45);
      case MessageStatus.delivered:
        return const Icon(Icons.check, size: 12, color: Colors.black45);
      case MessageStatus.read:
        return const Icon(Icons.done_all, size: 12, color: Colors.blue);
      case MessageStatus.error:
        return const Icon(Icons.error_outline, size: 12, color: Colors.red);
    }
  }

  Widget _buildMessageInput(Chat chat) {
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            offset: const Offset(0, -1),
            blurRadius: 4,
          ),
        ],
      ),
      child: SafeArea(
        child: Row(
          children: [
            IconButton(icon: const Icon(Icons.add), onPressed: () {}),
            Expanded(
              child: TextField(
                controller: _messageController,
                decoration: InputDecoration(
                  hintText: AppLocalizations.of(context)!.messageHint,
                  border: InputBorder.none,
                ),
                onChanged: (value) {
                  context.read<ChatBloc>().add(ChatEvent.sendTypingStatus(chat.id, value.isNotEmpty));
                },
                onSubmitted: (_) => _sendMessage(chat.id),
              ),
            ),
            IconButton(
              icon: const Icon(Icons.send),
              onPressed: () => _sendMessage(chat.id),
              color: Theme.of(context).primaryColor,
            ),
          ],
        ),
      ),
    );
  }

  void _sendMessage(String chatId) {
    final content = _messageController.text.trim();
    if (content.isNotEmpty) {
      context.read<ChatBloc>().add(ChatEvent.messageSent(chatId, content));
      context.read<ChatBloc>().add(ChatEvent.sendTypingStatus(chatId, false));
      _messageController.clear();
    }
  }
}
