import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:functions/src/features/activity_meter/domain/entities/activity_entity.dart';
import 'package:functions/src/features/activity_meter/presentation/state/activity_meter_view_model.dart';
import 'package:legacy_shared/legacy_shared.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:utils/utils.dart';

class ActivityChartScreen extends ConsumerWidget {

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    // final theme = ref.watch(themePortProvider);

    final state = ref.watch(activityMeterViewModelProvider);

    return PageLayout(
      title: 'Ver tus datos semanales',
      body: SingleChildScrollView(child: Padding(
        padding: EdgeInsets.symmetric(horizontal: SizeUtils.getByScreen(small: 8, big: 6)),
        child: Column(
          children: [
            ChartCard(title: 'Pasos', data: state.weekActivity),
            SizedBox(height: SizeUtils.getByScreen(small: 10, big: 8)),
            ChartCard(title: 'Vueltas al dormir', data: state.weekActivity),
            Text('Los datos que se muestran en los gráficos se actualizan automáticamente cada semana',
              style: TextStyle(
                  fontSize: SizeUtils.getByScreen(small: 13, big: 12),
                  fontWeight: FontWeight.w500
              ),
            )
          ],
        )
      )),
    );
  }
}

class ChartCard extends StatelessWidget {

  final String title;
  final List<ActivityEntity> data;

  const ChartCard({
    required this.title,
    required this.data,
  });

  @override
  Widget build(BuildContext context) {

    final weekDays =  ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
    final mean = data.fold(
      0.0,
      (s, activity) => s + activity.totalSteps/data.length
    ).round();

    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(SizeUtils.getByScreen(small: 16, big: 15))),
      ),
      padding: SizeUtils.getByScreen(
        small: EdgeInsets.symmetric(horizontal: 14, vertical: 18),
        big: EdgeInsets.symmetric(horizontal: 13, vertical: 16),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(title,
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  fontSize: SizeUtils.getByScreen(small: 18, big: 17)
                ),
              ),
              Text(data.isNotEmpty ? data.last.totalSteps.toString() : '0',
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  fontSize: SizeUtils.getByScreen(small: 18, big: 17)
                ),
              ),
            ],
          ),
          SizedBox(height: SizeUtils.getByScreen(small: 8, big: 6)),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text('promedio: $mean'),
              Text('hoy'),
            ],
          ),
          SizedBox(height: SizeUtils.getByScreen(small: 8, big: 6)),
          SizedBox(
            height: SizeUtils.getByScreen(small: 270, big: 260),
            child: BarChart(
              BarChartData(
                barGroups: data.map((activity) =>
                  BarChartGroupData(
                    x: activity.occurredAt.weekday - 1,
                    barRods: [BarChartRodData(
                      toY: activity.totalSteps.toDouble(),
                      color: Color(0xFF588EA5)
                    )]
                  )
                ).toList(),
                titlesData: FlTitlesData(
                  bottomTitles: AxisTitles(
                    axisNameSize: 12,
                    sideTitles: SideTitles(
                      showTitles: true,
                      getTitlesWidget: (double value, TitleMeta meta){
                        String text = weekDays[value.toInt()];
                        return SideTitleWidget(
                          space: 0,
                          meta: meta,
                          child: Container(
                            decoration: BoxDecoration(
                              color: Color(0xFF588EA5),
                              shape: BoxShape.circle
                            ),
                            padding: EdgeInsets.all(4),
                            child: Center(child: Text(text,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.white
                              )
                            ))
                          ),
                        );
                      },
                    ),
                  ),
                  leftTitles: AxisTitles(),
                  topTitles: AxisTitles(),
                  rightTitles: AxisTitles()
                ),
                borderData: FlBorderData(
                  show: false,
                ),
                gridData: FlGridData(
                  drawVerticalLine: false,
                ),
                // maxY: data.fold(10, (s, x) => max(s!, x as double)),
                // minY: 0,
              ),
            ),
          ),
        ],
      ),
    );
  }

}