import 'package:siro_rider/constant/currency.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:siro_rider/constant/box_name.dart';
import 'package:siro_rider/constant/style.dart';
import 'package:siro_rider/views/home/my_wallet/passenger_wallet.dart';

import '../../../constant/colors.dart';
import '../../../constant/info.dart';
import '../../../controller/home/map/ride_lifecycle_controller.dart';
import '../../../controller/payment/payment_controller.dart';
import '../../../main.dart';
import '../../widgets/elevated_btn.dart';

class CashConfirmPageShown extends StatelessWidget {
  CashConfirmPageShown({super.key});
  final PaymentController paymentController = Get.put(PaymentController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<RideLifecycleController>(builder: (controller) {
      // شرط الإظهار الرئيسي لم يتغير
      return Positioned(
        bottom: 0,
        left: 0,
        right: 0,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
          // التحكم في ظهور اللوحة لم يتغير
          transform: Matrix4.translationValues(
              0, controller.isCashConfirmPageShown ? 0 : Get.height, 0),
          decoration: BoxDecoration(
            color: AppColor.secondaryColor,
            borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(24),
              topRight: Radius.circular(24),
            ),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.2),
                blurRadius: 20,
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // --- 1. رأس الصفحة ---
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'Payment Method'.tr,
                      style: AppStyle.headTitle.copyWith(fontSize: 24),
                    ),
                    // زر الإغلاق (كان معلقاً في الكود القديم، تم تفعيله هنا)
                    IconButton(
                      onPressed: () => controller.changeCashConfirmPageShown(),
                      icon: Icon(Icons.close, color: AppColor.writeColor),
                    ),
                  ],
                ),
                const SizedBox(height: 16),

                // --- 2. بطاقات اختيار الدفع ---
                GetBuilder<PaymentController>(builder: (paymentCtrl) {
                  // نفس منطق تغيير اللون للسيارات النسائية
                  final bool isLadyRide = box.read(BoxName.carType) == 'Lady' ||
                      box.read(BoxName.carType) == 'Pink Bike';
                  final Color selectedColor =
                      isLadyRide ? Colors.pink.shade300 : AppColor.primaryColor;

                  return Column(
                    children: [
                      // بطاقة المحفظة
                      _buildPaymentOptionCard(
                        icon: Icons.account_balance_wallet_outlined,
                        title: '${AppInformation.appName} Balance'.tr,
                        subtitle:
                            '${'Balance:'.tr} ${box.read(BoxName.passengerWalletTotal) ?? '0.0'} ${CurrencyHelper.currency}',
                        isSelected: paymentCtrl.isWalletChecked,
                        selectedColor: selectedColor,
                        onTap: () =>
                            paymentCtrl.onChangedPaymentMethodWallet(true),
                      ),
                      const SizedBox(height: 12),
                      // بطاقة الكاش
                      _buildPaymentOptionCard(
                        icon: Icons.money_rounded,
                        title: 'Cash'.tr,
                        subtitle: 'Pay directly to the captain'.tr,
                        isSelected: paymentCtrl.isCashChecked,
                        selectedColor: selectedColor,
                        onTap: () =>
                            paymentCtrl.onChangedPaymentMethodCash(true),
                      ),
                    ],
                  );
                }),
                const SizedBox(height: 24),

                // --- 3. أزرار التأكيد (بنفس منطقك القديم تماماً) ---
                GetBuilder<PaymentController>(builder: (paymentCtrl) {
                  final bool isWalletSufficient = (double.tryParse(
                              box.read(BoxName.passengerWalletTotal) ?? '0') ??
                          0) >=
                      double.parse(controller.totalPassenger.toString());

                  // إذا تم اختيار المحفظة والرصيد غير كافٍ
                  if (paymentCtrl.isWalletChecked && !isWalletSufficient) {
                    return Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        MyElevatedButton(
                          title: 'Top up Balance to continue'.tr,
                          onPressed: () =>
                              Get.to(() => const PassengerWallet()),
                          kolor: AppColor.redColor,
                        ),
                        const SizedBox(height: 8),
                        TextButton(
                          onPressed: () =>
                              paymentCtrl.onChangedPaymentMethodCash(true),
                          child: Text("Or pay with Cash instead".tr,
                              style: TextStyle(color: AppColor.primaryColor)),
                        )
                      ],
                    );
                  }
                  // في كل الحالات الأخرى (كاش، أو محفظة برصيد كافٍ)
                  else {
                    return MyElevatedButton(
                      title: 'Confirm & Find a Ride'.tr,
                      onPressed: () {
                        // --- نفس منطقك القديم بالضبط ---
                        controller.changeCashConfirmPageShown();
                        // controller.isSearchingWindow = true;
                        controller.startSearchingForDriver();
                        // controller.update();
                      },
                    );
                  }
                }),
              ],
            ),
          ),
        ),
      );
    });
  }

  // --- ويدجت مساعدة لبناء بطاقة الدفع ---
  Widget _buildPaymentOptionCard({
    required IconData icon,
    required String title,
    required String subtitle,
    required bool isSelected,
    required VoidCallback onTap,
    required Color selectedColor,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: AnimatedContainer(
        duration: const Duration(milliseconds: 250),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: isSelected
              ? selectedColor.withOpacity(0.1)
              : AppColor.writeColor.withOpacity(0.05),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: isSelected
                ? selectedColor
                : AppColor.writeColor.withOpacity(0.2),
            width: isSelected ? 2.0 : 1.0,
          ),
        ),
        child: Row(
          children: [
            Icon(icon,
                color: isSelected ? selectedColor : AppColor.writeColor,
                size: 28),
            const SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(title,
                      style:
                          AppStyle.title.copyWith(fontWeight: FontWeight.bold)),
                  Text(subtitle,
                      style: AppStyle.subtitle.copyWith(
                          color: AppColor.writeColor.withOpacity(0.7))),
                ],
              ),
            ),
            if (isSelected)
              Icon(Icons.check_circle_rounded, color: selectedColor, size: 24),
          ],
        ),
      ),
    );
  }
}
