import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import '../../core/app_colors.dart';
import '../../di/service_locator.dart';
import '../../domain/entities/scooter_order.dart';
import '../components/custom_app_bar.dart';
import '../components/gradient_button.dart';
import '../viewmodel/order_history_bloc.dart';
import 'order_history_detail_screen.dart';

class OrderHistoryScreen extends StatelessWidget {
  const OrderHistoryScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => getIt<OrderHistoryBloc>()..add(OrderHistoryFetchRequested()),
      child: const OrderHistoryView(),
    );
  }
}

class OrderHistoryView extends StatelessWidget {
  const OrderHistoryView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(gradient: AppColors.phoneScreenBg),
        child: SafeArea(
          child: Column(
            children: [
              const SizedBox(height: 16),
              const Padding(
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: CustomAppBar(title: 'История поездок'),
              ),

              const SizedBox(height: 16),

              Expanded(
                child: BlocBuilder<OrderHistoryBloc, OrderHistoryState>(
                  builder: (context, state) {
                    if (state.status == OrderHistoryStatus.loading && state.orders.isEmpty) {
                      return const Center(
                        child: CircularProgressIndicator(color: Colors.white),
                      );
                    }

                    if (state.status == OrderHistoryStatus.failure) {
                      return Center(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            const Text(
                              'Ошибка загрузки',
                              style: TextStyle(color: Colors.white, fontSize: 16),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              state.errorMessage ?? '',
                              style: TextStyle(color: Colors.white.withOpacity(0.6), fontSize: 14),
                              textAlign: TextAlign.center,
                            ),
                            const SizedBox(height: 16),
                            ElevatedButton(
                              onPressed: () {
                                context.read<OrderHistoryBloc>().add(OrderHistoryFetchRequested());
                              },
                              child: const Text('Повторить'),
                            ),
                          ],
                        ),
                      );
                    }

                    if (state.status == OrderHistoryStatus.empty) {
                      return const _EmptyState();
                    }

                    final groupedOrders = _groupByMonth(state.orders);

                    return RefreshIndicator(
                      onRefresh: () async {
                        context.read<OrderHistoryBloc>().add(OrderHistoryRefreshRequested());
                      },
                      child: ListView.builder(
                        padding: const EdgeInsets.symmetric(horizontal: 20),
                        itemCount: groupedOrders.length,
                        itemBuilder: (context, index) {
                          final monthKey = groupedOrders.keys.elementAt(index);
                          final orders = groupedOrders[monthKey]!;

                          return Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Padding(
                                padding: const EdgeInsets.symmetric(vertical: 12),
                                child: Text(
                                  _getMonthTitle(monthKey),
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.7),
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                              ...orders.map((order) => _OrderCard(order: order)),
                            ],
                          );
                        },
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Map<String, List<ScooterOrder>> _groupByMonth(List<ScooterOrder> orders) {
    final Map<String, List<ScooterOrder>> grouped = {};

    for (var order in orders) {
      final date = order.startAt ?? order.finishAt ?? DateTime.now();
      final localDate = date.toLocal();
      final monthKey = '${localDate.year}-${localDate.month.toString().padLeft(2, '0')}';

      if (!grouped.containsKey(monthKey)) {
        grouped[monthKey] = [];
      }
      grouped[monthKey]!.add(order);
    }

    final sortedKeys = grouped.keys.toList()..sort((a, b) => b.compareTo(a));

    return Map.fromEntries(
      sortedKeys.map((key) => MapEntry(key, grouped[key]!)),
    );
  }

  String _getMonthTitle(String monthKey) {
    final parts = monthKey.split('-');
    final year = int.parse(parts[0]);
    final month = int.parse(parts[1]);

    const months = [
      'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
      'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
    ];

    return '${months[month - 1]} $year';
  }
}

class _EmptyState extends StatelessWidget {
  const _EmptyState();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 40),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/history.png',
              width: 380,
              fit: BoxFit.contain,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  width: 280,
                  height: 280,
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: const Icon(
                    Icons.history_outlined,
                    size: 120,
                    color: Colors.white38,
                  ),
                );
              },
            ),

            const SizedBox(height: 40),

            const Text(
              'У вас пока нет завершенных поездок.',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontWeight: FontWeight.w500,
                height: 1.4,
              ),
            ),

            const SizedBox(height: 32),

            GradientButton(
              text: 'Прокатиться',
              showArrows: true,
              height: 56,
              width: double.infinity,
              fontSize: 16,
              onTap: () {
                context.go('/home');
              },
            ),
          ],
        ),
      ),
    );
  }
}

// 🔹 КАРТОЧКА ОДНОГО ЗАКАЗА
class _OrderCard extends StatelessWidget {
  final ScooterOrder order;

  const _OrderCard({required this.order});

  @override
  Widget build(BuildContext context) {
    final date = _formatDate(order.startAt ?? order.finishAt ?? DateTime.now());
    final scooterNumber = order.scooter?.title ?? '№${order.scooterId}';
    final price = '${order.totalPrice?.toStringAsFixed(2)} BYN' ?? '${order.totalPrice?.toStringAsFixed(2) ?? '0.00'} BYN';

    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => OrderHistoryDetailScreen(order: order),
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.fromLTRB(4, 4, 16, 4),
        decoration: BoxDecoration(
          color: const Color(0xFF0A0F2E).withOpacity(0.7),
          borderRadius: BorderRadius.circular(16),
        ),
        child: Row(
          children: [
            Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(12),
                child: Image.asset(
                  'assets/icons/e6a5dcb6a3e2ec2362c25ea49509ab10d2312b19-reverse.png',
                  fit: BoxFit.contain,
                  errorBuilder: (context, error, stackTrace) {
                    return const Icon(
                      Icons.electric_scooter,
                      color: Colors.white,
                      size: 48,
                    );
                  },
                ),
              ),
            ),

            const SizedBox(width: 16),

            // 🔹 СТОЛБЕЦ 2: Дата, время, ID самоката
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Дата и время
                  Text(
                    date,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const SizedBox(height: 8),
                  // ID самоката
                  Row(
                    children: [
                      Icon(
                        Icons.qr_code_2,
                        color: Colors.white.withOpacity(0.6),
                        size: 18,
                      ),
                      const SizedBox(width: 4),
                      Text(
                        scooterNumber,
                        style: TextStyle(
                          color: Colors.white.withOpacity(0.8),
                          fontSize: 15,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),


            // 🔹 СТОЛБЕЦ 3: Цена
             Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Container(
                    width: 100,
                    alignment: Alignment.center,
                    padding: EdgeInsets.all(4),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(12), // Опционально: скругление углов
                    ),
                    child: Text(
                      order.status == 'Paid' ? 'ОПЛАЧЕН' : 'НЕ ОПЛАЧЕН',
                      style: TextStyle(
                        color: order.status == 'Paid'
                            ? Colors.greenAccent
                            : Colors.redAccent,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                        letterSpacing: 0.5,
                      ),
                    ),
                  ),

                  const SizedBox(height: 8),

                  Text(
                    price,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),

          ],
        ),
      ),
    );
  }

  // 🔹 ФОРМАТИРОВАНИЕ ДАТЫ (с корректным сравнением)
  String _formatDate(DateTime date) {
    // ✅ Конвертируем в локальное время
    final localDate = date.toLocal();
    final now = DateTime.now();

    // ✅ Сравниваем только дату (год, месяц, день), игнорируя время
    final isToday = localDate.year == now.year &&
        localDate.month == now.month &&
        localDate.day == now.day;

    final yesterday = now.subtract(const Duration(days: 1));
    final isYesterday = localDate.year == yesterday.year &&
        localDate.month == yesterday.month &&
        localDate.day == yesterday.day;

    if (isToday) {
      return 'Сегодня, ${_formatTime(localDate)}';
    } else if (isYesterday) {
      return 'Вчера, ${_formatTime(localDate)}';
    } else {
      return '${_formatDateFull(localDate)}, ${_formatTime(localDate)}';
    }
  }

  String _formatDateFull(DateTime date) {
    const months = [
      'января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
      'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'
    ];
    return '${date.day} ${months[date.month - 1]}';
  }

  String _formatTime(DateTime date) {
    return '${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}';
  }
}