import 'package:flutter/material.dart';
import 'package:fl_chart/fl_chart.dart';
import '../models/sensor_data.dart';

class ChartWidget extends StatelessWidget {
  final List<SensorData> data;

  ChartWidget({required this.data});

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: 1.5,
      child: BarChart(
        BarChartData(
          barGroups: _createBarGroups(),
          titlesData: FlTitlesData(
            leftTitles: AxisTitles(sideTitles: _buildLeftTitles()),
            bottomTitles: AxisTitles(sideTitles: _buildBottomTitles()),
          ),
          borderData: FlBorderData(show: false),
        ),
      ),
    );
  }

  List<BarChartGroupData> _createBarGroups() {
    return data.asMap().entries.map((entry) {
      final index = entry.key;
      final sensor = entry.value;
      return BarChartGroupData(
        x: index,
        barRods: [
          BarChartRodData(toY: sensor.value.toDouble(), color: Colors.blue),
        ],
      );
    }).toList();
  }

  SideTitles _buildLeftTitles() {
    return SideTitles(
      showTitles: true,
      getTitlesWidget: (value, meta) {
        return Text(value.toString(), style: TextStyle(fontSize: 12));
      },
    );
  }

  SideTitles _buildBottomTitles() {
    return SideTitles(
      showTitles: true,
      getTitlesWidget: (value, meta) {
        if (value.toInt() < data.length) {
          return Text(data[value.toInt()].name, style: TextStyle(fontSize: 12));
        }
        return SizedBox.shrink();
      },
    );
  }
}