import 'package:be_happy/domain/usecase/get_scooter_order_route_history_usecase.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:yandex_mapkit/yandex_mapkit.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 '../event/route_event.dart';
import '../state/route_state.dart';
import '../viewmodel/route_bloc.dart';

class OrderHistoryDetailScreen extends StatelessWidget {
  final ScooterOrder order;

  const OrderHistoryDetailScreen({
    super.key,
    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.totalPricePrint ?? '${order.totalPrice?.toStringAsFixed(2) ?? '0.00'} BYN';

    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(gradient: AppColors.phoneScreenBg),
        child: SafeArea(
          child: Column(
            children: [
              const SizedBox(height: 16),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20),
                child: CustomAppBar(title: 'Поездка $date'),
              ),

              const SizedBox(height: 16),

              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.symmetric(horizontal: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      BlocProvider(
                        create: (context) => RouteBloc(
                          getRouteUseCase: getIt<GetScooterOrderRouteHistoryUsecase>(), // Используем DI (Service Locator)
                        )..add(FetchRouteEvent(order.id)),
                        child: Container(
                          height: 280,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(16),
                            child: BlocBuilder<RouteBloc, RouteState>(
                              builder: (context, state) {
                                if (state is RouteLoading) {
                                  return const Center(child: CircularProgressIndicator());
                                }

                                if (state is RouteLoaded) {
                                  final List<Point> yandexPoints = state.points.map((p) =>
                                      Point(latitude: p.latitude, longitude: p.longitude)
                                  ).toList();
                                  return YandexMap(
                                    rotateGesturesEnabled: false,
                                    scrollGesturesEnabled: false,
                                    tiltGesturesEnabled: false,
                                    zoomGesturesEnabled: false,
                                    mapObjects: [
                                      PolylineMapObject(
                                        mapId: const MapObjectId('route_line'),
                                        polyline: Polyline(points: yandexPoints),
                                        strokeColor: Colors.blue,
                                        strokeWidth: 3,
                                      ),
                                    ],
                                    onMapCreated: (controller) async {
                                      final bounds = _calculateBounds(yandexPoints);
                                      await controller.moveCamera(
                                        CameraUpdate.newBounds(bounds),
                                      );
                                      await controller.moveCamera(CameraUpdate.zoomOut());
                                    },
                                  );
                                }

                                if (state is RouteError) {
                                  return Center(child: Text(state.message, style: const TextStyle(color: Colors.grey)));
                                }

                                return const SizedBox.shrink();
                              },
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(height: 16),

                      // 🔹 ИНФОРМАЦИЯ О ПОЕЗДКЕ
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: const Color(0xFF0A0F2E).withOpacity(0.7),
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Row(
                          children: [
                            // Фото самоката
                            Container(
                              width: 60,
                              height: 60,
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.1),
                                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: 32,
                                  );
                                },
                              ),
                            ),
                            const SizedBox(width: 12),
                            // Информация
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    date,
                                    style: const TextStyle(
                                      color: Colors.white,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                  const SizedBox(height: 8),
                                  Row(
                                    children: [
                                      Icon(
                                        Icons.qr_code_2,
                                        color: Colors.white.withOpacity(0.6),
                                        size: 16,
                                      ),
                                      const SizedBox(width: 4),
                                      Text(
                                        scooterNumber,
                                        style: TextStyle(
                                          color: Colors.white.withOpacity(0.8),
                                          fontSize: 14,
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            ),
                            // Цена
                            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,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),


                      if (order.status != 'Paid') ...[
                        const SizedBox(height: 16),
                        GradientButton(
                          text: 'Оплатить',
                          showArrows: true,
                          height: 56,
                          width: double.infinity,
                          fontSize: 16,
                          onTap: () {
                            context.go('/home/checkout/${order.id}');
                          },
                        ),
                      ],

                      const SizedBox(height: 16),

                      // 🔹 ДЕТАЛИ ПОЕЗДКИ
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: const Color(0xFF0A0F2E).withOpacity(0.7),
                          borderRadius: BorderRadius.circular(16),
                        ),
                        child: Column(
                          children: [
                            _DetailRow(
                              label: 'Старт',
                              value: _formatTime(order.startAt),
                            ),
                            const SizedBox(height: 12),
                            _DetailRow(
                              label: 'Завершение',
                              value: _formatTime(order.finishAt),
                            ),
                            const SizedBox(height: 12),
                            _DetailRow(
                              label: 'Расстояние',
                              value: '${order.mileage.toStringAsFixed(2)?? '0'} км',
                            ),
                            const SizedBox(height: 12),
                            _DetailRow(
                              label: 'Скорость',
                              value: '${order.avgSpeed ?? '0'} км/ч',
                            ),
                            const SizedBox(height: 12),
                            _DetailRow(
                              label: 'Тариф',
                              value: order.plan?.title ?? '—',
                            ),
                            const SizedBox(height: 12),
                            _DetailRow(
                              label: 'Страховка',
                              value: order.isInsurance ? "${order.insurancePrice} руб." : '—',
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 24),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 🔹 ВИДЖЕТ СТРОКИ С ДЕТАЛЯМИ
  Widget _DetailRow({required String label, required String value}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            color: Colors.white.withOpacity(0.6),
            fontSize: 14,
          ),
        ),
        Text(
          value,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 14,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

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

  String _formatTime(DateTime? date) {
    if (date == null) return '—';
    final localDate = date.toLocal();
    return '${localDate.hour.toString().padLeft(2, '0')}:${localDate.minute.toString().padLeft(2, '0')}';
  }

  BoundingBox _calculateBounds(List<Point> points) {
    double minLat = points.first.latitude;
    double minLng = points.first.longitude;
    double maxLat = points.first.latitude;
    double maxLng = points.first.longitude;

    for (var p in points) {
      if (p.latitude < minLat) minLat = p.latitude;
      if (p.latitude > maxLat) maxLat = p.latitude;
      if (p.longitude < minLng) minLng = p.longitude;
      if (p.longitude > maxLng) maxLng = p.longitude;
    }

    return BoundingBox(
      southWest: Point(latitude: minLat, longitude: minLng),
      northEast: Point(latitude: maxLat, longitude: maxLng),
    );
  }
}