import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/models/ai/ai_chat_args.dart';
import 'package:didvan/models/ai/tools_model.dart';
import 'package:didvan/views/ai/ai.dart';
import 'package:didvan/views/ai/ai_chat_page.dart';
import 'package:didvan/views/ai/widgets/hoshan_drawer.dart';
import 'package:didvan/views/ai_section/widgets/ai_section_bnb.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/hoshan_app_bar.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:didvan/views/ai/history_ai_chat_state.dart';
import 'package:didvan/views/ai/ai_state.dart';
import 'package:didvan/views/ai/widgets/tool_category_view_widget.dart';

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

  @override
  Widget build(BuildContext context) {
    final aiState = context.watch<AiState>();

    if (aiState.tools == null || aiState.tools!.isEmpty) {
      if (aiState.loading) {
        return const Center(child: CircularProgressIndicator());
      }
      return const Center(
          child: DidvanText('لیست ابزارها هنوز بارگذاری نشده یا خالی است.'));
    }
    final Tools imageGenToolCategory = aiState.tools![0];
    return ToolCategoryViewWidget(tool: imageGenToolCategory);
  }
}

class VoiceChatScreen extends StatelessWidget {
  const VoiceChatScreen({super.key});
  @override
  Widget build(BuildContext context) {
    final aiState = context.watch<AiState>();

    if (aiState.tools == null || aiState.tools!.isEmpty) {
      if (aiState.loading) {
        return const Center(child: CircularProgressIndicator());
      }
      return const Center(
          child: DidvanText('لیست ابزارها هنوز بارگذاری نشده یا خالی است.'));
    }
    final Tools voiceChatToolCategory = aiState.tools!.last;

    return ToolCategoryViewWidget(tool: voiceChatToolCategory);
  }
}

class ChartAnalysisScreen extends StatelessWidget {
  const ChartAnalysisScreen({super.key});
  @override
  Widget build(BuildContext context) {
    final aiState = context.watch<AiState>();

    if (aiState.tools == null || aiState.tools!.isEmpty) {
      if (aiState.loading) {
        return const Center(child: CircularProgressIndicator());
      }
      return const Center(
          child: DidvanText('لیست ابزارها هنوز بارگذاری نشده یا خالی است.'));
    }

    if (aiState.tools!.length < 2) {
      return const Center(
          child:
              DidvanText('ابزار کافی برای "تحلیل نمودار" وجود ندارد.'));
    }
    final Tools chartAnalysisToolCategory = aiState.tools![1];

    return ToolCategoryViewWidget(tool: chartAnalysisToolCategory);
  }
}

class TranslationScreen extends StatelessWidget {
  const TranslationScreen({super.key});
  @override
  Widget build(BuildContext context) {
    final aiState = context.watch<AiState>();

    if (aiState.tools == null || aiState.tools!.isEmpty) {
      if (aiState.loading) {
        return const Center(child: CircularProgressIndicator());
      }
      return const Center(
          child: DidvanText('لیست ابزارها هنوز بارگذاری نشده یا خالی است.'));
    }

    if (aiState.tools!.length < 3) {
      return const Center(
          child: DidvanText('ابزار کافی برای "ترجمه" وجود ندارد.'));
    }
    final Tools translationToolCategory = aiState.tools![2];

    return ToolCategoryViewWidget(tool: translationToolCategory);
  }
}
class AiSectionPage extends StatefulWidget {
  const AiSectionPage({super.key});

  @override
  State<AiSectionPage> createState() => _AiSectionPageState();
}

class _AiSectionPageState extends State<AiSectionPage> {
  int _currentTabIndex = 2;
  final GlobalKey<ScaffoldState> _aiSectionScaffoldKey =
      GlobalKey<ScaffoldState>();

  final List<Widget> _pages = const [
    ImageGenerationScreen(),
    VoiceChatScreen(),
    Ai(),
    ChartAnalysisScreen(),
    TranslationScreen(),
  ];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final historyAiChatState = context.read<HistoryAiChatState>();
      if (historyAiChatState.bots.isEmpty) {
        historyAiChatState.getBots();
      }

      final aiState = context.read<AiState>();
       aiState.endChat(); 
      if (aiState.tools == null) {
        aiState.getTools();
      }
    });
  }

  void _onTabChanged(int index) {
    final aiState = context.read<AiState>();
    aiState.endChat();

    setState(() {
      _currentTabIndex = index;
    });

    if (aiState.tools != null && aiState.tools!.isNotEmpty) {
      Tools? tool;
      switch (index) {
        case 0:
          tool = aiState.tools![0];
          break;
        case 1:
          tool = aiState.tools!.last;
          break;
        case 2:
          return;
        case 3:
          if (aiState.tools!.length > 1) {
            tool = aiState.tools![1];
          }
          break;
        case 4:
          if (aiState.tools!.length > 2) {
            tool = aiState.tools![2];
          }
          break;
      }

      if (tool != null && tool.bots != null && tool.bots!.isNotEmpty) {
        final firstBot = tool.bots!.first;
        aiState.startChat(AiChatArgs(bot: firstBot));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final aiState = context.watch<AiState>();

    return Scaffold(
      key: _aiSectionScaffoldKey,
      appBar: HoshanAppBar(
        onBack: () {
            Navigator.of(context).pop();
          },
        withActions: true,
      ),
      drawer: HoshanDrawer(scaffKey: _aiSectionScaffoldKey),
      body: Stack(
        children: [
          aiState.isChatting
              ? AiChatPage(args: aiState.currentChatArgs!)
              : IndexedStack(
                  index: _currentTabIndex,
                  children: _pages,
                ),
          Positioned(
            top: 32,
            right: 0,
            child: InkWell(
              onTap: () => _aiSectionScaffoldKey.currentState?.openDrawer(),
              child: Container(
                width: 46,
                height: 46,
                decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.surface,
                    borderRadius: const BorderRadius.only(
                        topLeft: Radius.circular(12),
                        bottomLeft: Radius.circular(12)),
                    boxShadow: DesignConfig.defaultShadow),
                child: Icon(
                  DidvanIcons.angle_left_light,
                  color: Theme.of(context).colorScheme.title,
                ),
              ),
            ),
          )
        ],
      ),
      bottomNavigationBar: AiSectionBNB(
        currentTabIndex: _currentTabIndex,
        onTabChanged: _onTabChanged,
      ),
    );
  }
}