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

import 'package:doormile/main.dart';
import 'package:doormile/shared/state/app_state.dart';
import 'package:doormile/core/utils/snackbar_utils.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/features/booking/screens/booking_scaffold.dart';
import 'package:doormile/features/booking/screens/payment_sheet.dart';

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

  @override
  State<BookingPreviewScreen> createState() => _BookingPreviewScreenState();
}

class _BookingPreviewScreenState extends State<BookingPreviewScreen> {
  bool _loading = false;
  
  void _confirmOrder() async {
    setState(() => _loading = true);
    try {
      await context.read<AppState>().placeOrder();
      if (!mounted) return;
      setState(() => _loading = false);
      Navigator.pushNamedAndRemoveUntil(context, Routes.bookingSuccess, ModalRoute.withName(Routes.home));
    } catch (e) {
      if (!mounted) return;
      setState(() => _loading = false);
      SnackbarUtils.showError(context, e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    final state = context.watch<AppState>();
    final draft = state.draft;

    return BookingScaffold(
      title: 'Review Booking',
      step: 4,
      stepLabel: 'Step 4: Review',
      buttonLabel: 'Confirm booking',
      loading: _loading,
      enabled: !_loading,
      onContinue: _confirmOrder,
      children: [
        Center(
          child: Column(
            children: [
              StatusChip(
                label: 'Step 4 of 4',
                color: AppColors.primary,
                bg: AppColors.primaryFixed.withValues(alpha: 0.5),
              ),
              const SizedBox(height: 10),
              Text('Review Booking', style: AppTheme.headlineLg),
              const SizedBox(height: 4),
              Text('Please verify your delivery details before confirming payment.',
                  textAlign: TextAlign.center,
                  style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
            ],
          ),
        ),
        const SizedBox(height: 20),
        // Pickup location
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  const Icon(Icons.gps_fixed, size: 18, color: AppColors.primary),
                  const SizedBox(width: 8),
                  Expanded(child: Text('Pickup Location', style: AppTheme.labelMd)),
                  SecondaryButton(
                    label: 'Change',
                    onPressed: () => Navigator.popUntil(
                        context, (r) => r.settings.name == Routes.bookingPickup),
                  ),
                ],
              ),
              const SizedBox(height: 10),
              Text(draft.pickupAddress,
                  style: AppTheme.headlineSm.copyWith(fontWeight: FontWeight.w700)),
              Text(draft.dropPincode.isNotEmpty
                  ? 'Drop details will be collected by Miler at Pincode: ${draft.dropPincode}'
                  : 'Drop details will be collected by Miler',
                  style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
            ],
          ),
        ),
        const SizedBox(height: 12),
        Row(
          children: [
            Expanded(
              child: _MiniCard(
                icon: Icons.inventory_2,
                title: 'Category',
                value: draft.parcelType,
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: _MiniCard(
                icon: Icons.speed,
                title: 'Service',
                value: draft.service,
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        AppCard(
          border: Border.all(color: AppColors.outlineVariant),
          child: Row(
            children: [
              const IconBadge(
                icon: Icons.local_shipping,
                bg: AppColors.primary,
                color: Colors.white,
              ),
              const SizedBox(width: 14),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('Doormile Collection',
                        style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
                    Text('Assigned optimal vehicle size', style: AppTheme.caption),
                  ],
                ),
              ),
              StatusChip(
                label: 'EV First',
                icon: Icons.eco,
                color: AppColors.tertiary,
                bg: AppColors.tertiaryFixed.withValues(alpha: 0.5),
              ),
            ],
          ),
        ),
        const SizedBox(height: 12),
        // Fare summary
        AppCard(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('Estimated Price Range', style: AppTheme.headlineSm),
              const SizedBox(height: 14),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Flexible(
                    child: Text('Final price determined at pickup',
                        style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant), overflow: TextOverflow.ellipsis),
                  ),
                  const SizedBox(width: 12),
                  Text('₹${draft.minPrice.toInt()} - ₹${draft.maxPrice.toInt()}',
                      style: AppTheme.headlineMd.copyWith(color: AppColors.primary)),
                ],
              ),
            ],
          ),
        ),

        const SizedBox(height: 12),
        Center(
          child: Text('Taxes and fees are included in the total price.',
              style: AppTheme.caption),
        ),
      ],
    );
  }

  Widget _fareRow(String label, String value) => Padding(
        padding: const EdgeInsets.symmetric(vertical: 5),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible(
              child: Text(label,
                  style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant),
                  overflow: TextOverflow.ellipsis),
            ),
            const SizedBox(width: 12),
            Text(value, style: AppTheme.labelMd),
          ],
        ),
      );
}

class _MiniCard extends StatelessWidget {
  final IconData icon;
  final String title;
  final String value;
  final String? subtitle;
  final List<String>? chips;
  const _MiniCard({
    required this.icon,
    required this.title,
    required this.value,
    this.subtitle,
    this.chips,
  });

  @override
  Widget build(BuildContext context) {
    return AppCard(
      padding: const EdgeInsets.all(14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          IconBadge(
            icon: icon,
            bg: AppColors.surfaceContainer,
            color: AppColors.primary,
            size: 34,
            iconSize: 18,
          ),
          const SizedBox(height: 10),
          Text(title, style: AppTheme.caption),
          Text(value, style: AppTheme.labelMd.copyWith(fontWeight: FontWeight.w700)),
          if (subtitle != null)
            Text(subtitle!, style: AppTheme.caption.copyWith(color: AppColors.onSurfaceVariant)),
          if (chips != null) ...[
            const SizedBox(height: 6),
            Wrap(
              spacing: 6,
              runSpacing: 6,
              children: chips!
                  .map((c) => Align(
                        alignment: Alignment.centerLeft,
                        child: FittedBox(
                          fit: BoxFit.scaleDown,
                          child: StatusChip(
                            label: c,
                            color: AppColors.secondary,
                            bg: AppColors.secondaryFixed,
                          ),
                        ),
                      ))
                  .toList(),
            ),
          ],
        ],
      ),
    );
  }
}
