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

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<AppState>().fetchOrders();
    });
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<AppState>();
    final active = state.orders.where((o) => o.status == OrderStatus.active).firstOrNull;

    return AppBackground(
      child: Stack(
        children: [
          SingleChildScrollView(
            padding: const EdgeInsets.only(bottom: 100),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _hero(context, state),
                const SizedBox(height: 26),
                active != null ? _activeShipment(context, active) : _emptyShipment(context),
                const SizedBox(height: 18),
                _ecoBanner(),
              ],
            ),
          ),
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            child: Container(
              height: MediaQuery.of(context).padding.top,
              color: AppColors.primaryContainer,
            ),
          ),
        ],
      ),
    );
  }

  Widget _hero(BuildContext context, AppState state) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Container(
          height: 196,
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              colors: [AppColors.primaryContainer, AppColors.primary],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(24)),
          ),
          child: ClipRRect(
            borderRadius: const BorderRadius.vertical(bottom: Radius.circular(24)),
            child: AnnotatedRegion<SystemUiOverlayStyle>(
              value: SystemUiOverlayStyle.light,
              child: Stack(
                children: [
                  Positioned(
                    right: -20,
                    top: 20,
                    child: Transform.rotate(
                      angle: -0.1,
                      child: Icon(Icons.local_shipping_rounded, size: 150, color: Colors.white.withValues(alpha: 0.04)),
                    ),
                  ),
                  Positioned(
                    left: 40,
                    bottom: -30,
                    child: Transform.rotate(
                      angle: 0.15,
                      child: Icon(Icons.route_rounded, size: 100, color: Colors.white.withValues(alpha: 0.03)),
                    ),
                  ),
                  SafeArea(
                    bottom: false,
                    child: Padding(
                  padding: const EdgeInsets.fromLTRB(20, 18, 20, 0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const DoormileMark(size: 48, color: Colors.white, glyphColor: AppColors.primary),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                const Icon(Icons.location_on_rounded, color: Colors.white70, size: 15),
                                const SizedBox(width: 4),
                                Text('Bengaluru', style: AppTheme.labelMd.copyWith(color: Colors.white)),
                              ],
                            ),
                            const SizedBox(height: 4),
                            Text(
                              'Hi, ${state.firstName.isEmpty ? 'Admin' : state.firstName}',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: AppTheme.headlineMd.copyWith(color: Colors.white),
                            ),
                            Text(
                              'Let deliveries move with less friction',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: AppTheme.caption.copyWith(color: Colors.white70),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: 44,
                        height: 44,
                        decoration: BoxDecoration(
                          color: Colors.white.withValues(alpha: 0.16),
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(color: Colors.white24),
                        ),
                        child: const Icon(Icons.notifications_none_rounded, color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
          ),
          ),
        ),
        Positioned(
          left: 20,
          right: 20,
          top: 130,
          child: AppCard(
            padding: const EdgeInsets.all(18),
            radius: BorderRadius.circular(24),
            border: Border.all(color: Colors.white),
            child: Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('Send a parcel', style: AppTheme.headlineLg),
                      const SizedBox(height: 6),
                      Text(
                        'Fast pickup, live tracking, EV-first delivery.',
                        style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant),
                      ),
                      const SizedBox(height: 16),
                      SizedBox(
                        height: 44,
                        child: ElevatedButton.icon(
                          onPressed: () {
                            final draft = context.read<AppState>().draft;
                            draft.pickupAddress = 'Current Location (GPS)';
                            Navigator.pushNamed(context, Routes.bookingPickup);
                          },
                          icon: const Icon(Icons.arrow_forward_rounded, size: 18),
                          label: const Text('Book Now'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: AppColors.primary,
                            foregroundColor: Colors.white,
                            elevation: 0,
                            padding: const EdgeInsets.symmetric(horizontal: 16),
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(width: 10),
                SizedBox(
                  width: 90,
                  height: 90,
                  child: Stack(
                    alignment: Alignment.center,
                    children: [
                      const Icon(Icons.local_shipping_rounded, size: 68, color: AppColors.primary),
                      Positioned(
                        right: 0,
                        top: 0,
                        child: IconBadge(
                          icon: Icons.eco_rounded,
                          bg: AppColors.tertiaryContainer,
                          color: AppColors.tertiary,
                          size: 28,
                          iconSize: 16,
                          circle: true,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
        const SizedBox(height: 310),
      ],
    );
  }

  Widget _activeShipment(BuildContext context, Order active) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('Live Shipment', style: AppTheme.headlineSm.copyWith(fontWeight: FontWeight.w800)),
              TextButton(
                onPressed: () => Navigator.pushNamed(context, Routes.myOrders),
                style: TextButton.styleFrom(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                  minimumSize: Size.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                ),
                child: Text('View Details', style: AppTheme.labelMd.copyWith(color: AppColors.primary)),
              ),
            ],
          ),
          const SizedBox(height: 14),
          GestureDetector(
            onTap: () => Navigator.pushNamed(context, Routes.liveTracking, arguments: active),
            child: Container(
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [AppColors.primary, AppColors.secondary],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(24),
                boxShadow: [
                  BoxShadow(color: AppColors.primary.withValues(alpha: 0.3), blurRadius: 24, offset: const Offset(0, 10)),
                ],
              ),
              padding: const EdgeInsets.all(2), // Gradient border width
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(22),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    children: [
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Container(
                            padding: const EdgeInsets.all(12),
                            decoration: BoxDecoration(
                              color: AppColors.primaryFixed,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: const Icon(Icons.inventory_2_rounded, color: AppColors.primary, size: 28),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Row(
                                  children: [
                                    Container(
                                      width: 8,
                                      height: 8,
                                      decoration: const BoxDecoration(
                                        color: AppColors.primary,
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    const SizedBox(width: 6),
                                    Text('PENDING PICKUP', style: AppTheme.caption.copyWith(color: AppColors.primary, fontWeight: FontWeight.w800, letterSpacing: 1.2)),
                                  ],
                                ),
                                const SizedBox(height: 4),
                                Text(active.id, style: AppTheme.headlineSm),
                              ],
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                            decoration: BoxDecoration(
                              color: AppColors.surfaceContainerLowest,
                              borderRadius: BorderRadius.circular(999),
                              border: Border.all(color: AppColors.outlineVariant),
                            ),
                            child: const Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text('Live', style: TextStyle(color: AppColors.onSurface, fontWeight: FontWeight.w600, fontSize: 12)),
                                SizedBox(width: 4),
                                Icon(Icons.arrow_forward_ios_rounded, size: 10, color: AppColors.onSurfaceVariant),
                              ],
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 24),
                      Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: AppColors.surfaceContainerLowest,
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(color: AppColors.surfaceContainerHigh),
                        ),
                        child: Row(
                          children: [
                            const Column(
                              children: [
                                Icon(Icons.my_location_rounded, size: 20, color: AppColors.primary),
                                SizedBox(height: 4),
                                SizedBox(
                                  height: 24,
                                  child: VerticalDivider(color: AppColors.outlineVariant, thickness: 2),
                                ),
                                SizedBox(height: 4),
                                Icon(Icons.pin_drop_rounded, size: 20, color: AppColors.tertiary),
                              ],
                            ),
                            const SizedBox(width: 16),
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text('Pickup Location', style: AppTheme.caption),
                                  Text(active.fromLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppTheme.labelMd),
                                  const SizedBox(height: 20),
                                  Text('Destination', style: AppTheme.caption),
                                  Text(active.toLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppTheme.labelMd),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _trackNode(String title, String subtitle, bool active) {
    return Expanded(
      child: Column(
        children: [
          Text(title,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: AppTheme.caption.copyWith(
                color: active ? AppColors.secondary : AppColors.onSurfaceVariant,
                fontWeight: FontWeight.w700,
              )),
          const SizedBox(height: 2),
          Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: AppTheme.caption),
        ],
      ),
    );
  }

  Widget _emptyShipment(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SectionHeader(title: 'Active Shipment'),
          const SizedBox(height: 12),
          AppCard(
            padding: const EdgeInsets.symmetric(vertical: 24, horizontal: 18),
            child: Column(
              children: [
                Container(
                  width: 80,
                  height: 80,
                  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: 20,
                        spreadRadius: 2,
                        offset: const Offset(0, 8),
                      ),
                    ],
                  ),
                  child: Center(
                    child: Container(
                      width: 54,
                      height: 54,
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.inbox_rounded,
                        size: 28,
                        color: AppColors.primary,
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 14),
                Text('No active shipments', style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w800)),
                const SizedBox(height: 4),
                Text(
                  'You do not have any deliveries in progress right now.',
                  textAlign: TextAlign.center,
                  style: AppTheme.caption,
                ),
                const SizedBox(height: 16),
                SecondaryButton(
                  label: 'Book a Shipment',
                  onPressed: () {
                    final draft = context.read<AppState>().draft;
                    draft.pickupAddress = 'Current Location (GPS)';
                    Navigator.pushNamed(context, Routes.bookingPickup);
                  },
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _ecoBanner() {
    return const Padding(
      padding: EdgeInsets.symmetric(horizontal: 20),
      child: EcoBanner(text: 'This delivery offsets 1.2kg of CO2 emissions.'),
    );
  }

}
