import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import 'package:doormile/shared/models/models.dart';
import 'package:doormile/core/theme/app_colors.dart';
import 'package:doormile/core/theme/app_theme.dart';
import 'package:doormile/core/widgets/common.dart';

class LiveTrackingScreen extends StatelessWidget {
  final Order? order;
  const LiveTrackingScreen({super.key, this.order});

  @override
  Widget build(BuildContext context) {
    final id = order?.id ?? 'DM-CHN-BLR-7741';
    final eta = order?.eta ?? '2:30 PM';
    return Scaffold(
      backgroundColor: AppColors.surface,
      body: Stack(
        children: [
          // Faux map
          Positioned.fill(
            child: CustomPaint(painter: _MapPainter()),
          ),
          // Top bar
          SafeArea(
            child: Padding(
              padding: const EdgeInsets.all(12),
              child: Row(
                children: [
                  _circleBtn(Icons.arrow_back, () => Navigator.pop(context)),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text('Live Tracking',
                        style: AppTheme.headlineSm.copyWith(color: AppColors.primary),
                        overflow: TextOverflow.ellipsis),
                  ),
                  const SizedBox(width: 8),
                  StatusChip(
                    label: 'EV Priority',
                    icon: Icons.eco,
                    color: AppColors.tertiary,
                    bg: Colors.white,
                  ),
                ],
              ),
            ),
          ),
          // Bottom detail sheet
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              width: double.infinity,
              decoration: const BoxDecoration(
                color: AppColors.surface,
                borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
                boxShadow: [
                  BoxShadow(color: Color(0x1A000000), blurRadius: 24, offset: Offset(0, -6)),
                ],
              ),
              child: SafeArea(
                top: false,
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(16, 14, 16, 16),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('PARCEL ID',
                                    style: AppTheme.caption.copyWith(letterSpacing: 1)),
                                Text(id,
                                    style: AppTheme.headlineSm
                                        .copyWith(fontWeight: FontWeight.w700)),
                              ],
                            ),
                          ),
                          StatusChip(
                            label: 'In transit',
                            color: AppColors.tertiary,
                            bg: AppColors.tertiaryFixed.withValues(alpha: 0.5),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Text('ETA $eta',
                          style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
                      const SizedBox(height: 16),
                      const _MileStepper(activeIndex: 2),
                      const SizedBox(height: 16),
                      _riderCard(context),
                      const SizedBox(height: 12),
                      const EcoBanner(
                          text: 'Eco-Friendly Journey · saving 1.2kg of CO₂ on this delivery.'),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _circleBtn(IconData icon, VoidCallback onTap) {
    return Material(
      color: Colors.white,
      shape: const CircleBorder(),
      elevation: 2,
      child: InkWell(
        onTap: onTap,
        customBorder: const CircleBorder(),
        child: SizedBox(
            width: 40, height: 40, child: Icon(icon, color: AppColors.primary, size: 22)),
      ),
    );
  }

  Widget _riderCard(BuildContext context) {
    return AppCard(
      color: AppColors.surfaceContainerLow,
      child: Column(
        children: [
          Row(
            children: [
              const CircleAvatar(
                radius: 24,
                backgroundColor: AppColors.primaryFixed,
                child: Icon(Icons.person, color: AppColors.primary, size: 28),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Rahul Sharma',
                        style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                    Row(
                      children: [
                        StatusChip(
                            label: 'EV',
                            icon: Icons.bolt,
                            color: AppColors.tertiary,
                            bg: AppColors.tertiaryFixed.withValues(alpha: 0.5)),
                        const SizedBox(width: 6),
                        Flexible(
                          child: Text('KA-01-EV-4412',
                              style: AppTheme.caption, overflow: TextOverflow.ellipsis),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text('★ 4.9',
                      style: AppTheme.labelMd.copyWith(color: AppColors.warning)),
                  Text('4821 trips', style: AppTheme.caption),
                ],
              ),
            ],
          ),
          const SizedBox(height: 14),
          Row(
            children: [
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: () async {
                    final uri = Uri(scheme: 'tel', path: '+919876543210');
                    try {
                      await launchUrl(uri);
                    } catch (e) {
                      if (context.mounted) _toast(context, 'Could not launch dialer.');
                    }
                  },
                  icon: const Icon(Icons.call, size: 18),
                  label: const Text('Call Rider'),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: AppColors.primary,
                    side: const BorderSide(color: AppColors.primary),
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () => Navigator.pushNamed(context, '/chat', arguments: 'Rahul Sharma'),
                  icon: const Icon(Icons.chat_bubble_outline, size: 18),
                  label: const Text('Chat'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.primary,
                    foregroundColor: Colors.white,
                    elevation: 0,
                    padding: const EdgeInsets.symmetric(vertical: 12),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12)),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  void _toast(BuildContext context, String msg) {
    ScaffoldMessenger.of(context)
      ..hideCurrentSnackBar()
      ..showSnackBar(SnackBar(
        content: Text(msg),
        backgroundColor: AppColors.inverseSurface,
        behavior: SnackBarBehavior.floating,
      ));
  }
}

class _MileStepper extends StatelessWidget {
  final int activeIndex;
  const _MileStepper({required this.activeIndex});

  static const _stops = [
    ('Booked', AppColors.primary),
    ('First Mile', AppColors.firstMile),
    ('Mid Mile', AppColors.midMile),
    ('Last Mile', AppColors.lastMile),
  ];

  @override
  Widget build(BuildContext context) {
    return Row(
      children: List.generate(_stops.length, (i) {
        final done = i <= activeIndex;
        final stop = _stops[i];
        return Expanded(
          child: Column(
            children: [
              Row(
                children: [
                  Expanded(
                    child: Container(
                      height: 3,
                      color: i == 0
                          ? Colors.transparent
                          : (i <= activeIndex ? stop.$2 : AppColors.surfaceContainerHigh),
                    ),
                  ),
                  Container(
                    width: 14,
                    height: 14,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: done ? stop.$2 : AppColors.surfaceContainerHigh,
                      border: Border.all(
                          color: done ? stop.$2 : AppColors.outlineVariant, width: 2),
                    ),
                    child: done
                        ? const Icon(Icons.check, size: 8, color: Colors.white)
                        : null,
                  ),
                  Expanded(
                    child: Container(
                      height: 3,
                      color: i == _stops.length - 1
                          ? Colors.transparent
                          : (i < activeIndex ? _stops[i + 1].$2 : AppColors.surfaceContainerHigh),
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 6),
              Text(stop.$1,
                  style: AppTheme.caption.copyWith(
                    color: done ? stop.$2 : AppColors.onSurfaceVariant,
                    fontWeight: i == activeIndex ? FontWeight.w700 : FontWeight.w500,
                  )),
            ],
          ),
        );
      }),
    );
  }
}

/// Lightweight stylised street map with a dashed delivery route.
class _MapPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final bg = Paint()..color = const Color(0xFFEDEAE9);
    canvas.drawRect(Offset.zero & size, bg);

    final road = Paint()
      ..color = Colors.white
      ..strokeWidth = 10;
    final thin = Paint()
      ..color = const Color(0xFFE0DCDB)
      ..strokeWidth = 4;

    for (double x = 30; x < size.width; x += 70) {
      canvas.drawLine(Offset(x, 0), Offset(x, size.height), thin);
    }
    for (double y = 80; y < size.height; y += 70) {
      canvas.drawLine(Offset(0, y), Offset(size.width, y), thin);
    }
    canvas.drawLine(Offset(0, size.height * 0.35),
        Offset(size.width, size.height * 0.42), road);
    canvas.drawLine(Offset(size.width * 0.4, 0),
        Offset(size.width * 0.5, size.height * 0.7), road);

    // Dashed route
    final routePaint = Paint()
      ..color = AppColors.primary
      ..strokeWidth = 4
      ..style = PaintingStyle.stroke;
    final path = Path()
      ..moveTo(size.width * 0.2, size.height * 0.6)
      ..quadraticBezierTo(size.width * 0.35, size.height * 0.3,
          size.width * 0.55, size.height * 0.35)
      ..quadraticBezierTo(size.width * 0.75, size.height * 0.4,
          size.width * 0.7, size.height * 0.18);
    _drawDashed(canvas, path, routePaint);

    // Origin & destination markers
    final dot = Paint()..color = AppColors.primary;
    canvas.drawCircle(Offset(size.width * 0.2, size.height * 0.6), 7, dot);
    canvas.drawCircle(Offset(size.width * 0.2, size.height * 0.6), 3,
        Paint()..color = Colors.white);
    canvas.drawCircle(Offset(size.width * 0.7, size.height * 0.18), 9,
        Paint()..color = AppColors.primary);
    // Vehicle marker (mid route)
    final mid = Offset(size.width * 0.55, size.height * 0.35);
    canvas.drawCircle(mid, 16, Paint()..color = AppColors.primary.withValues(alpha: 0.2));
    canvas.drawCircle(mid, 9, Paint()..color = AppColors.tertiary);
  }

  void _drawDashed(Canvas canvas, Path path, Paint paint) {
    const dash = 8.0;
    const gap = 6.0;
    for (final metric in path.computeMetrics()) {
      double dist = 0;
      while (dist < metric.length) {
        canvas.drawPath(
            metric.extractPath(dist, dist + dash), paint);
        dist += dash + gap;
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
