import 'dart:async';

import 'package:didvan/config/theme_data.dart';
import 'package:didvan/views/home/new_statistic/stock/exchange.dart';
import 'package:didvan/views/home/new_statistic/stock/metal.dart';
import 'package:didvan/views/home/new_statistic/stock/new_stock_state.dart';
import 'package:didvan/views/home/new_statistic/stock/total_type3.dart';
import 'package:didvan/views/home/new_statistic/stock/total_type4.dart';
import 'package:didvan/views/home/new_statistic/stock/total_type6.dart';
import 'package:didvan/views/home/new_statistic/stock/trade.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/divider.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/search_field.dart';
import 'package:didvan/views/widgets/shimmer_placeholder.dart';
import 'package:didvan/views/widgets/state_handlers/empty_result.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:toggle_switch/toggle_switch.dart';

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

  @override
  State<NewStock> createState() => _NewStockState();
}

class _NewStockState extends State<NewStock> {
  final ScrollController _scrollController = ScrollController();
  int pageNumber = 1;
  Timer? _timer;
  final _focusNode = FocusNode();

  int value = 0;

  @override
  void initState() {
    Future.delayed(Duration.zero, () {
      context.read<NewStockState>().getStock(page: 1);
    });

    _scrollController.addListener(_onScroll);
    super.initState();
  }

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

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent) {
      pageNumber++;
      context.read<NewStockState>().getStock(page: pageNumber);
    }
  }

  void _onChanged(String value) {
    final state = context.read<NewStockState>();
    if (value.length < 3 && value.isNotEmpty || state.lastSearch == value) {
      return;
    }
    _timer?.cancel();
    _timer = Timer(const Duration(seconds: 1), () {
      state.search = value;
      state.getStock(page: 1);
    });
  }

  List<bool> isSelected = [true, false, false, false];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.surface,
        elevation: 0.0,
        scrolledUnderElevation: 0.0,
        title: DidvanText(
          "بازار سرمایه",
          style: Theme.of(context).textTheme.bodyLarge,
          fontSize: 20,
        ),
      ),
      body: Column(
        children: [
          Container(
            height: 80,
            color: Theme.of(context).colorScheme.surface,
            padding:
                const EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0),
            child: SearchField(
              title: "بازار سرمایه",
              value: context.watch<NewStockState>().lastSearch,
              onChanged: _onChanged,
              focusNode: _focusNode,
            ),
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height / 24,
          ),

          // Here, default theme colors are used for activeBgColor, activeFgColor, inactiveBgColor and inactiveFgColor
          ToggleSwitch(
            borderWidth: 1,
            activeBgColor: [Theme.of(context).colorScheme.primary],
            radiusStyle: true,
            borderColor: [Theme.of(context).colorScheme.border],
            centerText: true,
            activeFgColor: Theme.of(context).colorScheme.onPrimary,
            inactiveBgColor: Theme.of(context).colorScheme.surface,
            inactiveFgColor: Theme.of(context).colorScheme.text,
            dividerColor: Theme.of(context).colorScheme.border,
            initialLabelIndex: value,
            customTextStyles: const [TextStyle(fontWeight: FontWeight.w500)],
            minWidth: 90,
            totalSwitches: 4,
            labels: const ['بورس', 'فرابورس', 'شاخص کل', 'گروه فولاد'],
            onToggle: (index) {
              setState(() {
                value = index!;
                context.read<NewStockState>().type = index + 1;
                context.read<NewStockState>().getStock(page: 1);
              });
            },
          ),
          SizedBox(
            height: MediaQuery.of(context).size.height / 48,
          ),
          StateHandler<NewStockState>(
            onRetry: context.read<NewStockState>().init,
            state: context.watch<NewStockState>(),
            emptyState: EmptyResult(
              onNewSearch: () => _focusNode.requestFocus(),
            ),
            enableEmptyState: context.read<NewStockState>().contents.isEmpty,
            topPadding: 16,
            placeholder: Column(
              children: [
                placeholder2,
                const SizedBox(
                  height: 8.0,
                ),
                placeholder2,
              ],
            ),
            builder: (context, state) => Expanded(
              child: ListView.builder(
                  controller: _scrollController,
                  itemCount: state.length,
                  itemBuilder: (context, index) {
                    if (state.type == 1) {
                      return Column(
                        children: [
                          if (state.contents[index].type == 2)
                            ExchangeCard(
                              exchangeContent: state.contents[index],
                            ),
                          if (state.contents[index].type == 4)
                            Trade(totalContent: state.contents[index])
                        ],
                      );
                    }

                    if (state.type == 2) {
                      return Column(
                        children: [
                          if (state.contents[index].type == 2)
                            ExchangeCard(
                              exchangeContent: state.contents[index],
                            ),
                          if (state.contents[index].type == 4)
                            Trade(totalContent: state.contents[index])
                        ],
                      );
                    }

                    if (state.type == 3) {
                      return Column(
                        children: [
                          if (state.contents[index].type == 3)
                            TotalType3Card(totalContent: state.contents[index]),
                          if (state.contents[index].type == 4)
                            TotalType4Card(totalContent: state.contents[index]),
                          if (state.contents[index].type == 6)
                            TotalType6Card(totalContent: state.contents[index])
                        ],
                      );
                    }

                    return MetalCard(metalContent: state.contents[index]);
                  }),
            ),
          ),
        ],
      ),
    );
  }

  static Widget get placeholder2 => const DidvanCard(
        child: Column(
          children: [
            ShimmerPlaceholder(height: 18, width: 400),
            DidvanDivider(
              verticalPadding: 8,
            ),
            SizedBox(
              height: 12,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                ),
                SizedBox(
                  height: 12,
                ),
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                )
              ],
            ),
            SizedBox(
              height: 12,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                ),
                SizedBox(
                  height: 12,
                ),
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                )
              ],
            ),
            SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                ),
                SizedBox(
                  height: 12,
                ),
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                )
              ],
            ),
            SizedBox(
              height: 12,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                ),
                SizedBox(
                  height: 12,
                ),
                ShimmerPlaceholder(
                  width: 100,
                  height: 18,
                )
              ],
            ),
          ],
        ),
      );
}
