/// Checkout Submit Button Widget
///
/// Place order or send negotiation request button.
library;

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

import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/router/app_router.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/account/domain/entities/address.dart';

/// Checkout Submit Button
///
/// Button that changes based on negotiation checkbox state.
class CheckoutSubmitButton extends StatelessWidget {
  const CheckoutSubmitButton({
    super.key,
    required this.formKey,
    required this.needsNegotiation,
    required this.needsInvoice,
    required this.selectedAddress,
    required this.paymentMethod,
    required this.total,
  });

  final GlobalKey<FormState> formKey;
  final bool needsNegotiation;
  final bool needsInvoice;
  final Address? selectedAddress;
  final String paymentMethod;
  final double total;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Column(
        children: [
          // Terms Agreement Text
          const Text(
            'Bằng việc đặt hàng, bạn đồng ý với các điều khoản và điều kiện của chúng tôi',
            style: TextStyle(fontSize: 12, color: AppColors.grey500),
            textAlign: TextAlign.center,
          ),

          const SizedBox(height: AppSpacing.md),

          // Place Order / Send Negotiation Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton(
              onPressed: () {
                // Validate address is selected
                if (selectedAddress == null) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('Vui lòng chọn địa chỉ giao hàng'),
                      backgroundColor: AppColors.danger,
                      duration: Duration(seconds: 2),
                    ),
                  );
                  return;
                }

                if (formKey.currentState?.validate() ?? false) {
                  _handlePlaceOrder(context);
                }
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: needsNegotiation
                    ? AppColors.warning
                    : AppColors.primaryBlue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(vertical: 16),
                elevation: 0,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
              ),
              child: Text(
                needsNegotiation ? 'Gửi yêu cầu đàm phán' : 'Đặt hàng',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Handle place order
  void _handlePlaceOrder(BuildContext context) {
    // TODO: Implement actual order placement with backend

    if (needsNegotiation) {
      // Show negotiation request sent message
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Yêu cầu đàm phán giá đã được gửi!'),
          backgroundColor: AppColors.success,
          duration: Duration(seconds: 2),
        ),
      );

      // Navigate back after a short delay
      Future.delayed(const Duration(milliseconds: 500), () {
        if (context.mounted) {
          context.pop();
        }
      });
    } else {
      // Generate order ID (mock - replace with actual from backend)
      final orderId =
          'DH${DateTime.now().millisecondsSinceEpoch.toString().substring(7)}';

      // Show order success message
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Đặt hàng thành công! Chuyển đến thanh toán...'),
          backgroundColor: AppColors.success,
          duration: Duration(seconds: 1),
        ),
      );

      // Navigate to payment QR page after a short delay
      Future.delayed(const Duration(milliseconds: 500), () {
        if (context.mounted) {
          context.pushNamed(
            RouteNames.paymentQr,
            queryParameters: {'orderId': orderId, 'amount': total.toString()},
          );
        }
      });
    }
  }
}
