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:intl/intl.dart'; // Import this for formatting
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';

class RatePassenger extends StatelessWidget {
  final RateController controller = Get.put(RateController());

  // Format: 1,234.5
  final NumberFormat currencyFormatter = NumberFormat("#,##0.0", "en_US");

  RatePassenger({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).scaffoldBackgroundColor,
      appBar: AppBar(
        title: Text('Trip Completed'.tr),
        centerTitle: true,
        automaticallyImplyLeading: false,
        elevation: 0,
      ),
      body: GetBuilder<RateController>(
        builder: (controller) {
          return SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(20.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  // 1. The HERO Section: Big Price Display
                  _buildHeroPriceDisplay(context),

                  const SizedBox(height: 24),

                  // 2. Wallet Section (Conditional)
                  if (controller.walletChecked != 'true')
                    _buildWalletSection(context, controller),

                  const SizedBox(height: 24),

                  // 3. Rating Section
                  _buildRatingSection(context, controller),

                  const SizedBox(height: 30),

                  // 4. Submit Button
                  SizedBox(
                    height: 55,
                    child: MyElevatedButton(
                      title: 'Finish & Submit'.tr,
                      onPressed: () => controller.addRateToPassenger(),
                      // isFullWidth: true,
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // --- WIDGETS ---

  Widget _buildHeroPriceDisplay(BuildContext context) {
    final MapDriverController mapController = Get.find<MapDriverController>();

    // Parse the string to double to format it correctly
    double amount =
        double.tryParse(mapController.paymentAmount.toString()) ?? 0.0;
    String formattedAmount = currencyFormatter.format(amount);

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20),
      decoration: BoxDecoration(
        color: AppColor.primaryColor, // Use your brand color or a dark color
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: AppColor.primaryColor.withOpacity(0.3),
            blurRadius: 15,
            offset: const Offset(0, 10),
          ),
        ],
      ),
      child: Column(
        children: [
          Text(
            'Collect Cash'.tr.toUpperCase(),
            style: const TextStyle(
              color: Colors.white70,
              fontSize: 16,
              fontWeight: FontWeight.w600,
              letterSpacing: 1.2,
            ),
          ),
          const SizedBox(height: 10),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Currency Symbol (Small)
              Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: Text(
                  'SYP'.tr, // Replace with your local currency symbol if needed
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.8),
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              const SizedBox(width: 4),
              // The Price (Huge)
              Text(
                formattedAmount,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 56, // Very Large Font
                  fontWeight: FontWeight.w900,
                  height: 1.0,
                ),
              ),
            ],
          ),
          const SizedBox(height: 10),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.2),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              'Passenger: ${mapController.passengerName}',
              style: const TextStyle(color: Colors.white, fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWalletSection(BuildContext context, RateController controller) {
    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: Theme.of(context).dividerColor),
      ),
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: AnimatedSwitcher(
          duration: const Duration(milliseconds: 300),
          child: controller.ispassengerWantWalletFromDriver
              ? _buildAmountInput(context, controller)
              : _buildWalletQuery(context, controller),
        ),
      ),
    );
  }

  Widget _buildWalletQuery(BuildContext context, RateController controller) {
    return Column(
      key: const ValueKey('walletQuery'),
      children: [
        Row(
          children: [
            Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                color: Colors.amber.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child:
                  const Icon(Icons.account_balance_wallet, color: Colors.amber),
            ),
            const SizedBox(width: 15),
            Expanded(
              child: Text(
                "Pay remaining to Wallet?".tr,
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ),
        const SizedBox(height: 20),
        Row(
          children: [
            Expanded(
              child: OutlinedButton(
                onPressed: () {}, // Optional logic
                style: OutlinedButton.styleFrom(
                  foregroundColor: Theme.of(context).hintColor,
                  side: BorderSide(color: Theme.of(context).dividerColor),
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                ),
                child: Text('No'.tr),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: ElevatedButton(
                onPressed: () => controller.passengerWantPay(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.primaryColor,
                  padding: const EdgeInsets.symmetric(vertical: 12),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10)),
                ),
                child: Text('Yes, Pay'.tr,
                    style: const TextStyle(color: Colors.white)),
              ),
            ),
          ],
        )
      ],
    );
  }

  Widget _buildAmountInput(BuildContext context, RateController controller) {
    return Column(
      key: const ValueKey('amountInput'),
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "Enter Amount Paid".tr,
          style: Theme.of(context)
              .textTheme
              .titleMedium
              ?.copyWith(fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 12),
        Form(
          key: controller.formKey,
          child: MyTextForm(
            controller: controller.passengerPayAmount,
            label: "Amount".tr,
            hint: "0.00",
            type: const TextInputType.numberWithOptions(decimal: true),
            // Suggestion: Add a suffix icon for currency if available in your widget
          ),
        ),
        const SizedBox(height: 12),
        SizedBox(
          width: double.infinity,
          child: ElevatedButton(
            onPressed: () => controller.addPassengerWallet(),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.green,
              shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10)),
            ),
            child: Text("Confirm Payment".tr,
                style: const TextStyle(color: Colors.white)),
          ),
        )
      ],
    );
  }

  Widget _buildRatingSection(BuildContext context, RateController controller) {
    return Column(
      children: [
        Text(
          'Rate Passenger'.tr,
          style: TextStyle(
            color: Theme.of(context).hintColor,
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        ),

        const SizedBox(height: 12),
        RatingBar.builder(
          initialRating: 0,
          minRating: 1,
          direction: Axis.horizontal,
          allowHalfRating: false,
          itemCount: 5,
          itemSize: 45, // Large stars
          itemPadding: const EdgeInsets.symmetric(horizontal: 2.0),
          itemBuilder: (context, _) => const Icon(
            Icons.star_rounded,
            color: Colors.amber,
          ),
          onRatingUpdate: (rating) {
            controller.selectRateItem(rating);
          },
        ),
        const SizedBox(height: 20),
        // Simplified comment box
        TextField(
          controller: controller.comment,
          maxLines: 2,
          style: Theme.of(context).textTheme.bodyLarge,
          decoration: InputDecoration(
            hintText: 'Any comments about the passenger?'.tr,
            filled: true,
            fillColor: Theme.of(context).cardColor,
            contentPadding:
                const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Theme.of(context).dividerColor),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Theme.of(context).dividerColor),
            ),
          ),
        ),
      ],
    );
  }
}
