// import 'package:flutter/material.dart';
// // import 'package:test_sa/pie_chart/pie_chart.dart';
// import 'package:provider/provider.dart';
// import 'package:syncfusion_flutter_charts/charts.dart';
// import 'package:test_sa/controllers/providers/api/all_requests_provider.dart';
// import 'package:test_sa/extensions/context_extension.dart';
// import 'package:test_sa/extensions/int_extensions.dart';
// import 'package:test_sa/extensions/text_extensions.dart';
// import 'package:test_sa/extensions/widget_extensions.dart';
// import 'package:test_sa/new_views/app_style/app_color.dart';
// import 'package:test_sa/new_views/pages/land_page/widgets/request_item_view_list.dart';
//
// import '../../../../controllers/providers/api/user_provider.dart';
// import '../../../../models/enums/user_types.dart';
//
// class ProgressFragment extends StatelessWidget {
//   ProgressFragment({Key key}) : super(key: key);
//
//   UserProvider _userProvider;
//
//   AllRequestsProvider _provider;
//
//   @override
//   Widget build(BuildContext context) {
//     _userProvider = Provider.of<UserProvider>(context);
//     bool isCurrentUserNotEngineer = (_userProvider.user.type != UsersTypes.engineer);
//     return Consumer<AllRequestsProvider>(
//       builder: (context, snapshot, _) {
//         if (_provider == null) {
//           _provider = snapshot;
//           if (isCurrentUserNotEngineer) {
//             _provider.getOpenRequests(reset: true);
//           }
//           _provider.getInProgressRequests(reset:true);
//           _provider.getCompletedRequests(reset:true);
//         }
//
//         int total = (snapshot.completedRequests?.total?.count ?? 0) + (snapshot.inProgressRequests?.total?.count ?? 0) + (isCurrentUserNotEngineer ? (snapshot.openRequests?.total?.count ?? 0) : 0);
//
//         final List<ChartData> chartData = [
//           ChartData('Completed', snapshot.completedRequests?.total?.count?.toDouble() ?? 0.0, AppColor.greenStatus(context)),
//           ChartData('In Progress', snapshot.inProgressRequests?.total?.count?.toDouble() ?? 0.0, AppColor.yellowStatus(context)),
//         ];
//
//         if (isCurrentUserNotEngineer) {
//           chartData.insert(1, ChartData('Open', snapshot.openRequests?.total?.count?.toDouble() ?? 0.0, AppColor.blueStatus(context)));
//         }
//
//         return Column(
//           children: [
//             AspectRatio(
//               aspectRatio: 398 / 237,
//               child: Stack(
//                 alignment: Alignment.center,
//                 children: [
//                   SfCircularChart(
//                       tooltipBehavior: TooltipBehavior(
//                         enable: true,
//                         // elevation: 2,
//                         color: context.isDark ? Color(0xFF111427) : Color(0xffF7F9FB),
//                         textStyle: context.isDark ? null : TextStyle(color: Colors.black87, fontSize: 12),
//                       ),
//                       legend: Legend(
//                           //isVisible: true,
//                           ),
//                       series: <CircularSeries>[
//                         DoughnutSeries<ChartData, String>(
//                           dataSource: chartData,
//                           radius: "110%",
//                           innerRadius: "60%",
//                           pointColorMapper: (ChartData data, _) => data.color,
//                           xValueMapper: (ChartData data, _) => data.x,
//                           yValueMapper: (ChartData data, _) => data.y,
//                           dataLabelMapper: (ChartData data, _) => data.x,
//                           dataLabelSettings: DataLabelSettings(
//                             isVisible: true,
//                             textStyle: TextStyle(color: context.isDark ? Colors.white : Colors.black87, fontSize: 12),
//                             labelPosition: ChartDataLabelPosition.outside,
//                             //useSeriesColor: true,
//                           ),
//                         )
//                       ]).toShimmer(isShow: snapshot.isOpenLoading || snapshot.isInProgressLoading || snapshot.isCompleteLoading, radius: 300).paddingAll(12).toShadowContainer(context),
//                   Column(
//                     mainAxisSize: MainAxisSize.min,
//                     children: [
//                       Text(
//                         context.translation.total,
//                         style: AppTextStyles.heading5.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50),
//                       ),
//                       Text(
//                         "$total",
//                         style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
//                       ),
//                     ],
//                   ),
//                 ],
//               ),
//             ).paddingOnly(start: 16, end: 16, bottom: 16),
//             DefaultTabController(
//               length: isCurrentUserNotEngineer ? 3 : 2,
//               child: Column(
//                 children: <Widget>[
//                   Container(
//                     margin: const EdgeInsets.only(left: 16, right: 16),
//                     decoration: BoxDecoration(color: context.isDark ? AppColor.neutral50 : AppColor.neutral30, borderRadius: BorderRadius.circular(16)),
//                     child: TabBar(
//                       //controller: _tabController,
//                       padding: EdgeInsets.zero,
//                       labelColor: context.isDark ? AppColor.neutral30 : AppColor.neutral60,
//                       unselectedLabelColor: context.isDark ? AppColor.neutral10 : AppColor.neutral20,
//                       unselectedLabelStyle: AppTextStyles.bodyText,
//                       labelStyle: AppTextStyles.bodyText,
//                       indicatorPadding: const EdgeInsets.all(4),
//                       indicator: BoxDecoration(color: context.isDark ? AppColor.neutral60 : Theme.of(context).cardColor, borderRadius: BorderRadius.circular(13)),
//                       onTap: (index) {
//                         // setState(() {});
//                       },
//                       tabs: [
//                         if (isCurrentUserNotEngineer) Tab(text: context.translation.open, height: 57.toScreenHeight),
//                         Tab(text: context.translation.inProgress, height: 57.toScreenHeight),
//                         Tab(text: context.translation.completed, height: 57.toScreenHeight),
//                       ],
//                     ),
//                   ),
//                   8.height,
//                   TabBarView(
//                     children: [
//                       if (isCurrentUserNotEngineer) RequestItemViewList(snapshot.openRequests?.requestsDetails ?? [], snapshot.isOpenLoading),
//                       RequestItemViewList(snapshot.inProgressRequests?.requestsDetails ?? [], snapshot.isInProgressLoading),
//                       RequestItemViewList(snapshot.completedRequests?.requestsDetails ?? [], snapshot.isCompleteLoading),
//                     ],
//                   ).expanded,
//                 ],
//               ),
//             ).expanded,
//           ],
//         );
//       },
//     );
//   }
// }
//
// class ChartData {
//   ChartData(this.x, this.y, this.color);
//
//   final String x;
//   final double y;
//   final Color color;
// }
//
//

import 'package:flutter/material.dart';
import 'package:pie_chart/pie_chart.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/dashboard_latest/dashboard_provider.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';

import '../../controllers/providers/api/user_provider.dart';
import '../../models/enums/user_types.dart';

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

  @override
  State<ProgressFragment> createState() => _ProgressFragmentState();
}

class _ProgressFragmentState extends State<ProgressFragment> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;
  late Animation<double> _scaleAnimation;
  late UserProvider _userProvider;

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

    _controller = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: const Interval(0.0, 0.6, curve: Curves.easeIn),
    ));

    _scaleAnimation = Tween<double>(
      begin: 0.92,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: const Interval(0.0, 0.8, curve: Curves.easeOutCubic),
    ));

    _controller.forward();
  }

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

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    bool isCurrentUserIsNurse = (_userProvider.user?.type == UsersTypes.normal_user);
    return Consumer<DashBoardProvider>(
      builder: (context, snapshot, _) {
        int total = 0;
        List<ChartData> chartData = [];
        if (isCurrentUserIsNurse) {
          total = (snapshot.dashboardCount?.data?.countComplete ?? 0) + (snapshot.dashboardCount?.data?.countInprogress ?? 0) + (snapshot.dashboardCount?.data?.countOpen ?? 0);
          chartData = [
            ChartData('Open', snapshot.dashboardCount?.data?.countOpen?.toDouble() ?? 0.0, AppColor.openChartColor, "dashboard/open_icon"),
            ChartData('In Progress', snapshot.dashboardCount?.data?.countInprogress?.toDouble() ?? 0.0, AppColor.inProgressChartColor, "dashboard/inprogress_icon"),
            ChartData('Acknowledged', snapshot.dashboardCount?.data?.countComplete?.toDouble() ?? 0.0, AppColor.completeChartColor, "dashboard/completed_icon"),
          ];
        } else if (_userProvider.isQualityUser) {
          total = (snapshot.dashboardCount?.data?.countClose ?? 0) + (snapshot.dashboardCount?.data?.countInprogress ?? 0) + (snapshot.dashboardCount?.data?.countOpen ?? 0);
          chartData = [
            ChartData('Open', snapshot.dashboardCount?.data?.countOpen?.toDouble() ?? 0.0, AppColor.openChartColor, "dashboard/open_icon"),
            ChartData('In Progress', snapshot.dashboardCount?.data?.countInprogress?.toDouble() ?? 0.0, AppColor.inProgressChartColor, "dashboard/inprogress_icon"),
            ChartData('Closed', snapshot.dashboardCount?.data?.countComplete?.toDouble() ?? 0.0, AppColor.completeChartColor, "dashboard/completed_icon"),
          ];
        } else if (_userProvider.isHouseKeeper) {
          total = (snapshot.dashboardCount?.data?.countClose ?? 0) + (snapshot.dashboardCount?.data?.countInprogress ?? 0) + (snapshot.dashboardCount?.data?.countOpen ?? 0);
          chartData = [
            ChartData('In Progress', snapshot.dashboardCount?.data?.countInprogress?.toDouble() ?? 0.0, AppColor.inProgressChartColor, "dashboard/inprogress_icon"),
            ChartData('Completed', snapshot.dashboardCount?.data?.countClose?.toDouble() ?? 0.0, AppColor.completeChartColor, "dashboard/completed_icon"),
          ];
        } else {
          total = (snapshot.dashboardCount?.data?.countComplete ?? 0) + (snapshot.dashboardCount?.data?.countInprogress ?? 0) + (snapshot.dashboardCount?.data?.countOpen ?? 0);
          chartData = [
            ChartData('Open', snapshot.dashboardCount?.data?.countOpen?.toDouble() ?? 0.0, AppColor.openChartColor, "dashboard/open_icon"),
            ChartData('In Progress', snapshot.dashboardCount?.data?.countInprogress?.toDouble() ?? 0.0, AppColor.inProgressChartColor, "dashboard/inprogress_icon"),
            ChartData('Completed', snapshot.dashboardCount?.data?.countComplete?.toDouble() ?? 0.0, AppColor.completeChartColor, "dashboard/completed_icon"),
          ];
        }

        return FadeTransition(
          opacity: _fadeAnimation,
          child: ScaleTransition(
            scale: _scaleAnimation,
            child: Column(
              children: [
                AspectRatio(
                  aspectRatio: (359.toScreenWidth / 214.toScreenWidth),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "Work Order Status".addTranslation,
                        style: AppTextStyles.heading4.copyWith(color: AppColor.headingTextColor(context)),
                      ),
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: [
                          for (int i = 0; i < chartData.length; i++)
                            Row(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Container(
                                  height: 6,
                                  width: 6,
                                  decoration: BoxDecoration(color: chartData[i].color, borderRadius: BorderRadius.circular(1)),
                                ),
                                4.width,
                                Text(chartData[i].x, style: AppTextStyles.textStyle9.copyWith(color: AppColor.text9Color(context))),
                              ],
                            )
                        ],
                      ),
                      8.height,
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        spacing: 60.toScreenWidth,
                        children: [
                          Expanded(
                            flex: 3,
                            child: Center(
                              child: AspectRatio(
                                aspectRatio: 1,
                                child: PieChart(
                                  dataMap: {for (var v in chartData) v.x: v.y},
                                  animationDuration: const Duration(milliseconds: 750),
                                  chartLegendSpacing: 0,
                                  chartRadius: MediaQuery.of(context).size.width * 0.35,
                                  colorList: chartData.map((element) => element.color).toList(),
                                  initialAngleInDegree: 270,
                                  chartType: ChartType.ring,
                                  ringStrokeWidth: 32.toScreenWidth,
                                  legendOptions: LegendOptions(
                                    showLegendsInRow: true,
                                    legendPosition: LegendPosition.top,
                                    showLegends: false,
                                    legendTextStyle: AppTextStyles.textStyle9,
                                  ),
                                  chartValuesOptions: ChartValuesOptions(
                                    showChartValueBackground: true,
                                    chartValueBackgroundColor: const Color(0xff226187).withValues(alpha: .75),
                                    chartValueStyle: AppTextStyles.tinyFont2.copyWith(height: 1.5, color: Colors.white),
                                    showChartValues: true,
                                    showChartValuesInPercentage: true,
                                    showChartValuesOutside: true,
                                    decimalPlaces: 0,
                                  ),
                                ).toShimmer(isShow: snapshot.isAllCountLoading, radius: 250, context: context),
                              ),
                            ).paddingOnly(top: 16, bottom: 16),
                          ),
                          Expanded(
                            flex: 2,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                for (int i = 0; i < chartData.length; i++)
                                  Row(
                                    spacing: 16.toScreenWidth,
                                    children: [
                                      chartData[i].icon.toSvgAsset(height: 26, width: 26, color: chartData[i].color).toShimmer(isShow: snapshot.isAllCountLoading, context: context),
                                      Expanded(
                                        child: Column(
                                          spacing: 4.toScreenHeight,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(chartData[i].x, style: AppTextStyles.textStyle9.copyWith(color: AppColor.text9Color(context)))
                                                .toShimmer(isShow: snapshot.isAllCountLoading, context: context),
                                            Text("${chartData[i].y.toInt()}", style: AppTextStyles.bodyText.copyWith(color: AppColor.headingTextColor(context)))
                                                .toShimmer(isShow: snapshot.isAllCountLoading, context: context),
                                          ],
                                        ),
                                      )
                                    ],
                                  )
                              ],
                            ).paddingOnly(top: 4, bottom: 4),
                          ),
                        ],
                      ).expanded,
                    ],
                  ).toShadowContainer(context, borderRadius: 20, paddingObject: const EdgeInsets.symmetric(horizontal: 24, vertical: 16)),
                ),
              ],
            ).paddingOnly(start: 16, end: 16),
          ),
        );
      },
    );
  }
}

class ChartData {
  ChartData(this.x, this.y, this.color, this.icon);

  final String x;
  final double y;
  final Color color;
  final String icon;
}
