import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nearle/controllers/profile_controller.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:nearle/views/helpers/constants/Font_constant.dart';

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

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  String _name = '';
  String _email = '';
  String _contact = '';
  String _address = '';
  final List<Worker> _workers = [];
  late final ProfileController _profileController =
      Get.isRegistered<ProfileController>()
          ? Get.find<ProfileController>()
          : Get.put(ProfileController(), permanent: true);

  @override
  void initState() {
    super.initState();
    _loadProfile();
    // Keep in sync with controller
    _workers.addAll([
      ever(_profileController.userName, (_) => _assignFromController()),
      ever(_profileController.userEmail, (_) => _assignFromController()),
      ever(_profileController.userContact, (_) => _assignFromController()),
      ever(_profileController.userAddress, (_) => _assignFromController()),
    ]);
    _profileController.loadFromPrefs();
  }

  @override
  void dispose() {
    for (final worker in _workers) {
      worker.dispose();
    }
    super.dispose();
  }

  Future<void> _loadProfile() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      _name = prefs.getString('user_name') ?? '';
      _email = prefs.getString('user_email') ?? '';
      _contact = prefs.getString('contactno') ?? '';
      _address = prefs.getString('user_address') ?? '';
    });
    debugPrint('[PROFILE_DETAILS] Loaded - Name: "$_name", Email: "$_email", Contact: "$_contact"');
  }

  void _assignFromController() {
    setState(() {
      if (_profileController.userName.value.trim().isNotEmpty) {
        _name = _profileController.userName.value.trim();
      }
      if (_profileController.userEmail.value.trim().isNotEmpty) {
        _email = _profileController.userEmail.value.trim();
      }
      if (_profileController.userContact.value.trim().isNotEmpty) {
        _contact = _profileController.userContact.value.trim();
      }
      if (_profileController.userAddress.value.trim().isNotEmpty) {
        _address = _profileController.userAddress.value.trim();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    // ignore: unused_local_variable
    final height = size.height;
    return Scaffold(
      backgroundColor: Colors.grey.shade200,
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(width * 0.04),
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // Profile image
                Center(
                  child: Stack(
                    children: [
                      // White border circle
                      Container(
                        padding: const EdgeInsets.all(4), // border thickness
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.white, // white border
                        ),
                        child: CircleAvatar(
                          radius: 60,
                          backgroundColor: Colors.grey.shade400,
                          child: const Icon(
                            Icons.person,
                            size: 60,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                const SizedBox(height: 40),

                // Name
                _buildLabel("Enter name", required: true),
                _buildTextField(
                  hintText: _name.isNotEmpty ? _name : "EX: Vijayan",
                  value: _name.isNotEmpty ? _name : null,
                  readOnly: true,
                  disabled: true,
                ),

                const SizedBox(height: 16),

                // Contact No
                _buildLabel("Contact no", required: true),
                _buildTextField(
                  hintText: _contact.isNotEmpty
                      ? "+91 $_contact"
                      : "EX: +91  8838304677",
                  value: _contact.isNotEmpty ? "+91 $_contact" : null,
                  keyboardType: TextInputType.phone,
                  readOnly: true,
                  disabled: true,
                ),

                const SizedBox(height: 16),

                // Email Id
                _buildLabel("Email Id"),
                _buildTextField(
                  hintText: _email.isNotEmpty ? _email : "EX: gmail@gmail.com",
                  value: _email.isNotEmpty ? _email : null,
                  keyboardType: TextInputType.emailAddress,
                  readOnly: true,
                  disabled: true,
                ),

                const SizedBox(height: 16),

                // Location
                _buildLabel("Address"),
  _buildTextField(hintText: _address.isNotEmpty ? _address : " EX: R.s puram", value: _address.isNotEmpty ? _address : null, readOnly: true, disabled: true),

                const SizedBox(height: 40),
              ],
            ),
          ),
        ),
      ),
      bottomNavigationBar: SafeArea(
        child: Padding(
          padding: EdgeInsets.all(width * 0.04),
          child: SizedBox(
            width: double.infinity,
            height: 55,
            child: ElevatedButton(
              onPressed: _handleBackNavigation,
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF5C1D8D), // Purple button color
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              child: Text(
                "Back",
                style: TextStyle(
                  fontSize: 21,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontFamily: FontConstants.fontFamily,
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _handleBackNavigation() async {
    final navigator = Navigator.of(context);
    if (navigator.canPop()) {
      navigator.pop();
      return;
    }
    final rootNavigator = Get.key.currentState;
    if (rootNavigator != null && rootNavigator.canPop()) {
      rootNavigator.pop();
      return;
    }
    if (Get.isOverlaysOpen) {
      Get.back(closeOverlays: true);
      return;
    }
    Get.back();
  }

  // Text label widget
  Widget _buildLabel(String text, {bool required = false}) {
    return Align(
      alignment: Alignment.centerLeft,
      child: RichText(
        text: TextSpan(
          text: text,
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontFamily: FontConstants.fontFamily,
          ),
          children: required
              ? const [
                  TextSpan(
                    text: " *",
                    style: TextStyle(color: Colors.red),
                  ),
                ]
              : [],
        ),
      ),
    );
  }

  // Reusable TextField
  Widget _buildTextField({
    required String hintText,
    String? value,
    TextInputType keyboardType = TextInputType.text,
    required bool readOnly,
    bool disabled = false,
  }) {
    return Container(
      margin: const EdgeInsets.only(top: 6),
      child: SizedBox(
        height: 55,
        width: 350,
        child: TextFormField(
          keyboardType: keyboardType,
          readOnly: readOnly,
          enabled: !disabled,
          enableInteractiveSelection: false,
          initialValue: value,
          decoration: InputDecoration(
            hintText: hintText,
            filled: true,
            fillColor: Colors.white,
            contentPadding: const EdgeInsets.symmetric(
              horizontal: 16,
              vertical: 14,
            ),
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Colors.grey.shade300),
            ),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide(color: Colors.grey.shade300),
            ),
          ),
        ),
      ),
    );
  }
}
