import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:gap/gap.dart';
import 'package:get/get.dart';
import 'package:traderscircuit/Utils/Common/CommonAppbar.dart';
import 'package:traderscircuit/Utils/Common/CustomTextFormField.dart';
import 'package:traderscircuit/Utils/Common/comonGlassmorphicContainer.dart';
import 'package:traderscircuit/Utils/Common/sized_box.dart';
import 'package:traderscircuit/Utils/text.dart';
import 'package:traderscircuit/controller/content_bytes_controller.dart';
import 'package:traderscircuit/model/ContentBytesModel/content_bytes_model.dart';
import 'package:traderscircuit/resources/routes/route_name.dart';
import 'package:traderscircuit/view/Sidemenu/ContentByte/PlayerWidget.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';
import 'package:traderscircuit/view_model/ContentBytesApi/content_bytes_api.dart';

class AudioMore extends StatefulWidget {
  const AudioMore({super.key});

  @override
  State<AudioMore> createState() => _VideosMoreState();
}

class _VideosMoreState extends State<AudioMore> {
  ContentBytesController contentBytesController =
      Get.put(ContentBytesController());
  var data;
  RxBool isLoading = false.obs;

  TextEditingController searchControllera = TextEditingController();

  @override
  void initState() {
    ContentBytesApi().getContentBytesData("", "audio", "").then((value) {
      contentBytesController.contentBytesModel =
          ContentBytesModel.fromJson(value.data);
      contentBytesController.isApiCalling.value = false;
      setState(() {});
    });
    super.initState();
  }

  void handleSearch(String query, String category) async {
    await ContentBytesApi()
        .getContentBytesData(
            query, "audio", contentBytesController.filterId.toString())
        .then((value) {
      contentBytesController.contentBytesModel =
          ContentBytesModel.fromJson(value.data);
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const CommonAppbar(
        titleTxt: "Audio",
      ),
      backgroundColor: Colors.black,
      extendBody: true,
      body: Obx(
        () => Stack(
          children: [
            const CommonBlurLeft(),
            const CommonBlurRight(),
            isLoading.value
                ? const Center(
                    child: CircularProgressIndicator(
                      color: Color(0xFF9A0000),
                    ),
                  )
                : Stack(
                    children: [
                      Padding(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 16, vertical: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            text16W400_DADADA('The Beauty and Power of Audios'),
                            sizedBoxHeight(8.w),
                            Row(
                              children: [
                                SizedBox(
                                  width: 295.w,
                                  child: TextField(
                                    controller: searchControllera,
                                    onChanged: (value) {
                                      // Call method to handle search
                                      handleSearch(value, "");
                                    },
                                    decoration: InputDecoration(
                                      prefixIcon: Icon(Icons.search),
                                      hintText: 'Search videos',
                                      border: OutlineInputBorder(),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  width: 12.w,
                                ),
                                filter(),
                              ],
                            ),
                            sizedBoxHeight(20.h),
                            GridView.builder(
                              shrinkWrap: true,
                              physics: const NeverScrollableScrollPhysics(),
                              gridDelegate:
                                  const SliverGridDelegateWithFixedCrossAxisCount(
                                mainAxisExtent: 172,
                                crossAxisCount:
                                    2, // number of items in each row
                                mainAxisSpacing: 8.0, // spacing between rows
                                crossAxisSpacing:
                                    8.0, // spacing between columns
                              ),

                              itemCount: contentBytesController
                                  .contentBytesModel
                                  .data!
                                  .audio!
                                  .length, // total number of items
                              itemBuilder: (context, index) {
                                return InkWell(
                                  onTap: () {
                                    contentBytesController.init(0);
                                    contentBytesController
                                        .isAudioSeekBarVisible.value = true;
                                    //https://actions.google.com/sounds/v1/horror/aggressive_zombie_snarls.ogg
                                  },
                                  child: Container(
                                    decoration: BoxDecoration(
                                      gradient: LinearGradient(
                                        begin: Alignment.topLeft,
                                        end: Alignment.bottomRight,
                                        colors: [
                                          Colors.white.withOpacity(0.1),
                                          const Color(0xFFFFFFFF)
                                              .withOpacity(0.05),
                                        ],
                                        stops: [
                                          0.1,
                                          1,
                                        ],
                                      ),
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                    child: Stack(
                                      children: [
                                        Image.network(
                                          contentBytesController
                                              .contentBytesModel
                                              .data!
                                              .audio![index]
                                              .image!,
                                        ),
                                        Positioned(
                                          bottom: 5,
                                          left: 5,
                                          child: Row(
                                            children: [
                                              CircleAvatar(
                                                radius: 18.sp,
                                                child: const Icon(
                                                    Icons.headphones),
                                              ),
                                              SizedBox(
                                                width: 5.w,
                                              ),
                                              SizedBox(
                                                width: 125.w,
                                                child: text14W500(
                                                    contentBytesController
                                                        .contentBytesModel
                                                        .data!
                                                        .audio![index]
                                                        .title!),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
          ],
        ),
      ),
    );
  }

  Widget filter() {
    return PopupMenuButton(
      icon: Image.asset(
        "assets/images/png/filter.png",
        height: 30.h,
        width: 30.w,
      ),
      color: const Color(0xFF191919),
      itemBuilder: (context) {
        return [
          PopupMenuItem(
              child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                height: (Get.height *
                        contentBytesController
                            .contentBytesCategoriesModel.data!.length) /
                    17,
                width: 150,
                child: ListView.builder(
                    padding: EdgeInsets.zero,
                    shrinkWrap: true,
                    itemCount: contentBytesController
                        .contentBytesCategoriesModel.data!.length,
                    itemBuilder: (ctx, index) {
                      return InkWell(
                          onTap: () {
                            //     contentBytesController.isApiCalling.value = true;
                            Get.back();
                            contentBytesController.filterId =
                                contentBytesController
                                    .contentBytesCategoriesModel
                                    .data![index]
                                    .id!;
                            log(contentBytesController.filterId.toString());
                            handleSearch(searchControllera.text,
                                contentBytesController.filterId.toString());
                          },
                          child: itemFilter(index));
                    }),
              ),
            ],
          ))
        ];
      },
    );
  }

  Widget itemFilter(int index) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const Gap(8),
        text18W400(
          contentBytesController
              .contentBytesCategoriesModel.data![index].categoryName!,
          texAl: TextAlign.center,
        ),
        index ==
                contentBytesController
                        .contentBytesCategoriesModel.data!.length -
                    1
            ? const SizedBox()
            : const Divider(
                color: Color(0xFF2C2C2C),
                thickness: 0.6,
                endIndent: 0,
              ),
      ],
    );
  }
}
