import 'package:flutter/material.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';
import 'package:doormile/core/widgets/logo.dart';

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

  @override
  Widget build(BuildContext context) {
    final steps = const [
      JourneyStep(
        title: 'First Mile',
        subtitle: 'Picked up from Guindy Hub, Chennai\nAssigned to EV-Fleet #TN01-EV-4421',
        time: '7 Jun, 10:45 AM',
        icon: Icons.inventory_2,
        color: AppColors.firstMile,
        done: true,
      ),
      JourneyStep(
        title: 'Mid Mile · IN TRANSIT',
        subtitle:
            'Departed Chennai Regional Hub\nEnroute to Nelamangala Distribution Center',
        time: 'Active Now',
        icon: Icons.local_shipping,
        color: AppColors.midMile,
        active: true,
        note:
            'AI REROUTE · Avoided AH45 congestion near Krishnagiri. Diverted to optimized arterial route.',
      ),
      JourneyStep(
        title: 'Last Mile',
        subtitle: 'Out for Delivery\nTo: Indiranagar, Bengaluru Hub',
        time: 'Expected 9 Jun',
        icon: Icons.home_filled,
        color: AppColors.lastMile,
      ),
    ];

    final logs = const [
      ActivityLog('Security Check Complete', 'Chennai Regional Center · 08 Jun 14:12',
          Icons.verified_user_outlined),
      ActivityLog('Sorted for Destination', 'Chennai Regional Center · 08 Jun 11:30',
          Icons.alt_route),
      ActivityLog('Arrived at Sorting Hub', 'Chennai Hub A · 07 Jun 18:45',
          Icons.warehouse_outlined),
      ActivityLog('Shipment Created', 'Electronic City Office · 07 Jun 09:15',
          Icons.add_box_outlined),
    ];

    return Scaffold(
      backgroundColor: AppColors.surface,
      appBar: AppBar(
        leading: BackButton(color: AppColors.primary, onPressed: () => Navigator.pop(context)),
        title: const DoormileWordmark(markSize: 32, fontSize: 22),
        actions: const [
          Padding(
            padding: EdgeInsets.only(right: 16),
            child: Icon(Icons.location_on_outlined, color: AppColors.primary),
          ),
        ],
      ),
      body: ListView(
        padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
        children: [
          // Summary card
          AppCard(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Shipment Contents', style: AppTheme.caption),
                          Text('Documents & electronics · 3.2 kg',
                              style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                        ],
                      ),
                    ),
                    StatusChip(
                      label: 'EV EXPRESS',
                      icon: Icons.eco,
                      color: AppColors.tertiary,
                      bg: AppColors.tertiaryFixed.withValues(alpha: 0.6),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                Row(
                  children: [
                    _city('MAA', 'Chennai'),
                    const Expanded(
                      child: Icon(Icons.bolt, color: AppColors.primary),
                    ),
                    _city('BLR', 'Bengaluru', end: true),
                  ],
                ),
                const Divider(height: 28, color: AppColors.surfaceContainer),
                Row(
                  children: [
                    const Icon(Icons.schedule, size: 18, color: AppColors.onSurfaceVariant),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('Estimated Arrival', style: AppTheme.caption),
                          Text('9 Jun 2:30 PM',
                              style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                        ],
                      ),
                    ),
                    PrimaryButton(
                      label: 'Track Live',
                      height: 44,
                      onPressed: () => Navigator.pushNamed(context, '/tracking/live',
                          arguments: order),
                    ).constrainedTo(120),
                  ],
                ),
              ],
            ),
          ),
          const SizedBox(height: 12),
          // AI insight banner
          Container(
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: AppColors.tertiaryFixed.withValues(alpha: 0.35),
              borderRadius: BorderRadius.circular(14),
              border: Border.all(color: AppColors.tertiary.withValues(alpha: 0.15)),
            ),
            child: Row(
              children: [
                const Icon(Icons.psychology_alt, color: AppColors.tertiary),
                const SizedBox(width: 12),
                Expanded(
                  child: Text('MileTruth AI Insight · Rerouted via Hosur bypass — ETA protected despite traffic.',
                      style: AppTheme.bodyMd
                          .copyWith(color: AppColors.tertiary, height: 1.35)),
                ),
              ],
            ),
          ),
          const SizedBox(height: 24),
          Text('Journey Timeline', style: AppTheme.headlineMd),
          const SizedBox(height: 12),
          ...List.generate(steps.length, (i) =>
              _TimelineTile(step: steps[i], isLast: i == steps.length - 1)),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('Activity Log', style: AppTheme.headlineMd),
              Text('All Updates',
                  style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
            ],
          ),
          const SizedBox(height: 12),
          AppCard(
            child: Column(
              children: [
                for (int i = 0; i < logs.length; i++) ...[
                  Row(
                    children: [
                      IconBadge(
                        icon: logs[i].icon,
                        bg: AppColors.surfaceContainer,
                        color: AppColors.onSurfaceVariant,
                        size: 38,
                        iconSize: 18,
                        circle: true,
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(logs[i].title,
                                style: AppTheme.labelMd
                                    .copyWith(fontWeight: FontWeight.w700)),
                            Text(logs[i].subtitle, style: AppTheme.caption),
                          ],
                        ),
                      ),
                    ],
                  ),
                  if (i < logs.length - 1)
                    const Divider(height: 22, color: AppColors.surfaceContainer),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _city(String code, String name, {bool end = false}) {
    return Column(
      crossAxisAlignment: end ? CrossAxisAlignment.end : CrossAxisAlignment.start,
      children: [
        Text(code, style: AppTheme.headlineMd.copyWith(color: AppColors.primary)),
        Text(name, style: AppTheme.caption),
      ],
    );
  }
}

class _TimelineTile extends StatelessWidget {
  final JourneyStep step;
  final bool isLast;
  const _TimelineTile({required this.step, required this.isLast});

  @override
  Widget build(BuildContext context) {
    return IntrinsicHeight(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            children: [
              Container(
                width: 40,
                height: 40,
                decoration: BoxDecoration(
                  color: step.done || step.active
                      ? step.color.withValues(alpha: 0.15)
                      : AppColors.surfaceContainer,
                  shape: BoxShape.circle,
                  border: step.active
                      ? Border.all(color: step.color, width: 2)
                      : null,
                ),
                child: Icon(step.icon,
                    color: step.done || step.active ? step.color : AppColors.outline,
                    size: 20),
              ),
              if (!isLast)
                Expanded(
                  child: Container(
                    width: 2.5,
                    color: step.done ? step.color : AppColors.surfaceContainerHigh,
                  ),
                ),
            ],
          ),
          const SizedBox(width: 14),
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(bottom: 24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(step.title,
                            style: AppTheme.labelMd.copyWith(
                                color: step.color, fontWeight: FontWeight.w700)),
                      ),
                      Text(step.time,
                          style: AppTheme.caption.copyWith(
                              color: step.active
                                  ? AppColors.tertiary
                                  : AppColors.onSurfaceVariant,
                              fontWeight:
                                  step.active ? FontWeight.w700 : FontWeight.w400)),
                    ],
                  ),
                  const SizedBox(height: 4),
                  Text(step.subtitle,
                      style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
                  if (step.note != null) ...[
                    const SizedBox(height: 10),
                    Container(
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        color: AppColors.warning.withValues(alpha: 0.08),
                        borderRadius: BorderRadius.circular(10),
                        border: Border.all(
                            color: AppColors.warning.withValues(alpha: 0.25)),
                      ),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Icon(Icons.warning_amber_rounded,
                              size: 16, color: AppColors.warning),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Text(step.note!,
                                style: AppTheme.caption.copyWith(
                                    color: AppColors.warning, height: 1.4)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

extension on Widget {
  Widget constrainedTo(double width) =>
      ConstrainedBox(constraints: BoxConstraints(maxWidth: width), child: this);
}
