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';

Future<void> showPaymentSheet(BuildContext context, double amount) {
  return showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: AppColors.surface,
    shape: const RoundedRectangleBorder(
      borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
    ),
    builder: (_) => _PaymentSheet(amount: amount),
  );
}

class _Method {
  final String name;
  final String? sub;
  final IconData icon;
  final Color iconColor;
  const _Method(this.name, this.icon, this.iconColor, {this.sub});
}

class _PaymentSheet extends StatefulWidget {
  final double amount;
  const _PaymentSheet({required this.amount});

  @override
  State<_PaymentSheet> createState() => _PaymentSheetState();
}

class _PaymentSheetState extends State<_PaymentSheet> {
  final _methods = const [
    _Method('UPI (GPay, PhonePe, Paytm)', Icons.account_balance, AppColors.secondary),
    _Method('Credit / Debit Cards', Icons.credit_card, AppColors.onSurface),
    _Method('Net banking', Icons.account_balance_outlined, AppColors.onSurface),
    _Method('Cash on Delivery', Icons.payments_outlined, AppColors.onSurface),
  ];
  int _selected = 0;
  bool _processing = false;

  void _pay() async {
    setState(() => _processing = true);
    final state = context.read<AppState>();
    state.draft.paymentMethod = _methods[_selected].name;
    await Future.delayed(const Duration(milliseconds: 1400));
    if (!mounted) return;
    try {
      await state.placeOrder();
      if (!mounted) return;
      Navigator.pop(context); // close sheet
      Navigator.pushNamedAndRemoveUntil(
        context,
        Routes.bookingSuccess,
        (r) => r.settings.name == Routes.home,
      );
    } catch (e) {
      if (!mounted) return;
      setState(() => _processing = false);
      SnackbarUtils.showError(context, e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const SizedBox(height: 10),
          Container(
            width: 40,
            height: 4,
            decoration: BoxDecoration(
                color: AppColors.surfaceContainerHighest,
                borderRadius: BorderRadius.circular(99)),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 18, 20, 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('Pay ₹${widget.amount.toStringAsFixed(0)}', style: AppTheme.headlineLg),
                Text('Order ID: 293810',
                    style: AppTheme.bodyMd.copyWith(color: AppColors.onSurfaceVariant)),
              ],
            ),
          ),
          ...List.generate(_methods.length, (i) {
            final m = _methods[i];
            final active = i == _selected;
            return Padding(
              padding: const EdgeInsets.fromLTRB(16, 6, 16, 6),
              child: GestureDetector(
                onTap: () => setState(() => _selected = i),
                child: Container(
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: active ? AppColors.surfaceContainer : AppColors.surface,
                    borderRadius: BorderRadius.circular(14),
                    border: Border.all(
                        color: active ? AppColors.primary : AppColors.outlineVariant),
                  ),
                  child: Row(
                    children: [
                      Container(
                        width: 44,
                        height: 44,
                        decoration: BoxDecoration(
                          color: AppColors.surfaceContainerLowest,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Icon(m.icon, color: m.iconColor, size: 22),
                      ),
                      const SizedBox(width: 14),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(m.name,
                                style: AppTheme.labelMd
                                    .copyWith(fontWeight: FontWeight.w700)),
                            if (m.sub != null)
                              Text(m.sub!,
                                  style: AppTheme.caption.copyWith(color: AppColors.primary)),
                          ],
                        ),
                      ),
                      Container(
                        width: 22,
                        height: 22,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          border: Border.all(
                              color: active ? AppColors.primary : AppColors.outline,
                              width: 2),
                          color: active ? AppColors.primary : Colors.transparent,
                        ),
                        child: active
                            ? const Icon(Icons.circle, size: 8, color: Colors.white)
                            : null,
                      ),
                    ],
                  ),
                ),
              ),
            );
          }),
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),
            child: SafeArea(
              top: false,
              child: PrimaryButton(
                label: 'Pay ₹${widget.amount.toStringAsFixed(0)}',
                loading: _processing,
                height: 54,
                onPressed: _pay,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
