import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gap/gap.dart';
import 'package:get/get.dart';
import 'package:traderscircuit/Utils/Common/CommonAppBar.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/view/Sidemenu/ContentByte/PlayerWidget.dart';
import 'package:traderscircuit/view/onBoarding/splashScreen1.dart';
import 'package:traderscircuit/view_model/ContentBytesApi/content_bytes_api.dart';

class VideosMore extends StatefulWidget {
  const VideosMore({Key? key}) : super(key: key);

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

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

  TextEditingController searchController = TextEditingController();

  @override
  void initState() {
    ContentBytesApi().getContentBytesData("", "video", "").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, "video", contentBytesController.filterId.toString())
        .then((value) {
      contentBytesController.contentBytesModel =
          ContentBytesModel.fromJson(value.data);
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const CommonAppbar(
        titleTxt: "Videos",
      ),
      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: 8),
                        child: Column(
                          children: [
                            Row(
                              children: [
                                SizedBox(
                                  width: 295.w,
                                  child: TextField(
                                    controller: searchController,
                                    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(),
                              ],
                            ),
                            SizedBox(
                              height: 10.h,
                            ),
                            // Display search results or regular list
                            SizedBox(
                              height: 620.h,
                              child: ListView.separated(
                                padding: EdgeInsets.zero,
                                shrinkWrap: true,
                                itemCount: contentBytesController
                                    .contentBytesModel.data!.video!.length,
                                itemBuilder: (ctx, index) {
                                  return Container(
                                    margin: const EdgeInsets.only(
                                      bottom: 20,
                                    ),
                                    child: videoCard(
                                        contentBytesController.contentBytesModel
                                                .data!.video![index].file ??
                                            "",
                                        contentBytesController.contentBytesModel
                                                .data!.video![index].title ??
                                            "",
                                        contentBytesController
                                                .contentBytesModel
                                                .data!
                                                .video![index]
                                                .description ??
                                            "",
                                        contentBytesController.contentBytesModel
                                                .data!.video![index].image ??
                                            ""),
                                  );
                                },
                                separatorBuilder: (ctx, inndex) {
                                  return SizedBox(
                                    height: 10,
                                  );
                                },
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
          ],
        ),
      ),
    );
  }

  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(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Center(
                child: SizedBox(
                  height: (Get.height *
                          contentBytesController
                              .contentBytesCategoriesModel.data!.length) /
                      17,
                  width: 160,
                  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(searchController.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,
              ),
      ],
    );
  }

  Widget searchResultsWidget() {
    // Display search results here
    return SizedBox();
  }

  Widget videoCard(
      String video, String title, String description, String image) {
    return InkWell(
      onTap: () {
        Get.to(() => const PlayerWidget(), arguments: {
          "video_url": video,
        });
      },
      child: commonGlassContainer(
          borderradius: 8,
          width: double.infinity,
          height: 320.h,
          customWidget: Padding(
            padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 10.w),
            child: Column(
              children: [
                Container(
                  height: 200.h,
                  width: double.infinity,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(8.r),
                      image: DecorationImage(
                          image: NetworkImage(
                        image,
                      ))),
                  child: Center(
                    child: SvgPicture.asset(
                      'assets/images/svg/gridicons_play.svg',
                      height: 56.h,
                      width: 56.w,
                    ),
                  ),
                ),
                sizedBoxHeight(20.h),
                Row(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        text18W500(title),
                        text16W400(description),
                        text12W400_979797('2 days ago'),
                      ],
                    )
                  ],
                )
              ],
            ),
          )),
    );
  }
}
