import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:sfm_app/feature/device_log/device_logs_model.dart';
import 'package:sfm_app/product/utils/date_time_utils.dart';

Widget sharedLineChart(String chartName, List<SensorLogs> sensors) {
  return LineChart(
    LineChartData(
      minX: 0,
      minY: 0,
      maxY: 4000,
      titlesData: FlTitlesData(
        show: true,
        topTitles: const AxisTitles(
          sideTitles: SideTitles(
            showTitles: false,
          ),
        ),
        rightTitles: const AxisTitles(
          sideTitles: SideTitles(
            showTitles: false,
          ),
        ),
        bottomTitles: AxisTitles(
          axisNameSize: 20,
          axisNameWidget: Text(
            chartName,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        leftTitles: const AxisTitles(
          sideTitles: SideTitles(
            showTitles: false,
          ),
        ),
      ),
      lineTouchData: LineTouchData(
        touchTooltipData: LineTouchTooltipData(
          tooltipBgColor: Colors.grey.withValues(alpha: 0.3),
          getTooltipItems: (List<LineBarSpot> touchedSpots) {
            return touchedSpots.map((spot) {
              final index = spot.x.toInt();
              final sensorData = sensors[index];
              return LineTooltipItem(
                'Time: ${DateTimeUtils.instance.convertCurrentMillisToDateTimeString(sensorData.time!)}\nValue: ${(sensorData.value! / 1000).toDouble()}V',
                const TextStyle(),
              );
            }).toList();
          },
        ),
        handleBuiltInTouches: true,
      ),
      lineBarsData: [
        LineChartBarData(
          color: Colors.green.withValues(alpha: 0.8),
          barWidth: 5,
          curveSmoothness: 0.35,
          spots: sensors
              .asMap()
              .entries
              .map(
                (entry) => FlSpot(
                  entry.key.toDouble(),
                  entry.value.value!.toDouble(),
                ),
              )
              .toList(),
          isCurved: true,
          dotData: const FlDotData(
            show: false,
          ),
          belowBarData: BarAreaData(
            show: true,
            color: Colors.green.withValues(alpha: 0.2),
          ),
        )
      ],
      gridData: const FlGridData(show: false),
      borderData: FlBorderData(
        border: Border(
          top: BorderSide.none,
          right: BorderSide.none,
          left: BorderSide.none,
          bottom: BorderSide(
            color: Colors.black.withValues(alpha: 0.7),
          ),
        ),
      ),
    ),
  );
}
