// 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/model/nutrisi.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/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:intl/intl.dart';

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

  @override
  State<TesAlert2> createState() => _TesAlert2State();
}

class _TesAlert2State extends State<TesAlert2> {
  List<Map<String, dynamic>> tes1 = [];

  List<dynamic> jadwal = [];
  String getkalori = '';
  String getriwayat = '';
  String Id = '';
  String umur = '';
  String jekel = '';
  String ceknutrisi = '';

  final formattedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());

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

  Future<void> tes12() async {
    final urlnutrisi = Uri.parse(
        'https://isipiringku.esolusindo.com/api/Makanan/konsumsi?id_user=65&waktu=2023-10-29&keterangan=Sarapan');
    final response = await http.get(urlnutrisi);

    if (response.statusCode == 200) {
      final decodedResponse = json.decode(response.body);
      setState(() {
        tes1 = List<Map<String, dynamic>>.from(decodedResponse['response']);
      });

      // Tampilkan dialog dengan grafik pie setelah data diambil
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Grafik Konsumsi Makanan'),
            content: Container(
              height: 300,
              width: 300,
              child: SfCircularChart(
                series: <CircularSeries>[
                  PieSeries<Map<String, dynamic>, String>(
                    dataSource: tes1,
                    xValueMapper: (datum, _) => 'nama_makanan',
                    yValueMapper: (datum, _) {
                      final karbohidrat = double.parse(datum['karbohidrat']);
                      final protein = double.parse(datum['protein']);
                      final lemak = double.parse(datum['lemak']);
                      final besi = double.parse(datum['besi']);
                      final vitamina = double.parse(datum['vitamina']);
                      final vitaminc = double.parse(datum['vitaminc']);

                      // Misalnya, Anda ingin menampilkan karbohidrat, Anda dapat mengembalikan nilai berikut:
                      return karbohidrat;
                    },
                  ),
                ],
              ),
            ),
            actions: <Widget>[
              ElevatedButton(
                child: Text('Tutup'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    } else {
      throw Exception('Gagal mengambil data dari API');
    }
  }

  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';
        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: 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']);
          int 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';
          }
        }
      }
    } 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) {
    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,
                          ),
                          ElevatedButton(
                              onPressed: () {
                                tes12();
                              },
                              child: Text('tes')),
                          Container(
                            height: 400,
                            child: ListView.builder(
                              itemCount: jadwal.length,
                              itemBuilder: (context, index) {
                                final item = jadwal[index];
                                return Card(
                                  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']),
                                                ));
                                          },
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                )),
          ),
        ]),
      ),
    );
  }
}
