import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:piring/bloc/nav/bottom_nav.dart';
import 'package:piring/model/user.dart';
import 'package:piring/profile/profile.dart';

import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<EditProfile> createState() => _EditProfileState();
}

class _EditProfileState extends State<EditProfile> {
  String selectedGender = 'Laki-Laki'; // Default jenis kelamin
  DateTime selectedDate = DateTime.now(); // Default tanggal lahir
  String inputText = '';
  TextEditingController _usernameController = TextEditingController();
  TextEditingController jabatanController = TextEditingController();
  TextEditingController namaController = TextEditingController();
  TextEditingController tanggalLahirController = TextEditingController();
  TextEditingController tinggiBadanController = TextEditingController();
  TextEditingController beratBadanController = TextEditingController();
  TextEditingController alamatController = TextEditingController();
  TextEditingController kecamatanController = TextEditingController();
  TextEditingController kabupatenController = TextEditingController();
  TextEditingController provinsiController = TextEditingController();
  TextEditingController jenisKelaminController = TextEditingController();
  TextEditingController noTelpController = TextEditingController();
  TextEditingController emailController = TextEditingController();
  TextEditingController umurController = TextEditingController();

  String? _validateNotEmpty(String? value) {
    if (value == null || value.isEmpty) {
      return 'Harus diisi';
    }
    return null; // Data valid
  }

  XFile? _imageFile;
  Future<void> _getImageFromGallery() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      setState(() {
        _imageFile = pickedFile;
      });

      // Simpan path gambar yang dipilih
      _saveImagePath(pickedFile.path);
    }
  }

  Future<void> _saveImagePath(String imagePath) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('profile_image', imagePath);
  }

  Future<void> loadProfileImage() async {
    final prefs = await SharedPreferences.getInstance();
    final imagePath = prefs.getString('profile_image');

    if (imagePath != null) {
      setState(() {
        _imageFile = XFile(imagePath);
      });
    }
  }

  final scaffoldKey = GlobalKey<ScaffoldState>();
  int Id = 0; // Awalnya set ke 0 atau nilai default lainnya
  String Nama = '';
  String username = '';
  String email = '';
  String notelp = '';
  String tinggi = '';
  String berat = '';
  String jekel = '';
  String tglLahir = '';
  String jabatan = '';
  String umur = '';
  String alamat = '';
  String kecamatan = '';
  String kabupaten = '';
  String provinsi = '';

  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(() {
        Id = userData.idUser; // Mengambil langsung nilai idUser dari userData
        Nama = userData.nama;
        username = userData.username;
        email = userData.email;
        notelp = userData.noTelp;
        tinggi = userData.tinggiBadan;
        berat = userData.beratBadan;
        jekel = userData.jekel;
        tglLahir = userData.tglLahir;
        jabatan = userData.jabatan;
        umur = userData.umur;
        alamat = userData.alamat;
        kecamatan = userData.kecamatan;
        kabupaten = userData.kabupaten;
        provinsi = userData.provinsi;
        _usernameController.text = username;
        jabatanController.text = jabatan;
        tanggalLahirController.text = tglLahir;
        emailController.text = email;
        noTelpController.text = notelp;
        tinggiBadanController.text = tinggi;
        beratBadanController.text = berat;
        selectedGender = jekel;
        umurController.text = umur;
        alamatController.text = alamat;
        kecamatanController.text = kecamatan;
        kabupatenController.text = kabupaten;
        provinsiController.text = provinsi;
        print(Id);
      });
    }
  }

  String clientId = "PKL2023";
  String clientSecret = "PKLSERU";
  String tokenUrl = "https://isipiringku.esolusindo.com/api/Token/token";
  String accessToken = "";

  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');
    }
  }

  void Updateprofile() async {
    final apiUrl =
        'https://isipiringku.esolusindo.com/api/UpdateProfil/UpdateProfil';

    final Map<String, dynamic> data = {
      'id_user': Id,
      'username': username,
      'jabatan': jabatanController.text,
      'nama': Nama,
      'tgl_lahir': tanggalLahirController.text,
      'tinggi_badan': tinggiBadanController.text,
      'berat_badan': beratBadanController.text,
      'alamat': alamatController.text,
      'kecamatan': kecamatanController.text,
      'kabupaten': kabupatenController.text,
      'provinsi': provinsiController.text,
      'jekel': selectedGender,
      'no_telp': noTelpController.text,
      'email': emailController.text,
      'umur': umurController.text,
    };

    try {
      final response = await http.post(
        Uri.parse(apiUrl),
        body: json.encode(data),
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $accessToken', // Menggunakan token OAuth2
        },
      );

      if (response.statusCode == 200) {
        // Update berhasil, lakukan sesuatu di sini
        print('Update berhasil');
        print(response.body);
        UserData updatedProfile = UserData(
          idUser: Id,
          username: username,
          jabatan: jabatan,
          nama: Nama,
          tglLahir: tanggalLahirController.text,
          tinggiBadan: tinggi,
          beratBadan: berat,
          alamat: alamat,
          kecamatan: kecamatan,
          kabupaten: kabupaten,
          provinsi: provinsi,
          jekel: selectedGender,
          noTelp: notelp,
          email: email,
          umur: umur,
          tglDaftar: '',
        );

        saveUserProfile(updatedProfile);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => Profile(),
          ),
        );
      } else {
        // Update gagal, tampilkan pesan kesalahan atau lakukan sesuatu yang sesuai
        print('Update gagal. Status code: ${response.statusCode}');
      }
    } catch (error) {
      // Terjadi kesalahan dalam proses Update
      print('Terjadi kesalahan: $error');
    }
  }

  Future<void> saveUserProfile(UserData updateprofile) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('user_data', json.encode(updateprofile.toJson()));

    // Setel nilai model User sesuai perubahan
    username = updateprofile.username;
    email = updateprofile.email;
    notelp = updateprofile.noTelp;
    tinggi = updateprofile.tinggiBadan;
    berat = updateprofile.beratBadan;
    selectedGender = updateprofile.jekel;
    tglLahir = updateprofile.tglLahir;
    jabatan = updateprofile.jabatan;
    umur = updateprofile.umur;
    alamat = updateprofile.alamat;
    kecamatan = updateprofile.kecamatan;
    kabupaten = updateprofile.kabupaten;
    provinsi = updateprofile.provinsi;
    // dan set nilai-nilai lain sesuai kebutuhan
  }

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

  @override
  void dispose() {
    // Hapus controller ketika widget tidak lagi digunakan
    _usernameController.dispose();
    jabatanController.dispose();
    umurController.dispose();
    emailController.dispose();
    tinggiBadanController.dispose();
    beratBadanController.dispose();
    tanggalLahirController.dispose();
    jenisKelaminController.dispose();
    alamatController.dispose();
    kecamatanController.dispose();
    kabupatenController.dispose();
    provinsiController.dispose();
    noTelpController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomNavBar(selected: 4),
      body: SingleChildScrollView(
        child: Stack(
          children: [
            Container(
              height: 130,
              width: double.infinity,
              decoration: const BoxDecoration(color: Colors.amber),
            ),
            SafeArea(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 15.0),
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  child: Stack(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Padding(padding: EdgeInsets.only(top: 64)),
                          SizedBox(height: 20),
                          Center(
                            child: Container(
                              width: MediaQuery.of(context).size.height * 0.4,
                              height: 30,
                              decoration: BoxDecoration(
                                color: const Color.fromARGB(255, 98, 182, 250),
                                borderRadius: BorderRadius.circular(30),
                                boxShadow: kElevationToShadow[1],
                              ),
                              padding: const EdgeInsets.symmetric(
                                horizontal: 5,
                                vertical: 0,
                              ),
                              child: Center(
                                child: Text(
                                  'EditProfile',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          SizedBox(height: 10),
                          Container(
                            alignment: Alignment.topCenter,
                            child: GestureDetector(
                              onTap: () {
                                print("Tapped on circle image");
                                _getImageFromGallery();
                              },
                              child: Container(
                                width: 120,
                                height: 120,
                                clipBehavior: Clip.antiAlias,
                                decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                ),
                                child: _imageFile != null
                                    ? Image.file(
                                        File(_imageFile!.path),
                                        fit: BoxFit.cover,
                                      )
                                    : Icon(
                                        Icons.camera_alt,
                                        size: 40.0,
                                        color: Colors.orange,
                                      ),
                              ),
                            ),
                          ),
                          TextFormField(
                            decoration: InputDecoration(labelText: 'Username'),
                            controller: _usernameController,
                            onChanged: (value) {
                              setState(() {
                                // Perbarui nilai variabel username saat pengguna mengubah input
                                username = value;
                              });
                            },
                          ),
                          SizedBox(height: 10),
                          Row(
                            children: [
                              Expanded(
                                child: TextFormField(
                                  decoration:
                                      InputDecoration(labelText: 'Email'),
                                  controller: emailController,
                                  onChanged: (value) {
                                    setState(() {
                                      email = value;
                                    });
                                  },
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TextFormField(
                                  keyboardType: TextInputType.number,
                                  decoration: InputDecoration(
                                      labelText: 'Nomor Telepon'),
                                  controller: noTelpController,
                                  onChanged: (value) {
                                    setState(() {
                                      notelp = value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Row(
                            children: [
                              Expanded(
                                child: TextFormField(
                                  keyboardType: TextInputType.number,
                                  decoration: InputDecoration(
                                      labelText: "Tinggi Badan"),
                                  controller: tinggiBadanController,
                                  onChanged: (value) {
                                    setState(() {
                                      tinggi = value;
                                    });
                                  },
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TextFormField(
                                  keyboardType: TextInputType.number,
                                  decoration:
                                      InputDecoration(labelText: 'Berat Badan'),
                                  controller: beratBadanController,
                                  onChanged: (value) {
                                    setState(() {
                                      berat = value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 10),
                          Row(
                            children: [
                              Expanded(
                                child: DropdownButtonFormField<String>(
                                  decoration: InputDecoration(
                                      labelText: 'Jenis Kelamin',
                                      hintText: 'Jenis Kelamin'),
                                  value: selectedGender,
                                  onChanged: (value) {
                                    // Tambahkan kode untuk menangani perubahan jenis kelamin
                                    setState(() {
                                      selectedGender = value!;
                                    });
                                  },
                                  items: ['Laki-Laki', 'Perempuan']
                                      .map((String value) {
                                    return DropdownMenuItem<String>(
                                      value: value,
                                      child: Text(value),
                                    );
                                  }).toList(),
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TextFormField(
                                  decoration: InputDecoration(
                                      labelText: 'Tanggal Lahir'),
                                  controller: tanggalLahirController,
                                  onTap: () async {
                                    // Tambahkan kode untuk menampilkan date picker
                                    final DateTime? pickedDate =
                                        await showDatePicker(
                                      context: context,
                                      initialDate: selectedDate,
                                      firstDate: DateTime(1900),
                                      lastDate: DateTime.now(),
                                    );
                                    if (pickedDate != null &&
                                        pickedDate != selectedDate) {
                                      setState(() {
                                        selectedDate = pickedDate;
                                        tanggalLahirController.text =
                                            DateFormat('yyyy-MM-dd')
                                                .format(selectedDate);
                                      });
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 10),
                          Row(
                            children: [
                              Expanded(
                                child: TextFormField(
                                  decoration:
                                      InputDecoration(labelText: 'Pekerjaan'),
                                  controller: jabatanController,
                                  onChanged: (value) {
                                    setState(() {
                                      jabatan = value;
                                    });
                                  },
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TextFormField(
                                  keyboardType: TextInputType.number,
                                  decoration:
                                      InputDecoration(labelText: 'Umur'),
                                  controller: umurController,
                                  onChanged: (value) {
                                    setState(() {
                                      umur = value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 10),
                          Row(
                            children: [
                              Expanded(
                                child: TextFormField(
                                  decoration:
                                      InputDecoration(labelText: 'Alamat'),
                                  controller: alamatController,
                                  onChanged: (value) {
                                    setState(() {
                                      alamat = value;
                                    });
                                  },
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TextFormField(
                                  decoration:
                                      InputDecoration(labelText: 'Kecamatan'),
                                  controller: kecamatanController,
                                  onChanged: (value) {
                                    setState(() {
                                      kecamatan = value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 10),
                          Row(
                            children: [
                              Expanded(
                                child: TextFormField(
                                  decoration:
                                      InputDecoration(labelText: 'Kabupaten'),
                                  controller: kabupatenController,
                                  onChanged: (value) {
                                    setState(() {
                                      kabupaten = value;
                                    });
                                  },
                                ),
                              ),
                              SizedBox(width: 10),
                              Expanded(
                                child: TextFormField(
                                  decoration:
                                      InputDecoration(labelText: 'Provinsi'),
                                  controller: provinsiController,
                                  onChanged: (value) {
                                    setState(() {
                                      provinsi = value;
                                    });
                                  },
                                ),
                              ),
                            ],
                          ),
                          SizedBox(
                            height: 5,
                          ),
                          Center(
                              child: Container(
                            child: ElevatedButton(
                              onPressed: () {
                                Updateprofile();
                              },
                              child: Text('Simpan'),
                            ),
                          ))
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
