import 'package:sefer_driver/controller/home/captin/map_driver_controller.dart';
import 'package:sefer_driver/views/widgets/my_textField.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:get/get.dart';
import 'package:sefer_driver/constant/colors.dart';
import 'package:sefer_driver/views/widgets/elevated_btn.dart';

import '../../constant/style.dart';
import '../../controller/rate/rate_conroller.dart';

// Changed: تم إعادة بناء الصفحة بالكامل لتحسين التصميم وتجربة المستخدم
class RatePassenger extends StatelessWidget {
  final RateController controller = Get.put(RateController());

  RatePassenger({super.key});

  @override
  Widget build(BuildContext context) {
    // New: استخدام Scaffold القياسي لهيكل أكثر قوة ومرونة
    return Scaffold(
      appBar: AppBar(
        title: Text('Rate Passenger'.tr),
        centerTitle: true,
        automaticallyImplyLeading: false, // New: إزالة سهم الرجوع
        backgroundColor: Colors.white,
        elevation: 1,
      ),
      // New: استخدام GetBuilder على مستوى الجسم لضمان تحديث الواجهة
      body: GetBuilder<RateController>(
        builder: (controller) {
          // New: استخدام SingleChildScrollView لتجنب مشاكل الـ overflow عند ظهور لوحة المفاتيح
          return SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // New: استدعاء ودجت منفصلة لكل قسم لزيادة التنظيم
                  _buildPriceSummaryCard(context, controller),
                  const SizedBox(height: 16),

                  // New: قسم المحفظة يظهر فقط إذا لم يتم التحقق منه
                  if (controller.walletChecked != 'true')
                    _buildWalletSection(context, controller),

                  const SizedBox(height: 16),

                  _buildRatingSection(context, controller),

                  const SizedBox(height: 24),

                  MyElevatedButton(
                    title: 'Submit rating'.tr,
                    onPressed: () => controller.addRateToPassenger(),
                    // New: جعل الزر يأخذ العرض الكامل لمزيد من الوضوح
                    // isFullWidth: true,
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // New: ودجت منفصلة لعرض بطاقة ملخص السعر
  Widget _buildPriceSummaryCard(
      BuildContext context, RateController controller) {
    final MapDriverController mapController = Get.find<MapDriverController>();
    final double originalPrice =
        double.tryParse(controller.price.toString()) ?? 0.0;
    final double priceAfterDiscount = originalPrice - (originalPrice * 0.12);

    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text(
              '${'Trip Summary with'.tr} ${mapController.passengerName}',
              style: AppStyle.title
                  .copyWith(fontSize: 18, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            const Divider(height: 24, thickness: 1),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('Original Fare'.tr, style: AppStyle.title),
                Text(
                  priceAfterDiscount.toStringAsFixed(2),
                  style: AppStyle.number.copyWith(
                    fontSize: 16,
                    color: AppColor.redColor,
                    decoration: TextDecoration.lineThrough,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('Your Earnings'.tr,
                    style:
                        AppStyle.title.copyWith(fontWeight: FontWeight.bold)),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: AppColor.greenColor.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: AppColor.greenColor),
                  ),
                  child: Text(
                    mapController.paymentAmount,
                    style: AppStyle.number
                        .copyWith(color: AppColor.greenColor, fontSize: 20),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Text(
              'Exclusive offers and discounts always with the Sefer app'.tr,
              textAlign: TextAlign.center,
              style: AppStyle.title
                  .copyWith(color: AppColor.redColor, fontSize: 13),
            )
          ],
        ),
      ),
    );
  }

  // New: ودجت منفصلة لقسم الدفع عبر المحفظة
  Widget _buildWalletSection(BuildContext context, RateController controller) {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          child: controller.ispassengerWantWalletFromDriver
              ? _buildAmountInput(controller)
              : _buildWalletQuery(controller),
        ),
      ),
    );
  }

  // New: واجهة سؤال استخدام المحفظة
  Widget _buildWalletQuery(RateController controller) {
    return Column(
      key: const ValueKey('walletQuery'),
      children: [
        Text(
          "Would the passenger like to settle the remaining fare using their wallet?"
              .tr,
          style: AppStyle.title,
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: MyElevatedButton(
                title: 'No'.tr,
                onPressed: () {
                  // يمكنك هنا تحديد ما يحدث عند الضغط على "لا"
                  // حاليًا، ستبقى الواجهة كما هي أو يمكنك إخفاؤها
                },
                kolor: AppColor.redColor,
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: MyElevatedButton(
                title: 'Yes, Pay'.tr,
                onPressed: () {
                  controller.passengerWantPay();
                },
              ),
            ),
          ],
        )
      ],
    );
  }

  // New: واجهة إدخال المبلغ المدفوع
  Widget _buildAmountInput(RateController controller) {
    return Column(
      key: const ValueKey('amountInput'),
      children: [
        Text(
          "How much Passenger pay?".tr,
          style: AppStyle.title,
        ),
        const SizedBox(height: 12),
        Form(
          key: controller.formKey,
          child: MyTextForm(
            controller: controller.passengerPayAmount,
            label: "Passenger paid amount".tr,
            hint: "0.00",
            type: const TextInputType.numberWithOptions(decimal: true),
          ),
        ),
        const SizedBox(height: 12),
        MyElevatedButton(
          title: "Add to Passenger Wallet".tr,
          // isFullWidth: true,
          onPressed: () {
            controller.addPassengerWallet();
          },
        )
      ],
    );
  }

  // New: ودجت منفصلة لقسم التقييم وكتابة الملاحظات
  Widget _buildRatingSection(BuildContext context, RateController controller) {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            Text('How was the passenger?'.tr,
                style: AppStyle.title
                    .copyWith(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 20),
            RatingBar.builder(
              initialRating: 0,
              itemCount: 5,
              itemSize: 40,
              itemPadding: const EdgeInsets.symmetric(horizontal: 4),
              itemBuilder: (context, index) {
                switch (index) {
                  case 0:
                    return const Icon(Icons.sentiment_very_dissatisfied,
                        color: Colors.red);
                  case 1:
                    return const Icon(Icons.sentiment_dissatisfied,
                        color: Colors.redAccent);
                  case 2:
                    return const Icon(Icons.sentiment_neutral,
                        color: Colors.amber);
                  case 3:
                    return const Icon(Icons.sentiment_satisfied,
                        color: Colors.lightGreen);
                  case 4:
                    return const Icon(Icons.sentiment_very_satisfied,
                        color: Colors.green);
                  default:
                    return const Icon(Icons.sentiment_neutral,
                        color: Colors.amber);
                }
              },
              onRatingUpdate: (rating) {
                controller.selectRateItem(rating);
              },
            ),
            const SizedBox(height: 24),
            TextFormField(
              maxLines: 4,
              minLines: 2,
              keyboardType: TextInputType.multiline,
              controller: controller.comment,
              decoration: InputDecoration(
                labelText: 'Add a comment (optional)'.tr,
                hintText: 'Type something...'.tr,
                prefixIcon: const Icon(Icons.rate_review_outlined),
                border: const OutlineInputBorder(
                  borderRadius: BorderRadius.all(Radius.circular(12)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// New: إضافة isFullWidth إلى MyElevatedButton لتسهيل التحكم في العرض
// تأكد من تحديث ملف elevated_btn.dart بهذا التغيير
/*
class MyElevatedButton extends StatelessWidget {
  final String title;
  final VoidCallback onPressed;
  final Color? kolor;
  final bool isFullWidth; // New property

  const MyElevatedButton({
    Key? key,
    required this.title,
    required this.onPressed,
    this.kolor,
    this.isFullWidth = false, // Default value
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: isFullWidth ? double.infinity : null, // Apply width
      height: 50, // Standard height
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: kolor ?? AppColor.primaryColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          textStyle: AppStyle.title.copyWith(color: Colors.white),
        ),
        child: Text(title, style: const TextStyle(color: Colors.white)),
      ),
    );
  }
}
*/
