import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'package:doormile/main.dart';
import 'package:doormile/shared/models/models.dart';
import 'package:doormile/shared/state/app_state.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 MyOrdersScreen extends StatefulWidget {
  /// When embedded in the bottom-nav shell we hide the back button.
  final bool embedded;
  const MyOrdersScreen({super.key, this.embedded = false});

  @override
  State<MyOrdersScreen> createState() => _MyOrdersScreenState();
}

class _MyOrdersScreenState extends State<MyOrdersScreen> {
  final _filters = const ['All', 'Active', 'Delivered', 'Cancelled'];
  int _filter = 0;
  Timer? _pollingTimer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<AppState>().fetchOrders();
    });
    
    // Start polling every 10 seconds for live status updates
    _pollingTimer = Timer.periodic(const Duration(seconds: 10), (_) {
      if (mounted) {
        context.read<AppState>().fetchOrders();
      }
    });
  }

  @override
  void dispose() {
    _pollingTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<AppState>();
    final orders = state.orders;
    final filtered = switch (_filter) {
      1 => orders.where((o) => o.status == OrderStatus.active).toList(),
      2 => orders.where((o) => o.status == OrderStatus.delivered).toList(),
      3 => orders.where((o) => o.status == OrderStatus.cancelled).toList(),
      _ => orders,
    };

    return AppBackground(
      child: Column(
          children: [
          ImmersiveHeader(
            title: 'My Parcels',
            subtitle: 'Track all your deliveries',
            icon: Icons.inventory_2_rounded,
            showBack: !widget.embedded,
          ),
          const SizedBox(height: 16),
          SizedBox(
              height: 44,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                padding: const EdgeInsets.symmetric(horizontal: 16),
                itemCount: _filters.length,
                separatorBuilder: (_, __) => const SizedBox(width: 8),
                itemBuilder: (context, i) {
                  final active = i == _filter;
                  return GestureDetector(
                    onTap: () => setState(() => _filter = i),
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 18),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: active ? AppColors.primary : AppColors.surfaceContainer,
                        borderRadius: BorderRadius.circular(999),
                      ),
                      child: Text(_filters[i],
                          style: AppTheme.labelMd.copyWith(
                              color: active ? Colors.white : AppColors.onSurfaceVariant)),
                    ),
                  );
                },
              ),
            ),
            Expanded(
              child: state.isLoadingOrders
                ? const Center(child: CircularProgressIndicator(color: AppColors.primary))
                : filtered.isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Container(
                            width: 100,
                            height: 100,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              gradient: LinearGradient(
                                colors: [AppColors.primary.withValues(alpha: 0.1), AppColors.primary.withValues(alpha: 0.25)],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              boxShadow: [
                                BoxShadow(
                                  color: AppColors.primary.withValues(alpha: 0.15),
                                  blurRadius: 24,
                                  spreadRadius: 4,
                                  offset: const Offset(0, 10),
                                ),
                              ],
                            ),
                            child: Center(
                              child: Container(
                                width: 68,
                                height: 68,
                                decoration: const BoxDecoration(
                                  color: Colors.white,
                                  shape: BoxShape.circle,
                                ),
                                child: const Icon(
                                  Icons.inventory_2_rounded,
                                  size: 34,
                                  color: AppColors.primary,
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(height: 24),
                          Text('No parcels found',
                              style: AppTheme.headlineSm.copyWith(color: AppColors.onSurface, fontWeight: FontWeight.w700)),
                          const SizedBox(height: 8),
                          Text('You have no active bookings in this category.',
                              style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
                          const SizedBox(height: 48), // Padding to lift it slightly above true center
                        ],
                      ),
                    )
                  : ListView.separated(
                      padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
                      itemCount: filtered.length,
                      separatorBuilder: (_, __) => const SizedBox(height: 14),
                      itemBuilder: (context, i) => _OrderCard(order: filtered[i]),
                    ),
            ),
          ],
        ),
      );
  }
}

class _OrderCard extends StatelessWidget {
  final Order order;
  const _OrderCard({required this.order});

  @override
  Widget build(BuildContext context) {
    final active = order.status == OrderStatus.active;
    return AppCard(
      onTap: () => Navigator.pushNamed(
        context,
        active ? Routes.liveTracking : Routes.shipmentJourney,
        arguments: order,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Order ID', style: AppTheme.caption),
                    Text('#${order.id}',
                        style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                  ],
                ),
              ),
              StatusChip(
                  label: order.status.label, color: order.status.color, bg: order.status.bg),
            ],
          ),
          const SizedBox(height: 14),
          // Route mini timeline
          _routeRow(Icons.radio_button_unchecked, order.fromLabel, order.fromSub,
              AppColors.primary, dashed: true),
          _routeRow(Icons.location_on, order.toLabel, order.toSub, AppColors.onSurfaceVariant),
          if (active) ...[
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Flexible(
                  child: Text('Journey Progress',
                      style: AppTheme.caption.copyWith(color: AppColors.primary),
                      overflow: TextOverflow.ellipsis),
                ),
                const SizedBox(width: 8),
                Text('${(order.progress * 3).toStringAsFixed(1)} / 3.0 Miles',
                    style: AppTheme.caption),
              ],
            ),
            const SizedBox(height: 6),
            JourneyProgressBar(value: order.progress),
          ],
          const SizedBox(height: 12),
          Row(
            children: [
              if (order.ecoRoute) ...[
                const Icon(Icons.eco, size: 14, color: AppColors.tertiary),
                const SizedBox(width: 4),
                Text('CO₂ saved: ${order.co2Saved} (EV)',
                    style: AppTheme.caption.copyWith(color: AppColors.tertiary)),
              ],
            ],
          ),
          const Divider(height: 22, color: AppColors.surfaceContainer),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(order.date,
                  style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
              Text('₹${order.amount.toStringAsFixed(2)}',
                  style: AppTheme.headlineSm.copyWith(fontWeight: FontWeight.w700)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _routeRow(IconData icon, String title, String sub, Color color,
      {bool dashed = false}) {
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            children: [
              Icon(icon, size: 18, color: color),
              if (dashed)
                Expanded(
                  child: Container(
                    width: 1.5,
                    margin: const EdgeInsets.symmetric(vertical: 2),
                    color: AppColors.outlineVariant,
                  ),
                ),
            ],
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(bottom: dashed ? 10 : 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title, style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                  Text(sub, style: AppTheme.caption),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
