// ignore_for_file: use_build_context_synchronously

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// import 'package:flutter_icons_plus/flutter_icons_plus.dart';
// import 'package:piring/bloc/nav/bottom_nav.dart';
// import 'package:piring/kalori/tambahbismillah.dart';
// import 'package:piring/kalori/tes2.dart';
// import 'package:piring/model/nutrisi.dart';
// import 'package:piring/model/piechart.dart';
// import 'package:piring/model/piechartlagi.dart';
// import 'package:piring/model/user.dart';
import 'package:piring_baru/bloc/nav/bottom_nav.dart';
import 'package:piring_baru/kalori/tambahbismillah.dart';
import 'package:piring_baru/model/nutrisi.dart';
import 'package:piring_baru/model/piechartlagi.dart';
import 'package:piring_baru/model/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:intl/intl.dart';

class RevKalori extends StatefulWidget {
  const RevKalori({super.key});

  @override
  State<RevKalori> createState() => _RevKaloriState();
}

class _RevKaloriState extends State<RevKalori> {
  List<dynamic> jadwal = [];
  List<Map<String, dynamic>> KalIni = [];
  List<dynamic> data = [];
  String getkalori = '';
  String getriwayat = '';
  String Id = '';
  String umur = '';
  String jekel = '';
  String ceknutrisi = '';
  int kebutuhanKalori = 0;
  String KaloriHariIni = '';
  double totalEnergi = 0.0;
  String totalKalori = '';
  final formattedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
  String fetch1 = '';
  String fetch2 = '';

  @override
  void initState() {
    super.initState();
    fetchjadwal();
    loadUserData();
  }

  Future<void> fetchData1() async {
    final uri = Uri.parse(fetch1);
    final response = await http.get(uri);
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      setState(() {
        totalKalori = jsonData['data']['total'];
      });
    } else {
      throw Exception('Gagal memuat data');
    }
  }

  Future<void> fetchData() async {
    final uri = Uri.parse(fetch2);
    final response = await http.get(uri);
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      setState(() {
        data = jsonData['response'];
        // Hitung total energi saat mengambil data
        totalEnergi =
            data.fold(0, (sum, item) => sum + double.parse(item['energi']));
      });
    } else {
      throw Exception('Gagal memuat data');
    }
  }

  Future<void> loadUserData() async {
    final prefs = await SharedPreferences.getInstance();
    final userDataString = prefs.getString('user_data');

    if (userDataString != null) {
      final userData = UserData.fromJson(json.decode(userDataString));

      setState(() {
        Id = userData.idUser.toString();
        umur = userData.umur;
        jekel = userData.jekel;
        getriwayat =
            'https://isipiringku.esolusindo.com/api/Makanan/konsumsi?id_user=$Id&waktu=$formattedDate&keterangan=';
        getkalori =
            'https://isipiringku.esolusindo.com/api/Kalori/kalori?umur=$umur&jekel=$jekel';
        ceknutrisi =
            'https://isipiringku.esolusindo.com/api/Kalori/kalori?umur=$umur&jekel=$jekel';
        KaloriHariIni =
            'https://isipiringku.esolusindo.com/api/Makanan/allKonsumsi?id_user=$Id';
        fetch1 =
            'https://isipiringku.esolusindo.com/api/Kalori/kalori?umur=$umur&jekel=$jekel';
        fetch2 =
            'https://isipiringku.esolusindo.com/api/Makanan/allKonsumsi?id_user=$Id';

        fetchData1();
        fetchData();
        print(getkalori);
        print(getriwayat);
        print(ceknutrisi);
        print(formattedDate);
      });
    }
  }

  Future<void> fetchjadwal() async {
    final uri =
        Uri.parse('https://isipiringku.esolusindo.com/api/JadwalMakan/jadwal');
    final response = await http.get(uri);
    if (response.statusCode == 200) {
      final jsonjadwal = json.decode(response.body);
      setState(() {
        jadwal = jsonjadwal['response'];
      });
    } else {
      throw Exception('Failed to load jadwal');
    }
  }

  // Fungsi untuk menampilkan data riwayat dari API dalam AlertDialog
  void _showRiwayatDialog(String keterangan) async {
    final apiUrl = '$getriwayat$keterangan';
    print('apiUrlshowriwayat=$apiUrl');

    final response = await http.get(Uri.parse(apiUrl));

    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body);
      final List<dynamic> responseList = jsonData['response'];

      if (responseList.isEmpty) {
        // Jika responseList kosong, tampilkan pesan "Data kosong nih" dan gambar dari 'assets/images/gemuk.gif'
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              backgroundColor: const Color.fromARGB(255, 199, 218, 228),
              title: Text("Riwayat $keterangan"),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset('assets/images/gemuk.gif'),
                  Text(
                    'Yahh Data kosong nih, yuk tambah dulu ',
                    textAlign: TextAlign.center,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                ],
              ),
              actions: <Widget>[
                TextButton(
                  child: Text("Tutup"),
                  onPressed: () {
                    Navigator.of(context).pop(); // Tutup dialog
                  },
                ),
              ],
            );
          },
        );
      } else {
        // Membangun pesan untuk ditampilkan dalam AlertDialog
        String makanan = '';
        String energi = '';

        for (var data in responseList) {
          makanan += 'Makanan: ${data['nama_makanan']}\n';
          energi += 'Energi: ${data['kalori']}\n';
        }

        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              backgroundColor: const Color.fromARGB(255, 199, 218, 228),
              title: Text("Riwayat $keterangan"),
              content: SingleChildScrollView(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      makanan,
                      style:
                          TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
                    ),
                    Text(energi,
                        style: TextStyle(
                            fontSize: 10, fontWeight: FontWeight.bold))
                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: Text("Tutup"),
                  onPressed: () {
                    Navigator.of(context).pop(); // Tutup dialog
                  },
                ),
              ],
            );
          },
        );
      }
    } else {
      throw Exception('Failed to load riwayat');
    }
  }

  void _showOptionsDialog(String itemName) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("Pilihan untuk $itemName"),
          actions: <Widget>[
            TextButton(
              child: Text("Analisis"),
              onPressed: () {
                _fetchNutritionData(context, itemName);
              },
            ),
            TextButton(
              child: Text("Tampilkan Riwayat"),
              onPressed: () {
                // Implementasi aksi yang diambil saat tombol "Tampilkan Riwayat" ditekan
                _showRiwayatDialog(itemName);
              },
            ),
          ],
        );
      },
    );
  }

  void _fetchNutritionData(BuildContext context, String ItemName) async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Container(
            width: double.maxFinite,
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  CircularProgressIndicator(),
                  Text("Mengambil data..."),
                ],
              ),
            ),
          ),
        );
      },
    );

    final urlnutrisi = Uri.parse('$getriwayat$ItemName');
    final response = await http.get(urlnutrisi);

    Navigator.pop(context);

    if (response.statusCode == 200) {
      final jsonResponse = json.decode(response.body);
      final List<dynamic> data = jsonResponse['response'];
      if (data.isEmpty) {
        // Menampilkan pesan "Data kosong nih" dan gambar dari 'assets/images/pas.gif'
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Data Kosong"),
              content: Container(
                height: MediaQuery.of(context).size.height * 0.3,
                width: 200,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset('assets/images/pas.gif'),
                    Text('Data kosong nih'),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(); // Tutup dialog
                  },
                  child: Text('Tutup'),
                ),
              ],
            );
          },
        );
      } else {
        int totalEnergi = 0;
        int totalKarbohidrat = 0;
        int totalProtein = 0;
        int totalLemak = 0;
        int totalBesi = 0;
        int totalVitamina = 0;
        int totalVitaminc = 0;

        for (var item in data) {
          NutritionData nutritionData = NutritionData.fromJson(item);
          totalEnergi += nutritionData.energi.toInt();
          totalKarbohidrat += nutritionData.karbohidrat.toInt();
          totalProtein += nutritionData.protein.toInt();
          totalLemak += nutritionData.lemak.toInt();
          totalBesi += nutritionData.besi.toInt();
          totalVitamina += nutritionData.vitamina.toInt();
          totalVitaminc += nutritionData.vitaminc.toInt();
        }

        final kaloriResponse = await http.get(
          Uri.parse(ceknutrisi),
        );

        if (kaloriResponse.statusCode == 200) {
          final kaloriJson = json.decode(kaloriResponse.body);
          final int totalKalori = int.parse(kaloriJson['data']['total']);
          kebutuhanKalori = totalKalori ~/ 3;
          print(kebutuhanKalori);

          String message = '';
          String gambar = '';
          if (totalEnergi < kebutuhanKalori) {
            message = "Yahh Nutrisi kamu kurang nih!";
            gambar = 'assets/images/sakit.gif';
          } else if (totalEnergi > kebutuhanKalori) {
            message = "Yahh, kamu terlalu banyak nih!";
            gambar = 'assets/images/pas.gif';
          } else {
            message = "Nutrisi kamu cukup";
            gambar = 'assets/imagges/gemuk.gif';
          }

          showDialog(
            context: context,
            builder: (context) {
              return Column(
                children: [
                  AlertDialog(
                    backgroundColor: const Color.fromARGB(255, 199, 218, 228),
                    content: Container(
                      height: 150,
                      width: 200,
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Container(
                                child: Column(
                              children: [
                                Center(
                                    child: Text(
                                  message,
                                  style: TextStyle(fontWeight: FontWeight.bold),
                                )),
                                Image.asset(gambar),
                              ],
                            )),
                          ],
                        ),
                      ),
                    ),
                  ),
                  AlertDialog(
                    backgroundColor: const Color.fromARGB(255, 199, 218, 228),
                    content: Container(
                      height: 300,
                      width: 200,
                      child: SingleChildScrollView(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Center(
                              child: Container(
                                height: 200,
                                width: 150,
                                child: SfCircularChart(
                                  series: <CircularSeries>[
                                    PieSeries<Nutritiondetail, String>(
                                      dataSource: [
                                        Nutritiondetail('Karbohidrat',
                                            totalKarbohidrat.toDouble()),
                                        Nutritiondetail(
                                            'Protein', totalProtein.toDouble()),
                                        Nutritiondetail(
                                            'Lemak', totalLemak.toDouble()),
                                        Nutritiondetail(
                                            'Besi', totalBesi.toDouble()),
                                        Nutritiondetail('Vitamin a',
                                            totalVitamina.toDouble()),
                                        Nutritiondetail('Vitamin c',
                                            totalVitaminc.toDouble()),
                                      ],
                                      xValueMapper: (Nutritiondetail data, _) =>
                                          data.nutrient,
                                      yValueMapper: (Nutritiondetail data, _) =>
                                          data.value,
                                    ),
                                  ],
                                  tooltipBehavior:
                                      TooltipBehavior(enable: true),
                                ),
                              ),
                            ),
                            Container(
                              child: Center(
                                child: Text(
                                  'Total Kalori: $totalEnergi',
                                  style: TextStyle(
                                      fontSize: 10,
                                      fontWeight: FontWeight.bold),
                                ),
                              ),
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('Total Karbohidrat: $totalKarbohidrat',
                                    style: TextStyle(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold)),
                                Text('Total Protein: $totalProtein',
                                    style: TextStyle(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('Total Lemak: $totalLemak',
                                    style: TextStyle(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold)),
                                Text('Total Besi: $totalBesi',
                                    style: TextStyle(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text('Total Vitamina: $totalVitamina',
                                    style: TextStyle(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold)),
                                Text('Total Vitaminc: $totalVitaminc',
                                    style: TextStyle(
                                        fontSize: 10,
                                        fontWeight: FontWeight.bold)),
                              ],
                            ),
                            SizedBox(
                              height: 10,
                            ),
                            Center(
                              child: Text('kebutuhan Kalori = $kebutuhanKalori',
                                  style: TextStyle(
                                      fontSize: 10,
                                      fontWeight: FontWeight.bold)),
                            )
                          ],
                        ),
                      ),
                    ),
                    actions: [
                      TextButton(
                        onPressed: () {
                          Navigator.of(context).pop();
                        },
                        child: Text('Tutup'),
                      ),
                    ],
                  ),
                ],
              );
            },
          );
        }
      }
    } else {
      showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('Kesalahan'),
            content: Text('Gagal mengambil data. Silakan coba lagi.'),
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('Tutup'),
              ),
            ],
          );
        },
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentDate = DateTime.now();

    // Melakukan filter berdasarkan tanggal saat ini
    final filteredData = data.where((item) {
      final itemDate = DateTime.parse(item['waktu']);
      return itemDate.isAfter(currentDate.subtract(Duration(days: 1))) &&
          itemDate.isBefore(currentDate.add(Duration(days: 1)));
    }).toList();
    String formattedTotalEnergi = totalEnergi.toStringAsFixed(2);
    return Scaffold(
      bottomNavigationBar: const BottomNavBar(selected: 1),
      body: SingleChildScrollView(
        child: Stack(children: [
          Container(
            height: 130,
            width: double.infinity,
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('assets/images/head2.jpg'),
                    fit: BoxFit.cover)),
          ),
          SafeArea(
            child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 15.0),
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  child: Stack(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Padding(padding: EdgeInsets.only(top: 64)),
                          const SizedBox(height: 20),
                          Center(
                            child: Container(
                              width: MediaQuery.of(context).size.height * 0.4,
                              height: 30,
                              decoration: BoxDecoration(
                                gradient: const LinearGradient(
                                  colors: [
                                    Color.fromARGB(255, 250, 154, 0),
                                    Color.fromARGB(255, 246, 80, 20),
                                    Color.fromARGB(255, 235, 38, 16),
                                  ],
                                ),
                                borderRadius: BorderRadius.circular(30),
                                boxShadow: kElevationToShadow[1],
                              ),
                              padding: const EdgeInsets.symmetric(
                                horizontal: 5,
                                vertical: 0,
                              ),
                              child: const Center(
                                child: Text(
                                  'Kalori Harian',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(
                            height: 14,
                          ),
                          Container(
                              height: 30,
                              child: Row(
                                children: [
                                  Icon(Icons.calendar_month),
                                  SizedBox(
                                    width: 20,
                                  ),
                                  Container(
                                    alignment: Alignment.center,
                                    height: 50,
                                    width: 150,
                                    decoration: BoxDecoration(
                                        color: Colors.orange,
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Text(
                                      formattedDate,
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                          fontSize: 16,
                                          fontWeight: FontWeight.bold,
                                          color: Colors.white),
                                    ),
                                  )
                                ],
                              )),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                children: [
                                  Text(
                                    'Kebutuhan Budget Kalori',
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 13),
                                  ),
                                  Text('$totalKalori',
                                      style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: 13))
                                ],
                              ),
                              Container(
                                height: 40,
                                width: 80,
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
                                  color: Colors.amber,
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                child: Text(
                                  '$formattedTotalEnergi',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 14),
                                ),
                              )
                            ],
                          ),
                          SizedBox(
                            height: 30,
                          ),
                          Container(
                            height: 300,
                            child: ListView.builder(
                              itemCount: jadwal.length,
                              itemBuilder: (context, index) {
                                final item = jadwal[index];
                                return Card(
                                  margin: EdgeInsets.only(bottom: 10),
                                  child: ListTile(
                                    leading: Image.network(item['gambar']),
                                    title: Text(item['nama']),
                                    trailing: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: <Widget>[
                                        IconButton(
                                          icon: Icon(
                                            Icons.info,
                                            color: Colors.blue,
                                          ),
                                          onPressed: () {
                                            _showOptionsDialog(item[
                                                'nama']); // Mengirim item['nama'] ke dialog
                                          },
                                        ),
                                        SizedBox(
                                            width: 20), // Spasi antara ikon
                                        IconButton(
                                          icon: Icon(
                                            Icons.add,
                                            color: Colors.green,
                                          ),
                                          onPressed: () {
                                            Navigator.pushReplacement(
                                                context,
                                                MaterialPageRoute(
                                                  builder: (context) =>
                                                      TambahBismillah(
                                                          nama: item['nama']),
                                                ));
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                )),
          ),
        ]),
      ),
    );
  }
}
