import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';

import 'package:rounded_loading_button_plus/rounded_loading_button.dart';
import '../../Controller/Rider_assign/rider_assign_controller.dart';
import '../../Globalwidgets/textwidget.dart';
import '../../Helper/Constants/AssetConstants.dart';
import '../../Helper/Constants/Colorconstants.dart';
import '../../Helper/Logger.dart';
import '../../Helper/toast.dart';
import '../../Helper/utility.dart';
import '../../Model/Response/Orders/Getorderresponse.dart';

class ReassignRidersView extends StatelessWidget {
  final OrderDetails deliveryDetails;

  ReassignRidersView({Key? key, required this.deliveryDetails}) : super(key: key);

  final RiderAssignController reassignRidersController = Get.put(RiderAssignController());

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      child: Scaffold(
        backgroundColor: Colors.grey[100],
        appBar: AppBar(
          leading: BackButton(color: Colors.black),
          title: TextWidget(
              text: 'Assign Rider',
              fontSize: 20,
              fontWeight: FontWeight.w700,
          ),
          backgroundColor: ColorConstants.secondaryColor,
          elevation: 2,
        ),
        body: GetBuilder<RiderAssignController>(
          initState: (_) {
            reassignRidersController.shimmer.value = true;
            reassignRidersController.getRiders(deliveryDetails.applocationid);
            logger.i('RiderDetails : ${deliveryDetails.pickupaddress}');
            logger.i('RiderDetails : ${deliveryDetails.pickupcustomer}');
            logger.i('RiderDetails : ${deliveryDetails.pickupaddress}');
            logger.i('RiderDetails : ${deliveryDetails.pickupcustomer}');
          },
          builder: (controller) {
            if (controller.shimmer.value) {
              return const Center(child: CircularProgressIndicator());
            }

            if (controller.riderDetails.isEmpty) {
              return Center(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.asset(
                      AssetConstants.NoRecords,
                      height: 160,
                      width: 160,
                    ),
                    const SizedBox(height: 12),
                    Text(
                      "No riders at this moment",
                      style: TextStyle(color: Colors.grey[600], fontSize: 18),
                    ),
                  ],
                ),
              );
            }

            return ListView.separated(
              itemCount: controller.riderDetails.length,
              padding: const EdgeInsets.all(12),
              separatorBuilder: (_, __) => const SizedBox(height: 8),
              itemBuilder: (context, index) {
                final rider = controller.riderDetails[index];
                final isSelected = controller.riderFcmToken.contains(rider.userfcmtoken);
                final status = rider.status ?? '';
                final isIdle = status.toLowerCase() == 'idle';

                return GestureDetector(
                  onTap: () {
                    if (isSelected) {
                      controller.riderFcmToken.remove(rider.userfcmtoken);
                      controller.riderUserIdList = 0;
                    } else if (rider.userfcmtoken == null || rider.userfcmtoken!.isEmpty) {
                      Toast.showToast("Rider token not available");
                    } else {
                      controller
                        ..isIdle = false
                        ..isSelectAll = false
                        ..riderFcmToken.clear()
                        ..riderFcmToken.add(rider.userfcmtoken!)
                        ..riderUserIdList = rider.userid ?? 0
                        ..partnerId = rider.partnerid ?? 0
                        ..shiftId = rider.shiftid ?? 0
                        ..riderStatus = status;
                    }

                    controller.update();
                  },
                  child: Card(
                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                    elevation: 0,
                    child: Padding(
                      padding: const EdgeInsets.all(12),
                      child: Row(
                        children: [
                          CircleAvatar(
                            radius: 26,
                            backgroundColor: Utility.getLightColors(rider.firstname?[0] ?? '').withAlpha(160),
                            child: TextWidget(
                                text: rider.firstname?[0].toUpperCase() ?? '',
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                            )
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '${rider.firstname} ${rider.lastname}',
                                  style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '+91 ${rider.contactno}',
                                  style: TextStyle(color: Colors.grey[700], fontSize: 14),
                                ),
                                const SizedBox(height: 4),
                                Chip(
                                  label: Text(
                                    status,
                                    style: TextStyle(
                                      color: isIdle ? Colors.green : Colors.green,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                  backgroundColor: isIdle
                                      ? Colors.green[50]
                                      : Colors.green[50],
                                  visualDensity: VisualDensity.compact,
                                ),
                              ],
                            ),
                          ),
                          Icon(
                            Icons.check_circle,
                            color: isSelected ? Colors.green : Colors.grey,
                            size: 28,
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
            );
          },
        ),
        bottomNavigationBar: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
          child: Row(
            children: [
              Expanded(
                child: ElevatedButton.icon(
                  onPressed: () => Navigator.pop(context),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey[600],
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30),
                    ),
                    padding: const EdgeInsets.symmetric(vertical: 14),
                  ),
                  icon: const Icon(Icons.arrow_back, size: 18),
                  label: const Text('Back'),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: RoundedLoadingButton(
                    color:  Colors.green,
                    controller: reassignRidersController.btnNotifyRiderController,
                    onPressed: () {
                      if (reassignRidersController.riderUserIdList != 0 &&
                              reassignRidersController.riderFcmToken.isNotEmpty) {
                              reassignRidersController.createDelivery([deliveryDetails]);
                          } else {
                            Toast.showToast("Please select a rider");
                            reassignRidersController.btnNotifyRiderController.reset();
                          }
                    },
                    child: TextWidget(
                        text: 'Notify',
                        fontWeight: FontWeight.w700,
                        color: ColorConstants.secondaryColor,
                    )
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
