import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';

class DataDisplayPage extends StatefulWidget {
  @override
  _DataDisplayPageState createState() => _DataDisplayPageState();
}

class _DataDisplayPageState extends State<DataDisplayPage> {
  final databaseRef = FirebaseDatabase.instance.reference();
  List<Map<String, dynamic>> dataList = [];

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  void fetchData() {
    DatabaseReference reference = databaseRef.child('data-listrik');
    reference.once().then((DatabaseEvent event) {
      DataSnapshot snapshot = event.snapshot;
      Map<dynamic, dynamic>? data = snapshot.value as Map<dynamic, dynamic>?;

      if (data != null) {
        data.forEach((key, value) {
          setState(() {
            dataList.add({
              "datetime": value["dateTime"],
              "voltage": value["voltage"],
              "current": value["current"],
              "power": value["power"],
              "energy": value["energy"],
              "va": value["va"],
              "frequency": value["frequency"],
              "pf": value["pf"]
            });
          });
        });

        // Sort dataList by datetime
        dataList.sort((a, b) => a["datetime"].compareTo(b["datetime"]));
      }
    }).catchError((error) {
      // Handle errors here
      print("Error fetching data: $error");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Data Listrik'),
      ),
      body: dataList.isEmpty
          ? Center(child: CircularProgressIndicator())
          : SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: SingleChildScrollView(
                child: DataTable(
                  columnSpacing: 10,
                  dataRowHeight: 40,
                  columns: [
                    DataColumn(label: Text('No.')),
                    DataColumn(label: Text('Datetime')),
                    DataColumn(label: Text('Voltage (V)')),
                    DataColumn(label: Text('Current (A)')),
                    DataColumn(label: Text('Power (W)')),
                    DataColumn(label: Text('Energy (kWh)')),
                    DataColumn(label: Text('VA')),
                    DataColumn(label: Text('Frequency (Hz)')),
                    DataColumn(label: Text('Pf')),
                  ],
                  rows: dataList
                      .asMap()
                      .entries
                      .map((entry) => DataRow(cells: [
                            DataCell(Text((entry.key + 1).toString())),
                            DataCell(Text(entry.value['datetime'].toString())),
                            DataCell(Text(entry.value['voltage'].toString())),
                            DataCell(Text(entry.value['current'].toString())),
                            DataCell(Text(entry.value['power'].toString())),
                            DataCell(Text(entry.value['energy'].toString())),
                            DataCell(Text(entry.value['va'].toString())),
                            DataCell(Text(entry.value['frequency'].toString())),
                            DataCell(Text(entry.value['pf'].toString())),
                          ]))
                      .toList(),
                ),
              ),
            ),
    );
  }
}
