import 'package:agrilink_vocpro/core/constant/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class PhIndicator extends StatelessWidget {
  final double phValue; // Nilai pH yang ditampilkan (misal 3.5 atau 6.7)

  const PhIndicator({super.key, required this.phValue});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Center(
          child: Text(
            'pH : $phValue',
            style: AppTheme.headline1,
          ),
        ),
        SizedBox(height: 16.h),
        SizedBox(
          height: 80.h,
          child: Stack(
            alignment: Alignment.center,
            children: [
              CustomPaint(
                size: Size(300.w, 30.h), // Ukuran bar
                painter: PhBarPainter(),
              ),
              Positioned(
                top: 48.h,
                left: calculatePointerPosition(
                    phValue, 300), // Hitung posisi pointer
                child: const Icon(
                  Icons.arrow_drop_up,
                  size: 40,
                  color: Colors.black, // Warna pointer
                ),
              ),
              const Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('0'),
                    Text('7'),
                    Text('14'),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // Fungsi untuk menghitung posisi pointer berdasarkan nilai pH
  double calculatePointerPosition(double phValue, double barWidth) {
    // Nilai pH umumnya antara 0 dan 14, sesuaikan dengan lebar bar
    double normalizedPh = phValue / 14; // Normalisasi nilai pH (-7 hingga 7)
    return normalizedPh * barWidth;
  }
}

class PhBarPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // Buat gradasi dari biru ke merah
    const gradient = LinearGradient(
      colors: [Colors.blue, Colors.orange, Colors.red],
      stops: [0.0, 0.5, 1.0], // Set stop untuk 0, 7, 14 (pH)
    );

    // Buat rect untuk menggambar gradasi
    final rect = Rect.fromLTWH(0, 0, size.width, size.height);
    final paint = Paint()..shader = gradient.createShader(rect);

    // Gambar rect dengan gradasi
    canvas.drawRect(rect, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
