import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:monitoring/config.dart';
import 'dart:convert';

import 'edit_profile_screen.dart';
import 'change_password_screen.dart';

class ProfileScreen extends StatefulWidget {
  final String token;
  const ProfileScreen({super.key, required this.token});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  Map<String, dynamic>? userData;
  Map<String, dynamic>? santriData;
  String? fotoUrl;
  bool loading = true;

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

  Future<void> fetchProfile() async {
    final url = '$baseUrl/santri/me';
    try {
      final res = await http.get(
        Uri.parse(url),
        headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer ${widget.token}',
        },
      );

      if (res.statusCode == 200) {
        final jsonRes = json.decode(res.body);
        setState(() {
          userData = jsonRes['user'];
          santriData = jsonRes['santri'];
          fotoUrl = santriData?['foto_url'];
          loading = false;
        });
      } else {
        debugPrint('Gagal ambil profil: ${res.body}');
        setState(() => loading = false);
      }
    } catch (e) {
      debugPrint('Error profile: $e');
      setState(() => loading = false);
    }
  }

  void _logout() {
    Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Profil'),
        actions: [
          IconButton(
            onPressed: _logout,
            icon: const Icon(Icons.logout),
            tooltip: 'Logout',
          ),
        ],
      ),
      body:
          loading
              ? const Center(child: CircularProgressIndicator())
              : userData == null || santriData == null
              ? const Center(child: Text('Data tidak ditemukan'))
              : SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Center(
                      child: CircleAvatar(
                        radius: 50,
                        backgroundImage:
                            fotoUrl != null
                                ? NetworkImage(fotoUrl!)
                                : const AssetImage('assets/default_profile.png')
                                    as ImageProvider,
                        backgroundColor: Colors.grey[300],
                      ),
                    ),
                    const SizedBox(height: 20),
                    Center(
                      child: Text(
                        userData!['name'] ?? '-',
                        style: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    const SizedBox(height: 16),
                    // _buildInfoTile('Username', userData!['username']),
                    // _buildInfoTile('Email', userData!['email']),
                    // _buildInfoTile('Role', userData!['role']),
                    const Divider(),
                    _buildInfoTile('NIS', santriData!['nis']),
                    _buildInfoTile('Alamat', santriData!['alamat']),
                    _buildInfoTile('Tempat Lahir', santriData!['tempat_lahir']),
                    _buildInfoTile(
                      'Tanggal Lahir',
                      santriData!['tanggal_lahir'],
                    ),
                    _buildInfoTile(
                      'Jenis Kelamin',
                      santriData!['jenis_kelamin'] == 'L'
                          ? 'Laki-laki'
                          : 'Perempuan',
                    ),
                    const SizedBox(height: 24),

                    // ✅ PERBAIKAN NAVIGASI EDIT
                    ElevatedButton.icon(
                      onPressed: () async {
                        final result = await Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder:
                                (_) => EditProfileScreen(token: widget.token),
                          ),
                        );
                        if (result == true) {
                          fetchProfile(); // Refresh profil setelah edit
                        }
                      },
                      icon: const Icon(Icons.edit),
                      label: const Text('Edit Profil'),
                    ),

                    const SizedBox(height: 12),

                    ElevatedButton.icon(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                      ),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder:
                                (_) =>
                                    ChangePasswordScreen(token: widget.token),
                          ),
                        );
                      },
                      icon: const Icon(Icons.lock),
                      label: const Text('Ganti Password'),
                    ),
                  ],
                ),
              ),
    );
  }

  Widget _buildInfoTile(String label, String? value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 120,
            child: Text(
              '$label:',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(child: Text(value ?? '-')),
        ],
      ),
    );
  }
}
