import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:real_time_chart/real_time_chart.dart';

import '../business/utils/get_cpu_usage_percentage.dart';
import '../business/service/memory_service.dart';

class SystemResourcesScreen extends ConsumerWidget {
  const SystemResourcesScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final totalMemory = ref.watch(memoryServiceProvider);
    final freeMemory = ref.watch(memoryServiceProvider.notifier).freeMemory();

    return SingleChildScrollView(
      child: Center(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 128.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Column(
                    children: [
                      const Text('CPU Usage'),
                      const SizedBox(
                        height: 4,
                      ),
                      RealTimeChart(
                        stream: getCpuUsagePercentage(),
                        maxY: 100,
                        valueDesc: 'Total CPU Usage',
                        valueType: '%',
                      ),
                    ],
                  ),
                  const SizedBox(
                    width: 64,
                  ),
                  Column(
                    children: [
                      const Text('RAM Usage'),
                      const SizedBox(
                        height: 4,
                      ),
                      totalMemory.when(
                        data: (data) => RealTimeChart(
                          stream: freeMemory,
                          maxY: data,
                          valueDesc: 'Used Memory',
                          valueType: 'MiB',
                          maxValueDesc: 'Total Memory',
                          maxValueType: 'MiB',
                        ),
                        error: (error, stackTrace) => Text(error.toString()),
                        loading: () => const SizedBox(
                          height: 200,
                          width: 200,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            if (!Platform.isLinux)
              const Padding(
                padding: EdgeInsets.only(top: 16.0),
                child: Text(
                  'The live monitoring of the system resources is only available on Linux. \n Using random data for demonstration purposes.',
                  textAlign: TextAlign.center,
                ),
              ),
          ],
        ),
      ),
    );
  }
}
