// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:go_router/go_router.dart';
import 'package:hoshan/core/services/api/dio_service.dart';
import 'package:hoshan/data/model/ai/bots_model.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';
import 'package:hoshan/ui/screens/library/bloc/chats_history_bloc.dart';
import 'package:hoshan/ui/screens/library/library_screen.dart';
import 'package:hoshan/ui/screens/gmedia/cubit/media_g_response_cubit.dart';
import 'package:hoshan/ui/screens/gmedia/cubit/single_media_cubit.dart';
import 'package:hoshan/ui/screens/gmedia/chats/video_chat_page.dart';
import 'package:hoshan/ui/theme/colors.dart';
import 'package:hoshan/ui/theme/cubit/theme_mode_cubit.dart';
import 'package:hoshan/ui/theme/responsive.dart';
import 'package:hoshan/ui/theme/text.dart';
import 'package:hoshan/ui/widgets/components/dialog/dialog_handler.dart';
import 'package:hoshan/ui/widgets/components/snackbar/snackbar_manager.dart';

class GenerateVideoPage extends StatefulWidget {
  final int? id;
  const GenerateVideoPage({super.key, this.id});

  @override
  State<GenerateVideoPage> createState() => _GenerateAudioPageState();
}

class _GenerateAudioPageState extends State<GenerateVideoPage>
    with TickerProviderStateMixin {
  Bots? selectedBot;
  int? chatId;

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ChatsHistoryBloc>().add(RestartChatsHistory());
      context.read<ChatsHistoryBloc>().add(const GetAllChats(type: 'video'));

      if (!GuidsStorage.isSeenVideo()) {
        DialogHandler(context: context).onVideoCreate();
        GuidsStorage.setSeenVideo(true);
      }

      if (widget.id != null) {
        context.read<SingleMediaCubit>().getMediaById(widget.id!);
      }
    });
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  late final TabController tabController =
      TabController(length: 3, vsync: this);

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<SingleMediaCubit, SingleMediaState>(
      listener: (context, state) {
        if (state is SingleMediaFail) {
          context.pop();
          SnackBarManager(context).show(
              message:
                  'خطا در برقراری ارتباط با سرور لطفا لحظاتی دیگر امتحان کنید',
              status: SnackBarStatus.error);
        }
      },
      builder: (context, state) {
        if (state is SingleMediaFail) {
          return const SizedBox.shrink();
        }
        if (state is SingleMediaSuccess) {
          return DefaultTabController(
            length: state.medias.categories?.length ?? 0,
            child: Scaffold(
              body: Responsive(context).maxWidthInDesktop(
                child: (contxet, mw) => Scaffold(
                  drawer: Drawer(
                    shape: const BeveledRectangleBorder(
                        borderRadius: BorderRadius.zero),
                    child: LibraryScreen(
                      type: 'video',
                      onTap: (chat) {
                        final id = chat.bot?.category?.id;
                        if (id != null && state.medias.categories != null) {
                          try {
                            final categoryIndex = state.medias.categories!
                                .indexWhere((element) => element.id == id);
                            
                            if (categoryIndex != -1) {
                              tabController.animateTo(categoryIndex);
                              Navigator.of(context).pop(); // Close the drawer
                              
                              // استفاده از postFrameCallback برای جلوگیری از setState در build
                              WidgetsBinding.instance.addPostFrameCallback((_) {
                                if (mounted) {
                                  setState(() {
                                    chatId = chat.id;
                                    selectedBot = chat.bot;
                                  });
                                }
                              });
                            }
                          } catch (e) {
                            // اگر category پیدا نشد، فقط drawer را ببند
                            Navigator.of(context).pop();
                          }
                        } else {
                          // اگر category null بود، فقط drawer را ببند
                          Navigator.of(context).pop();
                        }
                      },
                    ),
                  ),
                  appBar: AppBar(
                    toolbarHeight: 28,
                    backgroundColor: context.read<ThemeModeCubit>().isDark()
                        ? null
                        : AppColors.primaryColor[50],
                    bottom: TabBar(
                      controller: tabController,
                      dividerColor: Colors.transparent,
                      onTap: (value) {
                        setState(() {
                          selectedBot = null;
                          chatId = null;
                        });
                      },
                      tabs: List.generate(
                        state.medias.categories?.length ?? 0,
                        (index) {
                          return Tab(
                            height: 80,
                            child: AnimatedBuilder(
                                animation: tabController,
                                builder: (context, _) {
                                  return Column(
                                    children: [
                                      if (state
                                              .medias.categories?[index].icon !=
                                          null)
                                        Expanded(
                                          child: SvgPicture.network(
                                            DioService.baseURL +
                                                state.medias.categories![index]
                                                    .icon!,
                                            color: tabController.index == index
                                                ? Theme.of(context)
                                                    .colorScheme
                                                    .primary
                                                : AppColors.gray[context
                                                        .read<ThemeModeCubit>()
                                                        .isDark()
                                                    ? 400
                                                    : 800],
                                          ),
                                        ),
                                      Text(
                                        state.medias.categories?[index].name ??
                                            '',
                                        style: AppTextStyles.body4.copyWith(
                                            fontWeight:
                                                tabController.index == index
                                                    ? FontWeight.bold
                                                    : FontWeight.normal,
                                            color: tabController.index == index
                                                ? Theme.of(context)
                                                    .colorScheme
                                                    .primary
                                                : AppColors.gray[context
                                                        .read<ThemeModeCubit>()
                                                        .isDark()
                                                    ? 400
                                                    : 800]),
                                      ),
                                      const SizedBox(
                                        height: 8,
                                      ),
                                    ],
                                  );
                                }),
                          );
                        },
                      ),
                    ),
                  ),
                  body: TabBarView(
                    key: ValueKey(chatId), // Change key to force rebuild
                    physics: const NeverScrollableScrollPhysics(),
                    controller: tabController,
                    children: List.generate(
                      state.medias.categories!.length,
                      (index) {
                        final bot = selectedBot ??
                            state.medias.categories![index].bots!.first;
                        return MultiBlocProvider(
                          providers: [
                            BlocProvider<MediaGResponseCubit>(
                              create: (context) {
                                return MediaGResponseCubit();
                              },
                            ),
                          ],
                          child: VideoChatPage(
                            textToVideo: bot.attachmentType == null,
                            chatId: chatId,
                            bot: bot,
                            maxWidth: mw,
                          ),
                        );
                      },
                    ),
                  ),
                ),
              ),
            ),
          );
        }
        return const Scaffold(
          body: Center(
            child: CircularProgressIndicator(),
          ),
        );
      },
    );
  }
}
