import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
// import 'package:piring/bloc/nav/bottom_nav.dart';
// import 'package:piring/dashboard/dashboard.dart';
// import 'package:piring/model/user.dart';
import 'package:piring_baru/bloc/nav/bottom_nav.dart';
import 'package:piring_baru/dashboard/dashboard.dart';
import 'package:piring_baru/model/user.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<Blood> createState() => _BloodState();
}

class _BloodState extends State<Blood> {
  String clientId = "PKL2023";
  String clientSecret = "PKLSERU";
  String tokenUrl = "https://isipiringku.esolusindo.com/api/Token/token";
  String accessToken = "";
  String Sekarang = DateFormat('dd-MM-yyyy').format(DateTime.now());
  String hariIni = DateFormat('yyyy-MM-dd').format(DateTime.now());
  DateTime _selectedDate = DateTime.now();
  String username = '';
  String Id = '';

  List<Map<String, dynamic>> dataList = [];

  String status = 'belum'; // Awalnya status belum

  void onTambahPressed() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Konfirmasi'),
          content: Text('Apakah Anda yakin dengan pilihan Anda?'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // Tutup dialog
                setState(() {
                  status = 'sudah'; // Ubah status menjadi sudah
                });
                getData();
              },
              child: Text('Ya'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // Tutup dialog
              },
              child: Text('Tidak'),
            ),
          ],
        );
      },
    );
  }

  void onTidakPressed() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Konfirmasi'),
          content: Text('Apakah Anda yakin dengan pilihan Anda?'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // Tutup dialog
                setState(() {
                  status = 'belum'; // Ubah status menjadi sudah
                });
                getData();
              },
              child: Text('Ya'),
            ),
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // Tutup dialog
              },
              child: Text('Tidak'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: _selectedDate,
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null && picked != _selectedDate)
      setState(() {
        _selectedDate = picked;
        print(_selectedDate);
      });
  }

  Future<void> getToken() async {
    try {
      var response = await http.post(
        Uri.parse(tokenUrl),
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: {
          'grant_type': 'client_credentials',
          'client_id': clientId,
          'client_secret': clientSecret,
        },
      );

      if (response.statusCode == 200) {
        Map<String, dynamic> tokenData = jsonDecode(response.body);
        accessToken = tokenData['access_token'];
        print('Token Akses: $accessToken');
      } else {
        print('Gagal mendapatkan token: ${response.statusCode}');
      }
    } catch (e) {
      print('Gagal mendapatkan token: $e');
    }
  }

  Future<void> tambahDataDarah() async {
    const apiUrl = 'https://isipiringku.esolusindo.com/api/Darah/darah';

    String formattedDate = DateFormat('yyyy-MM-dd').format(_selectedDate);

    Map<String, String> data = {
      'id_user': Id,
      'tanggal': formattedDate, // Format the date as a string
      'status': status,
    };

    final response = await http.post(
      Uri.parse(apiUrl),
      body: data,
    );

    if (response.statusCode == 200) {
      print(response.body);
      // Permintaan sukses, Anda dapat menangani respons API di sini jika diperlukan.
      print('Data darah berhasil ditambahkan');
    } else {
      // Gagal menambahkan data, Anda dapat menangani kesalahan di sini jika diperlukan.
      print(
          'Gagal menambahkan data darah. Kode status: ${response.statusCode}');
      print('Respons: ${response.body}');
    }
  }

  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));
      print(userData.nama);

      setState(() {
        username = userData.username;
        Id = userData.idUser.toString();
        // Setelah mendapatkan Id, panggil getData
      });
    }
  }

  Future<Map<String, dynamic>?> getData() async {
    print(Id);

    if (Id.isEmpty) {
      print("Id tidak tersedia.");
      return null;
    }

    String cekDarah =
        'https://isipiringku.esolusindo.com/api/Darah/tambahdarah?id_user=$Id&tanggal=$hariIni';
    print(cekDarah);

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

    if (response.statusCode == 200) {
      final Map<String, dynamic> jsonResponse = json.decode(response.body);
      if (jsonResponse.containsKey("data")) {
        List<dynamic> data = jsonResponse["data"];
        setState(() {
          dataList = List<Map<String, dynamic>>.from(data);
        });
      }

      if (jsonResponse["status"] == 200) {
        // Tampilkan gambar GIF
        showGifAlert();
      } else {
        // Data tidak ditemukan, panggil _tambahDarah
        tambahDataDarah();
      }

      print(response.body);
      return jsonResponse;
    } else {
      throw Exception('Gagal mengambil data dari API');
    }
  }

  void showGifAlert() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(
                'Data Hari Ini Sudah terinput Kembali lagi besok yaa',
                style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 5),
              Image.asset('assets/images/sudahDarah2.gif'),
            ],
          ),
        );
      },
    );
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: const BottomNavBar(
        selected: 2,
      ),
      body: Stack(
        children: [
          Container(
            height: 90,
            width: double.infinity,
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [
                  Color.fromARGB(255, 250, 154, 0),
                  Color.fromARGB(255, 246, 80, 20),
                  Color.fromARGB(255, 235, 38, 16),
                ],
              ),
            ),
          ),
          SafeArea(
            child: Container(
              width: MediaQuery.of(context).size.width,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: Row(
                      children: [
                        const Padding(padding: EdgeInsets.only(left: 10)),
                        Container(
                          decoration: const BoxDecoration(
                            color: Colors.white,
                            shape: BoxShape.circle,
                          ),
                          child: IconButton(
                            icon: const Icon(
                              Icons.arrow_back,
                              color: Colors.orange,
                              size: 25,
                            ),
                            onPressed: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) => const Dashboard()));
                            },
                          ),
                        ),
                        const SizedBox(
                          width: 20,
                        ),
                        Container(
                          child: const Text(
                            'TAMBAH DARAH',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 19,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Center(
                    child: Padding(
                      padding: const EdgeInsets.all(30.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Row(
                            children: [
                              IconButton(
                                icon: const Icon(Icons.calendar_today),
                                onPressed: () {
                                  // _selectDate(
                                  //     context); // Memunculkan date picker
                                },
                              ),
                              const SizedBox(
                                width: 10.0,
                              ),
                              const Text(
                                'Tambah Darah Hari Ini',
                                style: TextStyle(
                                  fontSize: 15,
                                  color: Colors.black,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ],
                          ),
                          // Tambahkan komponen UI lainnya di sini
                          const SizedBox(
                            height:
                                20, // Tambahkan jarak antara teks dan Container
                          ),
                          Container(
                            width: 400, // Lebar container
                            padding: const EdgeInsets.all(
                                16.0), // Padding pada Container
                            decoration: BoxDecoration(
                              color: Colors
                                  .white, // Warna latar belakang Container
                              borderRadius: BorderRadius.circular(
                                  10.0), // Radius sudut sebesar 10
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey
                                      .withOpacity(0.5), // Warna shadow abu-abu
                                  spreadRadius:
                                      5, // Seberapa jauh shadow menyebar
                                  blurRadius: 7, // Tingkat keburaman shadow
                                  offset: const Offset(0, 3), // Posisi shadow
                                ),
                              ],
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  'Tanggal: $Sekarang',
                                  style: const TextStyle(
                                    fontSize: 15,
                                    color: Colors.black,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                SizedBox(
                                  height: 3,
                                ),
                                Text(
                                  username,
                                  style: TextStyle(
                                    fontSize: 15,
                                    color: Colors.deepOrange,
                                  ),
                                ),
                                SizedBox(
                                  height: 3,
                                ),
                                const Text(
                                  'Apakah anda memilikii jadwal meminum pil tambah darah hari ini?',
                                  style: TextStyle(
                                    fontSize: 15,
                                    color: Colors.black,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceAround,
                                  children: [
                                    ElevatedButton(
                                      onPressed: () {
                                        setState(() {
                                          status =
                                              'sudah'; // Ubah status menjadi sudah
                                        });
                                        onTambahPressed();
                                      },
                                      style: ElevatedButton.styleFrom(
                                        primary: Colors.green,
                                      ),
                                      child: const Text('Tambah'),
                                    ),
                                    ElevatedButton(
                                      onPressed: () {
                                        setState(() {
                                          status =
                                              'Belum'; // Ubah status menjadi sudah
                                        });
                                        onTidakPressed();
                                      },
                                      style: ElevatedButton.styleFrom(
                                        primary: Colors.green,
                                      ),
                                      child: const Text('Tidak'),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Container(
                      height: 300,
                      child: ListView.builder(
                          itemCount: dataList.length,
                          itemBuilder: (context, index) {
                            return Card(
                              child: ListTile(
                                title: Text(
                                    'Status: ${dataList[index]['status']}'),
                                subtitle: Text(
                                    'Tanggal: ${dataList[index]['tanggal']}'),
                              ),
                            );
                          }))
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
