import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mitra_corporate/app/constant.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/screen/dashboard/chart_provider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../widgets/custom_snackbar_widget.dart';

class ChartScreen extends HookConsumerWidget {
  const ChartScreen({super.key, required this.filter});
  final ValueNotifier<String> filter;
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // N = New, S= Send, P= Parsial, D=Done,
    final auth = ref.watch(authProvider);
    final chartLoading = useState(false);

    final total = useState<List<String>>(List.empty());
    final dikirim = useState<List<String>>(List.empty());
    final dikonfirmasi = useState<List<String>>(List.empty());

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        var fltr = "month";
        if (filter.value.toLowerCase() == "bulan") {
          fltr = "month";
        }
        if (filter.value.toLowerCase() == "tahun") {
          fltr = "year";
        }
        ref.read(ChartDataProvider.notifier).ChartData(
            token: auth?.token ?? "",
            filter: fltr,
            company_id: auth?.mUserMCompanyID ?? "");
      });
      return () {};
    }, [filter.value]);

    ref.listen(ChartDataProvider, (prev, next) async {
      if (next is ChartDataStateLoading) {
        chartLoading.value = true;
      } else if (next is ChartDataStateError) {
        chartLoading.value = false;

        SanckbarWidget(context, next.message ?? "", snackbarType.error);
        Constant.autoLogout(context: context, msg: next.message ?? "");
      } else if (next is ChartDataStateDone) {
        total.value = next.model.t ?? [];
        dikirim.value = next.model.s ?? [];
        dikonfirmasi.value = next.model.y ?? [];

        chartLoading.value = false;
      }
    });

    return Scaffold(
      body: chartLoading.value
          ? Center(
              child: LoadingAnimationWidget.discreteCircle(
                  color: Constant.primaryBlue, size: 40))
          : Padding(
              padding: const EdgeInsets.all(20),
              child: LineChart(
                LineChartData(
                    gridData: FlGridData(
                      show: true,
                    ),
                    borderData: FlBorderData(
                        show: true,
                        border: Border(
                            top: BorderSide.none,
                            right: BorderSide.none,
                            left: BorderSide(color: Colors.grey.shade500),
                            bottom: BorderSide(color: Colors.grey.shade500))),
                    backgroundColor: Colors.white,
                    minX: 0,
                    minY: 0,
                    // maxX: 31,
                    titlesData: FlTitlesData(
                        rightTitles: AxisTitles(
                          sideTitles: SideTitles(showTitles: false),
                        ),
                        topTitles: AxisTitles(
                            sideTitles: SideTitles(showTitles: false)),
                        leftTitles: AxisTitles(
                            axisNameSize: 30,
                            axisNameWidget: Text(
                              "Total",
                              style: Constant.caption1_400(context: context),
                            ),
                            sideTitles: SideTitles(
                              showTitles: true,
                              reservedSize: 32,
                              interval: 10,
                              getTitlesWidget: (double value, TitleMeta meta) {
                                return SideTitleWidget(
                                  axisSide: meta.axisSide,
                                  space: 10,
                                  child: Text(
                                    value.toInt().toString(),
                                    style:
                                        Constant.caption1_400(context: context),
                                  ),
                                );
                              },
                            )),
                        bottomTitles: AxisTitles(
                            axisNameSize: 30,
                            axisNameWidget: Container(
                              child: Text(
                                filter.value == "Bulan" ? "Hari" : "Bulan",
                                style: Constant.caption1_400(context: context),
                              ),
                            ),
                            sideTitles: SideTitles(
                              showTitles: true,
                              reservedSize: 32,
                              interval: 1,
                              getTitlesWidget: (double value, TitleMeta meta) {
                                return SideTitleWidget(
                                    axisSide: meta.axisSide,
                                    space: 10,
                                    child: Text(
                                      style: Constant.caption1_400(
                                          context: context),
                                      value.toInt().toString(),
                                    ));
                              },
                            ))),
                    lineBarsData: [
                      // LineChartBarData(
                      //     isCurved: true,
                      //     curveSmoothness: 0.20,
                      //     color: Colors.red,
                      //     barWidth: 4,
                      //     isStrokeCapRound: true,
                      //     dotData: FlDotData(
                      //       checkToShowDot: (spot, barData) {
                      //         if (pending.value.length == 1) {
                      //           return true;
                      //         } else {
                      //           return false;
                      //         }
                      //       },
                      //     ),
                      //     belowBarData: BarAreaData(show: false),
                      //     spots: pending.value.map((e) {
                      //       var sp = e.split("|");
                      //       return FlSpot(
                      //           double.parse(sp[0]), double.parse(sp[1]));
                      //     }).toList()),
                      LineChartBarData(
                          isCurved: true,
                          curveSmoothness: 0.2,
                          color: Colors.purple,
                          barWidth: 4,
                          isStrokeCapRound: true,
                          dotData: FlDotData(
                            checkToShowDot: (spot, barData) {
                              if (dikirim.value.length == 1) {
                                return true;
                              } else {
                                return false;
                              }
                            },
                          ),
                          belowBarData: BarAreaData(show: false),
                          spots: dikirim.value.map((e) {
                            var sp = e.split("|");
                            return FlSpot(
                                double.parse(sp[0]), double.parse(sp[1]));
                          }).toList()),
                      LineChartBarData(
                          isCurved: true,
                          curveSmoothness: 0.1,
                          color: Colors.blue,
                          barWidth: 4,
                          isStrokeCapRound: true,
                          dotData: FlDotData(
                            checkToShowDot: (spot, barData) {
                              if (total.value.length == 1) {
                                return true;
                              } else {
                                return false;
                              }
                            },
                          ),
                          belowBarData: BarAreaData(show: false),
                          spots: total.value.map((e) {
                            var sp = e.split("|");
                            return FlSpot(
                                double.parse(sp[0]), double.parse(sp[1]));
                          }).toList()),
                      LineChartBarData(
                          isCurved: true,
                          curveSmoothness: 0.20,
                          color: Colors.green,
                          barWidth: 4,
                          isStrokeCapRound: true,
                          dotData: FlDotData(
                            checkToShowDot: (spot, barData) {
                              if (dikonfirmasi.value.length == 1) {
                                return true;
                              } else {
                                return false;
                              }
                            },
                          ),
                          belowBarData: BarAreaData(show: false),
                          spots: dikonfirmasi.value.map((e) {
                            var sp = e.split("|");
                            return FlSpot(
                                double.parse(sp[0]), double.parse(sp[1]));
                          }).toList()),
                    ],
                    extraLinesData: ExtraLinesData(horizontalLines: [
                      HorizontalLine(
                          y: 0,
                          color: Colors.white,
                          strokeWidth: 1,
                          dashArray: [5])
                    ])),
                // swapAnimationDuration: Duration(milliseconds: 150),
                // swapAnimationCurve: Curves.linear,
              ),
            ),
    );
  }
}
