import 'dart:ui';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../utils/api_config.dart';
import '../utils/session_manager.dart';

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

  @override
  State<EditProfileScreen> createState() => _EditProfileScreenState();
}

class _EditProfileScreenState extends State<EditProfileScreen> {
  final _formKey = GlobalKey<FormState>();
  
  late TextEditingController _nameController;
  late TextEditingController _usernameController;
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController();

  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: SessionManager.userName);
    _usernameController = TextEditingController(text: SessionManager.userEmail);
  }

  Future<void> _updateProfile() async {
    // 1. Validasi Dasar
    if (!_formKey.currentState!.validate()) return;

    // 2. Cek apakah ada perubahan
    bool isNameChanged = _nameController.text != SessionManager.userName;
    bool isUsernameChanged = _usernameController.text != SessionManager.userEmail;
    bool isPasswordChanged = _passwordController.text.isNotEmpty;

    if (!isNameChanged && !isUsernameChanged && !isPasswordChanged) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text("Tidak ada perubahan yang dilakukan.")),
      );
      return;
    }

    // 3. Validasi Password
    if (isPasswordChanged) {
      if (_passwordController.text != _confirmPasswordController.text) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("Konfirmasi password tidak cocok!")),
        );
        return;
      }
      if (_passwordController.text.length < 5) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text("Password minimal 5 karakter!")),
        );
        return;
      }
    }

    setState(() => _isLoading = true);

    try {
      final response = await http.post(
        Uri.parse("${ApiConfig.baseUrl}/edit_profile.php"),
        body: {
          'id_users': SessionManager.userId.toString(),
          'nama': _nameController.text,
          'username': _usernameController.text,
          'password': _passwordController.text, 
        },
      );

      final data = jsonDecode(response.body);

      if (data['status'] == 'success') {
        SessionManager.saveSession(
          SessionManager.userId!,
          _nameController.text, 
          _usernameController.text,
          SessionManager.userPhoto,
        );
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text("Profil berhasil diperbarui!")),
          );
          Navigator.pop(context, true);
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text(data['message'] ?? "Terjadi kesalahan")),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("Tidak terhubung ke server: $e")),
        );
      }
    }

    if (mounted) setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    final isDark = Theme.of(context).brightness == Brightness.dark;
    
    return Scaffold(
      // Latar belakang gradien agar efek kaca terlihat nyata
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFF3949AB), Color(0xFF00BCD4)],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
        ),
        child: Stack(
          children: [
            SafeArea(
              child: SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 20.0),
                child: Column(
                  children: [
                    const SizedBox(height: 20),
                    // Header Icon
                    Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.2),
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(Icons.manage_accounts, size: 60, color: Colors.white),
                    ),
                    const SizedBox(height: 16),
                    const Text(
                      "Perbarui Profil",
                      style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold, color: Colors.white),
                    ),
                    const Text(
                      "Kelola informasi akun Anda",
                      style: TextStyle(fontSize: 14, color: Colors.white70),
                    ),
                    const SizedBox(height: 40),

                    // FORM DENGAN EFEK GLASSMORPHISM
                    ClipRRect(
                      borderRadius: BorderRadius.circular(30),
                      child: BackdropFilter(
                        filter: ImageFilter.blur(sigmaX: 15, sigmaY: 15),
                        child: Container(
                          padding: const EdgeInsets.all(28.0),
                          decoration: BoxDecoration(
                            color: isDark 
                              ? Colors.black.withOpacity(0.3) 
                              : Colors.white.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(30),
                            border: Border.all(color: Colors.white.withOpacity(0.3), width: 1.5),
                          ),
                          child: Form(
                            key: _formKey,
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                _buildLabel("NAMA", isDark),
                                _buildTextField(_nameController, Icons.person_outline, "Nama Anda", isDark),
                                const SizedBox(height: 20),

                                _buildLabel("USERNAME", isDark),
                                _buildTextField(_usernameController, Icons.alternate_email, "Username Anda", isDark),
                                const SizedBox(height: 20),

                                _buildLabel("PASSWORD BARU", isDark),
                                _buildTextField(_passwordController, Icons.lock_outline, "Minimal 5 karakter", isDark, isPassword: true),
                                const SizedBox(height: 20),

                                // KONFIRMASI PASSWORD (Tampil hanya jika password diisi)
                                _buildLabel("KONFIRMASI PASSWORD", isDark),
                                _buildTextField(_confirmPasswordController, Icons.lock_reset, "Ulangi password", isDark, isPassword: true),
                                
                                const SizedBox(height: 40),

                                // TOMBOL SIMPAN (IKUT GLASS STYLE)
                                SizedBox(
                                  width: double.infinity,
                                  height: 55,
                                  child: ElevatedButton(
                                    onPressed: _isLoading ? null : _updateProfile,
                                    style: ElevatedButton.styleFrom(
                                      backgroundColor: Colors.white,
                                      foregroundColor: const Color(0xFF3949AB),
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
                                      elevation: 0,
                                    ),
                                    child: _isLoading 
                                        ? const CircularProgressIndicator(color: Color(0xFF3949AB))
                                        : const Text(
                                            "SIMPAN PERUBAHAN", 
                                            style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1),
                                          ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    const SizedBox(height: 40),
                  ],
                ),
              ),
            ),
            // Tombol Back Custom (Dipindah ke paling bawah agar di atas lapisan lain)
            Positioned(
              top: 50,
              left: 20,
              child: IconButton(
                icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
                onPressed: () => Navigator.pop(context),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLabel(String text, bool isDark) {
    return Padding(
      padding: const EdgeInsets.only(left: 4, bottom: 8),
      child: Text(
        text,
        style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Colors.white70, letterSpacing: 1.2),
      ),
    );
  }

  Widget _buildTextField(TextEditingController controller, IconData icon, String hint, bool isDark, {bool isPassword = false}) {
    return TextFormField(
      controller: controller,
      obscureText: isPassword,
      style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
      decoration: InputDecoration(
        hintText: hint,
        hintStyle: TextStyle(color: Colors.white.withOpacity(0.4), fontSize: 14),
        prefixIcon: Icon(icon, color: Colors.white70, size: 22),
        filled: true,
        fillColor: Colors.white.withOpacity(0.1),
        contentPadding: const EdgeInsets.symmetric(vertical: 16, horizontal: 20),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(15),
          borderSide: BorderSide(color: Colors.white.withOpacity(0.3)),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(15),
          borderSide: const BorderSide(color: Colors.white, width: 2),
        ),
      ),
    );
  }
}