import 'dart:developer';
import 'package:customer/models/section_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../controllers/service_list_controller.dart';
import '../../themes/app_them_data.dart';
import '../../utils/network_image_widget.dart';

class ServiceListScreen extends StatelessWidget {
  const ServiceListScreen({super.key});

  @override
  Widget build(BuildContext context) {
    // final themeController = Get.find<ThemeController>();
    return GetX(
      init: ServiceListController(),
      builder: (controller) {
        return Scaffold(
          backgroundColor: AppThemeData.cardColor,
          appBar: AppBar(
            elevation: 0,
            automaticallyImplyLeading: false,
            titleSpacing: 20,
            centerTitle: false,
            backgroundColor: AppThemeData.cardColor,
            title: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Image.asset(
                  "assets/images/fondex_logo.png",
                  height: 32.r,
                  width: 124.r,
                  fit: BoxFit.contain,
                ),
              ],
            ),
          ),
          body:
              controller.isLoading.value
                  ? const Center(child: CircularProgressIndicator())
                  : SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // controller.serviceListBanner.isEmpty
                        //     ? SizedBox()
                        //     : Padding(
                        //       padding: EdgeInsets.symmetric(horizontal: 16.r),
                        //       child: BannerView(
                        //         bannerList: controller.serviceListBanner,
                        //       ),
                        //     ),
                        SizedBox(height: 10.h),
                        // Main Cards Section
                        _mainCardsSection(
                          context: context,
                          controller: controller,
                          sectionModel: controller.sectionList,
                        ),

                        SizedBox(height: 15.h),

                        // Other Services Section Title
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.r),
                          child: Text(
                            "Другие услуги",
                            style: TextStyle(
                              fontFamily: AppThemeData.bold,
                              fontWeight: FontWeight.w700,
                              fontSize: 20.sp,
                              color: AppThemeData.darkGrey,
                            ),
                          ),
                        ),

                        SizedBox(height: 10.h),

                        // Other Services Section
                        _otherServicesCardMaker(
                          image: "assets/images/garderob_img.png",
                          title: "Обновить гардероб",
                          subtitle: "Доставляем безопасно",
                        ),
                        _otherServicesCardMaker(
                          image: "assets/images/keys_img.png",
                          title: "Аренда",
                          subtitle: "Огромный выбор объявлений!",
                        ),
                        _otherServicesCardMaker(
                          image: "assets/images/cosmetics_img.png",
                          title: "Косметика",
                          subtitle: "Более 1000 товаров",
                        ),
                        _otherServicesCardMaker(
                          image: "assets/images/products_img.png",
                          title: "Продукты питания",
                          subtitle: "Более 1000 товаров",
                        ),

                        SizedBox(height: 45.h),
                      ],
                    ),
                  ),
        );
      },
    );
  }

  Widget _otherServicesCardMaker({
    required String image,
    required String title,
    required String subtitle,
  }) {
    return InkWell(
      onTap: () {
        log("Other Service Card Tapped: $title");
      },
      child: Container(
        width: double.infinity,
        margin: EdgeInsets.symmetric(horizontal: 16.r).copyWith(bottom: 10.r),
        padding: EdgeInsets.only(left: 6.r, right: 12.r, top: 6.r, bottom: 6.r),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16.r),
          color: AppThemeData.grey50,
        ),
        child: Row(
          spacing: 15.r,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Row(
                spacing: 10.r,
                children: [
                  Container(
                    height: 52.r,
                    width: 52.r,
                    decoration: BoxDecoration(
                      color: AppThemeData.cardColor,
                      borderRadius: BorderRadius.circular(14.r),
                    ),
                    child: Image.asset(
                      image,
                      height: 62.r,
                      width: 62.r,
                      fit: BoxFit.contain,
                    ),
                  ),
                  Expanded(
                    child: Column(
                      spacing: 2.r,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          title,
                          style: TextStyle(
                            overflow: TextOverflow.ellipsis,
                            fontFamily: AppThemeData.semiBold,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w700,
                            color: AppThemeData.darkGrey,
                          ),
                        ),
                        Text(
                          subtitle,
                          style: TextStyle(
                            overflow: TextOverflow.ellipsis,
                            fontFamily: AppThemeData.semiBold,
                            fontSize: 13.sp,
                            fontWeight: FontWeight.w400,
                            color: AppThemeData.darkGrey,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 18.r,
              color: AppThemeData.darkGrey,
            ),
          ],
        ),
      ),
    );
  }

  Widget _mainCardsSection({
    required BuildContext context,
    required ServiceListController controller,
    required RxList<SectionModel> sectionModel,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.r, horizontal: 16.r),
      decoration: BoxDecoration(
        color: AppThemeData.grey50,
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Row(
        spacing: 12.r,
        children: [
          // Food & Garderobe Cards
          Column(
            spacing: 12.r,
            children: [
              _mainCardsMaker(
                title: "Еда и доставка",
                image: "assets/images/food_img.png",
                // onTap: () {
                //   log("Main Card Tapped");
                onTap: () async {
                  SectionModel? innerSectionModel = sectionModel
                      .firstWhereOrNull(
                        (element) =>
                            element.serviceTypeFlag == "delivery-service",
                      );

                  if (innerSectionModel != null) {
                    controller.onServiceTap(context, innerSectionModel);
                  }
                },
                // },
              ),
              _mainCardsMaker(
                title: "Курьерская доставка",
                image: "assets/images/delivery_img.png",
                onTap: () {
                  log("Main Card Tapped");
                  SectionModel? innerSectionModel = sectionModel
                      .firstWhereOrNull(
                        (element) =>
                            element.serviceTypeFlag == "parcel_delivery",
                      );

                  if (innerSectionModel != null) {
                    controller.onServiceTap(context, innerSectionModel);
                  }
                },
              ),
            ],
          ),
          // Taxi Card
          InkWell(
            onTap: () {
              log("Taxi Card Tapped");
              // push(context, DashBoardCabService(user: null));
              SectionModel? innerSectionModel = sectionModel.firstWhereOrNull(
                (element) => element.serviceTypeFlag == "cab-service",
              );

              if (innerSectionModel != null) {
                controller.onServiceTap(context, innerSectionModel);
              }
            },
            child: Container(
              height: 192.h,
              width: 166.w,
              padding: EdgeInsets.only(top: 12.r, right: 12.r),
              decoration: BoxDecoration(
                color: AppThemeData.yellow,
                borderRadius: BorderRadius.circular(16.r),
              ),
              child: Column(
                children: [
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 12.r),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(
                            child: Text(
                              maxLines: 2,
                              "Позвать такси",
                              style: TextStyle(
                                overflow: TextOverflow.ellipsis,
                                fontFamily: AppThemeData.bold,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w700,
                                color: AppThemeData.grey50,
                              ),
                            ),
                          ),
                          Container(
                            height: 36.r,
                            width: 36.r,
                            decoration: BoxDecoration(
                              color: AppThemeData.grey50.withValues(alpha: 0.3),
                              borderRadius: BorderRadius.circular(8.r),
                            ),
                            child: Icon(
                              Icons.arrow_outward_rounded,
                              size: 20.r,
                              color: AppThemeData.grey50,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Image.asset(
                    "assets/images/taxi_img.png",
                    height: 119.r,
                    width: 156.r,
                    fit: BoxFit.contain,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _mainCardsMaker({
    required String title,
    required String image,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        height: 93.h,
        width: 165.w,
        padding: EdgeInsets.only(left: 12.r),
        decoration: BoxDecoration(
          color: AppThemeData.cardColor,
          borderRadius: BorderRadius.circular(16.r),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(bottom: 12.r, top: 12.r),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      maxLines: 2,
                      title,
                      style: TextStyle(
                        overflow: TextOverflow.ellipsis,
                        fontFamily: AppThemeData.bold,
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w700,
                        color: AppThemeData.darkGrey,
                      ),
                    ),
                    Icon(
                      Icons.arrow_outward_rounded,
                      size: 24.r,
                      color: AppThemeData.darkGrey,
                    ),
                  ],
                ),
              ),
            ),
            Image.asset(image, height: 71.r, width: 71.r, fit: BoxFit.contain),
          ],
        ),
      ),
    );
  }
}

class BannerView extends StatelessWidget {
  final List<dynamic> bannerList;
  final RxInt currentPage = 0.obs;
  final ScrollController scrollController = ScrollController();

  BannerView({super.key, required this.bannerList});

  void onScroll(BuildContext context) {
    if (scrollController.hasClients && bannerList.isNotEmpty) {
      final screenWidth = MediaQuery.of(context).size.width;
      final itemWidth = screenWidth * 0.8 + 10; // 80% width + spacing
      final offset = scrollController.offset;
      final index = (offset / itemWidth).round();

      if (index != currentPage.value && index < bannerList.length) {
        currentPage.value = index;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    scrollController.addListener(() => onScroll(context));

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        children: [
          SizedBox(
            height: 168,
            child: ListView.separated(
              controller: scrollController,
              scrollDirection: Axis.horizontal,
              itemCount: bannerList.length,
              separatorBuilder: (_, __) => const SizedBox(width: 12),
              itemBuilder: (context, index) {
                return ClipRRect(
                  borderRadius: BorderRadius.circular(12),
                  child: SizedBox(
                    width: MediaQuery.of(context).size.width * 0.8,
                    child: NetworkImageWidget(
                      imageUrl: bannerList[index].toString(),
                      fit: BoxFit.fill,
                    ),
                  ),
                );
              },
            ),
          ),
          const SizedBox(height: 8),
          Obx(() {
            return Row(
              children: List.generate(bannerList.length, (index) {
                final isSelected = currentPage.value == index;
                return Expanded(
                  child: Container(
                    height: 4,
                    decoration: BoxDecoration(
                      color:
                          isSelected
                              ? AppThemeData.grey300
                              : AppThemeData.grey100,
                      borderRadius: BorderRadius.circular(5),
                    ),
                  ),
                );
              }),
            );
          }),
        ],
      ),
    );
  }
}
