import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:get/get.dart';
import 'package:taafee_mobile/common/const/const.dart';
import 'package:taafee_mobile/common/extensions/widget_extension.dart';
import 'package:taafee_mobile/common/widgets/button.dart';
import 'package:taafee_mobile/common/widgets/listview.dart';
import 'package:taafee_mobile/common/widgets/text.dart';
import 'package:taafee_mobile/core/routing/routing_manager.dart';
import 'package:taafee_mobile/core/utils/utils.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/image.dart';
import 'package:taafee_mobile/features/card/business_logic_layer/card_controller.dart';
import 'package:taafee_mobile/features/card/data_layer/model/appointment.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/card_details.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/card_service.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/consultation_price.dart';
import 'package:taafee_mobile/features/card/presentation_layer/widgets/wording_time.dart';
import 'package:taafee_mobile/features/chat/business%20logic%20layer/chat_controller.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../../../common/widgets/header_screen.dart';
import '../../../../common/widgets/toast.dart';
import '../../../../core/url launcher/url_launcher_service.dart';
import '../../../home/business_logic_layer/home_controller.dart';
import '../../data_layer/model/card_model.dart';
import '../widgets/appointment_details.dart';
import '../widgets/appointment_widget.dart';
import '../widgets/card_email.dart';
import '../widgets/card_header.dart';
import '../widgets/card_image.dart';
import '../widgets/card_information.dart';
import '../widgets/card_location.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart' as location;

import '../widgets/rate.dart';

class CardDetailsScreen extends StatelessWidget {
  final CardModel cardModel = Get.arguments;
  CardDetailsScreen({super.key});
  final CardController cardController = Get.find<CardController>();
  final HomeController homeController = Get.find<HomeController>();
  final ChatController chatController = Get.find<ChatController>();
  @override
  Widget build(BuildContext context) {
    cardController.updateCardNetworkImageUrls(cardModel.cardImages);
    return Scaffold(
      appBar: AppBar(
        leadingWidth: homeController.isArabic.value ? 16 : 30,
        leading: SizedBox(
          child: Obx(
            () => (!homeController.isArabic.value)
                ? SvgPicture.asset(
                    "assets/icons/arrow-left.svg",
                    width: Responsive.isTablet() ? 20 : null,
                  )
                : SvgPicture.asset(
                    "assets/icons/arrow right.svg",
                    width: Responsive.isTablet() ? 20 : null,
                  ),
          ),
        ).paddingSymmetric(horizontal: 3).onTap(
          () {
            RoutingManager.back();
          },
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        title: SizedBox(
          width: 50,
          height: 50,
          child: SvgPicture.asset("assets/icons/tafee icon.svg"),
        ),
      ),
      backgroundColor: AppColors.backGroundColor,
      body: SingleChildScrollView(
          child: Column(
        children: [
          Stack(
            alignment: Alignment.topCenter,
            children: [
              Column(
                children: [
                  Container(
                    width: Get.width,
                    height: 60,
                    decoration: BoxDecoration(
                      color: AppColors.secondaryColor,
                      borderRadius: const BorderRadius.only(
                        bottomLeft: Radius.circular(10),
                        bottomRight: Radius.circular(10),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SvgPicture.asset("assets/icons/Share.svg"),
                        Row(
                          children: [
                            const RegularTextWidget(
                              "  300  ",
                              color: Colors.white,
                            ),
                            SvgPicture.asset("assets/icons/Eye.svg"),
                          ],
                        )
                      ],
                    ).paddingSymmetric(horizontal: 20),
                  ),
                  Container(
                    alignment: Alignment.bottomCenter,
                    width: Get.width,
                    height: 120,
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(20),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            BoldTextWidget(
                              " ${cardModel.user.firstName} "
                              " ${cardModel.user.lastName} ",
                              fontSize: Responsive.isTablet() ? 22 : 14,
                              color: AppColors.textColor,
                            ),
                          ],
                        ),
                        MediumTextWidget(
                          cardModel.name,
                          fontSize: Responsive.isTablet() ? 22 : 14,
                        ),
                      ],
                    ),
                  )
                ],
              ),
              CircleAvatar(
                radius: 60,
                backgroundColor: AppColors.secondaryColor,
              ),
              const Positioned(
                top: 15,
                child: CircleAvatar(
                  radius: 50,
                  backgroundImage: AssetImage(
                    "assets/images/Ellipse 8.png",
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(
            height: 20,
          ),
          SizedBox(
            width: Get.width * .92,
            height: 75,
            child: ListViewWidget(
              physics: const BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              itemCount: 4,
              childBuilder: (index) {
                if (index == 3) {
                  return const ImageWidget(
                    numberOfImages: 5,
                  ).onTap(() {
                    RoutingManager.to(RouteName.imageView);
                  });
                }
                return const ImageWidget(numberOfImages: 1);
              },
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          ConsultationPriceWidget(
            cardModel: cardModel,
          ),
          const SizedBox(
            height: 20,
          ),
          WorkingTimeWidget(),
          const SizedBox(
            height: 20,
          ),
          RateWidget(),
          const SizedBox(
            height: 20,
          ),
          SizedBox(
            width: Get.width * .89,
            height: 150,
            // decoration: BoxDecoration(
            //   borderRadius: BorderRadius.circular(8),
            // ),
            child: FlutterMap(
              options: MapOptions(
                center: const location.LatLng(51.509364, -0.128928),
              ),
              children: [
                TileLayer(
                  urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
                  userAgentPackageName: 'com.example.app',
                ),
                // RichAttributionWidget(
                //   attributions: [
                //     TextSourceAttribution(
                //       'OpenStreetMap contributors',
                //       onTap: () => launchUrl(Uri.parse('https://openstreetmap.org/copyright')),
                //     ),
                //   ],
                // ),
              ],
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          Container(
            width: Get.width * .89,
            height: 100,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const RegularTextWidget(
                  "Information about the doctor",
                  color: Colors.grey,
                  fontSize: 14,
                ).paddingSymmetric(horizontal: 30),
                RegularTextWidget(cardModel.additionalData).paddingSymmetric(horizontal: 10, vertical: 5)
              ],
            ),
          ),
          const SizedBox(
            height: 20,
          ),
          // Row(
          //   children: [
          //     ButtonWidget(
          //       color: AppColors.callColor,
          //       haveIcon: true,
          //       onTap: () async {
          //         await UrlLauncherService.makePhoneCall(cardModel.phoneNumber);
          //       },
          //       title: "call_owner".tr,
          //       textColor: Colors.white,
          //       child: SvgPicture.asset(
          //         "assets/icons/phone.svg",
          //         colorFilter: const ColorFilter.mode(Colors.white, BlendMode.srcIn),
          //       ),
          //     ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5),
          //     ButtonWidget(
          //       color: AppColors.emailColor,
          //       haveIcon: true,
          //       onTap: () async {
          //         await UrlLauncherService.sendEmail(cardModel.user.email);
          //       },
          //       title: "email".tr,
          //       textColor: Colors.white,
          //       child: SvgPicture.asset("assets/icons/Email.svg"),
          //     ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5),
          //     if (Responsive.isTablet())
          //       Visibility(
          //         visible: chatController.chatUser.id != cardModel.user.chatUserId,
          //         child: Obx(() {
          //           return ButtonWidget(
          //             isLoading: chatController.createRoomState.loading,
          //             textColor: Colors.white,
          //             color: AppColors.messageColor,
          //             haveIcon: true,
          //             onTap: () {
          //               if (chatController.connectionState.value == SocketConnectionState.connected) {
          //                 chatController.createRoom(
          //                     chatUserId: cardModel.user.chatUserId,
          //                     onSuccess: (room) {
          //                       RoutingManager.to(RouteName.chatDetails, arguments: {
          //                         "room": room,
          //                       });
          //                     });
          //               } else {
          //                 Toast.showToast('you_have_no_internet_connection.'.tr);
          //               }
          //             },
          //             title: "start_conversation".tr,
          //             fontSize: 13,
          //             child: SvgPicture.asset("assets/icons/message.svg"),
          //           ).expanded(Responsive.isTablet() ? 1 : 5);
          //         }),
          //       ),
          //     if (Responsive.isTablet())
          //       Obx(() {
          //         return Visibility(
          //           visible: homeController.user.value!.id != cardModel.user.id,
          //           child: (homeController.currentCardAppointment.value != null)
          //               ? ButtonWidget(
          //                   haveIcon: true,
          //                   onTap: () {
          //                     appointmentDialog(context);
          //                   },
          //                   fontSize: 13,
          //                   color: AppColors.secondaryColor,
          //                   title: 'you_have_an_appointment'.tr,
          //                   child: const Icon(
          //                     Icons.schedule,
          //                     color: Colors.white,
          //                   ),
          //                 ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5)
          //               : ButtonWidget(
          //                   onTap: () {
          //                     cardController.getAvailableAppointments();
          //                     appointmentSchedulingDialog(context);
          //                   },
          //                   haveIcon: true,
          //                   fontSize: 12,
          //                   title: 'schedule_an_appointment'.tr,
          //                   color: AppColors.secondaryColor,
          //                   child: const Icon(
          //                     Icons.schedule,
          //                     color: Colors.white,
          //                   ),
          //                 ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5),
          //         );
          //       }),
          //   ],
          // ).paddingSymmetric(vertical: Responsive.isTablet() ? 20 : 4, horizontal: Responsive.isTablet() ? 40 : 10),
          // if (!Responsive.isTablet())
          //   Obx(() {
          //     return Row(
          //       children: [
          //         Obx(() {
          //           return Visibility(
          //             visible: homeController.user.value!.id != cardModel.user.id,
          //             child: (homeController.currentCardAppointment.value != null)
          //                 ? ButtonWidget(
          //                     haveIcon: true,
          //                     onTap: () {
          //                       appointmentDialog(context);
          //                     },
          //                     fontSize: 12,
          //                     color: AppColors.secondaryColor,
          //                     title: 'you_have_an_appointment'.tr,
          //                     child: const Icon(
          //                       Icons.schedule,
          //                       color: Colors.white,
          //                     ),
          //                   ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5)
          //                 : ButtonWidget(
          //                     onTap: () {
          //                       cardController.getAvailableAppointments();
          //                       appointmentSchedulingDialog(context);
          //                     },
          //                     haveIcon: true,
          //                     fontSize: 12,
          //                     title: 'schedule_an_appointment'.tr,
          //                     color: AppColors.secondaryColor,
          //                     child: const Icon(
          //                       Icons.schedule,
          //                       color: Colors.white,
          //                     ),
          //                   ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5),
          //           );
          //         }),
          //         Visibility(
          //           visible: chatController.chatUser.id != cardModel.user.chatUserId,
          //           child: ButtonWidget(
          //             isLoading: chatController.createRoomState.loading,
          //             textColor: Colors.white,
          //             color: AppColors.messageColor,
          //             haveIcon: true,
          //             onTap: () {
          //               if (chatController.connectionState.value == SocketConnectionState.connected) {
          //                 chatController.createRoom(
          //                     chatUserId: cardModel.user.chatUserId,
          //                     onSuccess: (room) {
          //                       RoutingManager.to(RouteName.chatDetails, arguments: {"room": room});
          //                     });
          //               } else {
          //                 Toast.showToast('you_have_no_internet_connection'.tr);
          //               }
          //             },
          //             title: "start_conversation".tr,
          //             fontSize: 12,
          //             child: SvgPicture.asset("assets/icons/message.svg"),
          //           ).paddingSymmetric(horizontal: 4).expanded(Responsive.isTablet() ? 1 : 5),
          //         ),
          //       ],
          //     ).paddingSymmetric(vertical: Responsive.isTablet() ? 20 : 4, horizontal: Responsive.isTablet() ? 40 : 10);
          //   }),
          // const SizedBox(
          //   height: 60,
          // ),
        ],
      ).paddingSymmetric(horizontal: Responsive.isTablet() ? 20 : 0)),
    ).makeSafeArea();
  }

  void appointmentSchedulingDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            contentPadding: EdgeInsets.zero,
            actionsPadding: EdgeInsets.zero,
            title: RegularTextWidget(
              "available_times".tr,
              fontSize: 14,
            ),
            content: Obx(() {
              if (cardController.availableAppointmentsState.loading ||
                  homeController.appointmentSchedulingState.loading) {
                return SizedBox(width: 320, height: 320, child: const CircularProgressIndicator().center());
              }
              return SizedBox(
                height: 320,
                width: 320,
                child: Column(
                  children: [
                    const SizedBox(
                      height: 20,
                    ),
                    SizedBox(
                      height: 280,
                      child: ListView.builder(
                        physics: const BouncingScrollPhysics(),
                        itemCount: 12,
                        itemBuilder: (context, index) {
                          DateTime dateTime = Utils.generateRandomDateTime();
                          return AppointmentWidget(dateTime: dateTime).paddingOnly(bottom: 16).onTap(() {
                            homeController.scheduleAnAppointment(
                                Appointment(cardId: cardModel.id, dateTime: dateTime, user: homeController.user.value!),
                                onSuccess: () {
                              Toast.showToast('appointment_scheduled_successfully.'.tr);
                              RoutingManager.back();
                            });
                          });
                        },
                      ).paddingOnly(left: 8, right: 8, top: 8, bottom: 8),
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                  ],
                ),
              );
            }),
          );
        });
  }

  void appointmentDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            contentPadding: EdgeInsets.zero,
            actionsPadding: EdgeInsets.zero,
            title: HeaderScreen(
              '   ${"appointment".tr}',
            ),
            content: AppointmentDetails(appointment: homeController.currentCardAppointment.value!),
          );
        });
  }
}
