import 'dart:convert';
import 'dart:io';

import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// NOTE (Policy):
/// - This screen only allows the user to select/take ONE profile photo.
/// - On Android, image_picker uses the system photo picker (Android 13+) when
///   no READ_MEDIA_* / storage permissions are declared in AndroidManifest.
/// - Make sure AndroidManifest does NOT contain READ_MEDIA_IMAGES / VIDEO /
///   READ/WRITE_EXTERNAL_STORAGE – only CAMERA (optional).
/// - On iOS, make sure Info.plist has NSCameraUsageDescription and
///   NSPhotoLibraryUsageDescription.

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

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

class _EditProfileScreenState extends State<EditProfileScreen> {
  final TextEditingController nameController = TextEditingController();
  final TextEditingController mobileNumberController = TextEditingController();
  // This controller is mapped to "home_address" in API
  final TextEditingController emailController = TextEditingController();

  final ImagePicker _picker = ImagePicker();

  String? _userId;
  bool _isLoading = false;

  // Profile image
  File? _profileImageFile; // local picked image file
  String? _profileImageUrl; // full URL from API (profile_photo)
  bool _isRemovingImage = false;

  // API URLs
  static const String profileGetUrl = 'https://gelite.asia/api/profile_get.php';
  static const String profileUpdateUrl =
      'https://gelite.asia/api/profile_update.php';

  @override
  void initState() {
    super.initState();
    _initProfile();
    _checkPhoneNo();
  }

  Future<void> _checkPhoneNo() async {
    final prefs = await SharedPreferences.getInstance();
    final String? phoneNo = prefs.getString('phone_no');

    if (phoneNo == null || phoneNo.isEmpty) {
      if (!mounted) return;
      Navigator.pushNamedAndRemoveUntil(
        context,
        '/login',
            (route) => false,
      );
    }
  }

  @override
  void dispose() {
    nameController.dispose();
    mobileNumberController.dispose();
    emailController.dispose();
    super.dispose();
  }

  Future<void> _initProfile() async {
    final prefs = await SharedPreferences.getInstance();
    final intId = prefs.getInt('id');
    debugPrint("✅ USER ID FROM SharedPreferences (int): $intId");

    if (!mounted) return;

    if (intId == null || intId == 0) {
      _showSnackBar('User ID missing in SharedPreferences');
      return;
    }

    setState(() {
      _userId = intId.toString();
    });

    await _fetchProfile();
  }

  Future<void> _fetchProfile() async {
    if (_userId == null || _userId!.isEmpty) return;

    final body = {'id': _userId!};

    try {
      debugPrint('➡️ PROFILE GET REQUEST URL: $profileGetUrl');
      debugPrint('➡️ PROFILE GET REQUEST BODY: $body');

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

      debugPrint('⬅️ PROFILE GET RESPONSE STATUS: ${response.statusCode}');
      debugPrint('⬅️ PROFILE GET RESPONSE RAW BODY: ${response.body}');

      if (!mounted) return;

      if (response.statusCode == 200) {
        dynamic jsonData;
        try {
          jsonData = json.decode(response.body);
        } catch (e) {
          debugPrint('❌ JSON DECODE ERROR (GET): $e');
          _showSnackBar('Invalid response from server');
          return;
        }

        debugPrint('📥 PROFILE GET PARSED JSON: $jsonData');

        if (jsonData['success'] == true && jsonData['data'] != null) {
          final data = jsonData['data'];

          final String name = (data['name'] ?? '').toString();
          final String phoneNo = (data['phone_no'] ?? '').toString();
          final String homeAddress = (data['home_address'] ?? '').toString();
          final String profilePhoto = (data['profile_photo'] ?? '').toString();

          setState(() {
            nameController.text = name;
            mobileNumberController.text = phoneNo;
            emailController.text = homeAddress;
            _profileImageUrl = profilePhoto.isEmpty ? null : profilePhoto;
            _profileImageFile = null;
            _isRemovingImage = false;
          });
        } else {
          _showSnackBar(
            jsonData['message']?.toString() ?? 'Failed to load profile',
          );
        }
      } else {
        _showSnackBar('Server error while fetching profile');
      }
    } catch (e) {
      debugPrint('❌ PROFILE GET ERROR: $e');
      if (mounted) {
        _showSnackBar('Something went wrong while fetching profile');
      }
    }
  }

  /// Picks image from camera or gallery.
  /// On Android 13+, this uses the system photo picker for gallery
  /// (no READ_MEDIA_* permissions required).
  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? picked = await _picker.pickImage(
        source: source,
        maxWidth: 1024,
        maxHeight: 1024,
        imageQuality: 80,
      );
      if (picked != null) {
        if (!mounted) return;
        setState(() {
          _profileImageFile = File(picked.path);
          _isRemovingImage = false;
        });
      }
    } catch (e) {
      debugPrint('❌ IMAGE PICK ERROR: $e');
      _showSnackBar('Unable to pick image');
    }
  }

  Future<void> _updateProfile() async {
    if (_userId == null || _userId!.isEmpty) {
      _showSnackBar('User ID missing');
      return;
    }

    final String name = nameController.text.trim();
    final String phoneNo = mobileNumberController.text.trim();
    final String homeAddress = emailController.text.trim();

    if (name.isEmpty || phoneNo.isEmpty || homeAddress.isEmpty) {
      _showSnackBar('All fields are required');
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final uri = Uri.parse(profileUpdateUrl);
      final request = http.MultipartRequest('POST', uri);

      // Required fields
      request.fields.addAll({
        'id': _userId!,
        'name': name,
        'phone_no': phoneNo,
        'home_address': homeAddress,
      });

      // If new image selected, send it
      if (_profileImageFile != null) {
        request.files.add(
          await http.MultipartFile.fromPath(
            'profile_photo',
            _profileImageFile!.path,
          ),
        );
      } else if (_isRemovingImage) {
        // Flag to remove existing photo
        request.fields['remove_profile_photo'] = '1';
      }

      debugPrint('➡️ PROFILE UPDATE REQUEST URL: $profileUpdateUrl');
      debugPrint('➡️ PROFILE UPDATE REQUEST FIELDS: ${request.fields}');

      final streamedResponse = await request.send();
      final response = await http.Response.fromStream(streamedResponse);

      debugPrint('⬅️ PROFILE UPDATE RESPONSE STATUS: ${response.statusCode}');
      debugPrint('⬅️ PROFILE UPDATE RESPONSE RAW BODY: ${response.body}');

      if (!mounted) return;

      if (response.statusCode == 200) {
        dynamic jsonData;
        try {
          jsonData = json.decode(response.body);
        } catch (e) {
          debugPrint('❌ JSON DECODE ERROR (UPDATE): $e');
          _showSnackBar('Invalid response from server');
          return;
        }

        debugPrint('📥 PROFILE UPDATE PARSED JSON: $jsonData');

        final bool success = jsonData['success'] == true;
        final String message =
            jsonData['message']?.toString() ?? (success ? 'Updated' : 'Failed');

        _showSnackBar(message);

        if (success) {
          Navigator.pop(context, true);
        }
      } else {
        _showSnackBar('Server error while updating profile');
      }
    } catch (e) {
      debugPrint('❌ PROFILE UPDATE ERROR: $e');
      if (mounted) {
        _showSnackBar('Something went wrong while updating profile');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  void _showSnackBar(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          msg,
          style: regular15White,
        ),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: false,
        backgroundColor: whiteColor,
        titleSpacing: 0.0,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(
            Icons.arrow_back,
            color: blackColor,
          ),
        ),
        title: Text(
          tr(context, 'edit_profile.edit_profile'),
          style: medium18Black,
        ),
      ),
      body: Stack(
        children: [
          ListView(
            physics: const BouncingScrollPhysics(),
            padding: const EdgeInsets.fromLTRB(
              fixPadding * 2.0,
              fixPadding * 3.0,
              fixPadding * 2.0,
              fixPadding * 2.0,
            ),
            children: [
              userProfileImage(size),
              heightSpace,
              heightSpace,
              heightSpace,
              heightSpace,
              nameField(),
              heightSpace,
              heightSpace,
              height5Space,
              mobileNumberField(),
              heightSpace,
              heightSpace,
              height5Space,
              emailField(),
            ],
          ),
          if (_isLoading)
            Container(
              color: Colors.black.withOpacity(0.05),
              alignment: Alignment.center,
              child: const CircularProgressIndicator(),
            ),
        ],
      ),
      bottomNavigationBar: updateButton(context),
    );
  }

  Widget updateButton(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
        bottom: MediaQuery.viewInsetsOf(context).bottom,
      ),
      child: GestureDetector(
        onTap: _isLoading ? null : _updateProfile,
        child: Container(
          margin: const EdgeInsets.symmetric(
            vertical: fixPadding * 2.5,
            horizontal: fixPadding * 2.0,
          ),
          padding: const EdgeInsets.symmetric(
            horizontal: fixPadding * 2.0,
            vertical: fixPadding * 1.1,
          ),
          width: double.maxFinite,
          decoration: BoxDecoration(
            color: primaryColor,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: buttonShadow,
          ),
          child: Text(
            tr(context, 'edit_profile.update'),
            style: medium20White,
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }

  Widget emailField() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          tr(context, 'edit_profile.email_address'),
          style: regular16Black,
        ),
        heightSpace,
        Container(
          width: double.maxFinite,
          decoration: BoxDecoration(
            color: whiteColor,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: boxShadow2,
          ),
          child: TextField(
            cursorColor: primaryColor,
            keyboardType: TextInputType.emailAddress,
            style: regular15Black,
            controller: emailController,
            decoration: InputDecoration(
              border: InputBorder.none,
              focusedBorder: focusedBorder,
              isDense: true,
              hintText:
              tr(context, 'edit_profile.enter_your_email_address'),
              hintStyle: regular15Grey,
              contentPadding: const EdgeInsets.symmetric(
                vertical: fixPadding * 1.4,
                horizontal: fixPadding * 1.5,
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget mobileNumberField() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          tr(context, 'edit_profile.mobile_number'),
          style: regular16Black,
        ),
        heightSpace,
        Container(
          width: double.maxFinite,
          decoration: BoxDecoration(
            color: whiteColor,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: boxShadow2,
          ),
          child: TextField(
            cursorColor: primaryColor,
            keyboardType: TextInputType.phone,
            style: regular15Black,
            controller: mobileNumberController,
            decoration: InputDecoration(
              border: InputBorder.none,
              focusedBorder: focusedBorder,
              isDense: true,
              hintText:
              tr(context, 'edit_profile.enter_your_mobile_number'),
              hintStyle: regular15Grey,
              contentPadding: const EdgeInsets.symmetric(
                vertical: fixPadding * 1.4,
                horizontal: fixPadding * 1.5,
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget nameField() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          tr(context, 'edit_profile.name'),
          style: regular16Black,
        ),
        heightSpace,
        Container(
          width: double.maxFinite,
          decoration: BoxDecoration(
            color: whiteColor,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: boxShadow2,
          ),
          child: TextField(
            cursorColor: primaryColor,
            keyboardType: TextInputType.name,
            style: regular15Black,
            controller: nameController,
            decoration: InputDecoration(
              border: InputBorder.none,
              focusedBorder: focusedBorder,
              isDense: true,
              hintText: tr(context, 'edit_profile.enter_your_name'),
              hintStyle: regular15Grey,
              contentPadding: const EdgeInsets.symmetric(
                vertical: fixPadding * 1.4,
                horizontal: fixPadding * 1.5,
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget userProfileImage(Size size) {
    Widget imageWidget;

    if (_profileImageFile != null) {
      // Local image picked from camera/gallery
      imageWidget = ClipRRect(
        borderRadius: BorderRadius.circular(9.0),
        child: Image.file(
          _profileImageFile!,
          height: size.height * 0.11,
          width: size.height * 0.11,
          fit: BoxFit.cover,
        ),
      );
    } else if (_profileImageUrl != null && _profileImageUrl!.isNotEmpty) {
      // Remote image from server
      imageWidget = ClipRRect(
        borderRadius: BorderRadius.circular(9.0),
        child: Image.network(
          _profileImageUrl!,
          height: size.height * 0.11,
          width: size.height * 0.11,
          fit: BoxFit.cover,
          errorBuilder: (_, __, ___) {
            return Image.asset(
              "assets/profile/user-image.png",
              height: size.height * 0.11,
              width: size.height * 0.11,
              fit: BoxFit.cover,
            );
          },
        ),
      );
    } else {
      // Default placeholder
      imageWidget = Container(
        height: size.height * 0.11,
        width: size.height * 0.11,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(9.0),
          image: const DecorationImage(
            image: AssetImage("assets/profile/user-image.png"),
            fit: BoxFit.cover,
          ),
        ),
      );
    }

    return Center(
      child: SizedBox(
        height: size.height * 0.11,
        width: size.height * 0.13,
        child: Stack(
          children: [
            imageWidget,
            languageValue == 4
                ? Positioned(
              left: 0,
              top: 0,
              bottom: 0,
              child: cameraIconButton(size),
            )
                : Positioned(
              right: 0,
              top: 0,
              bottom: 0,
              child: cameraIconButton(size),
            )
          ],
        ),
      ),
    );
  }

  Widget cameraIconButton(Size size) {
    return GestureDetector(
      onTap: () {
        imageChangeBottomSheet();
      },
      child: Container(
        height: size.height * 0.043,
        width: size.height * 0.043,
        decoration: const BoxDecoration(
          shape: BoxShape.circle,
          color: whiteColor,
        ),
        alignment: Alignment.center,
        child: Icon(
          Icons.camera_alt_outlined,
          color: primaryColor,
          size: size.height * 0.025,
        ),
      ),
    );
  }

  Future<dynamic> imageChangeBottomSheet() {
    return showModalBottomSheet(
      isScrollControlled: true,
      backgroundColor: whiteColor,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          top: Radius.circular(20.0),
        ),
      ),
      context: context,
      builder: (context) {
        return ListView(
          physics: const BouncingScrollPhysics(),
          shrinkWrap: true,
          padding: const EdgeInsets.symmetric(
            horizontal: fixPadding * 2.0,
            vertical: fixPadding * 2.5,
          ),
          children: [
            Text(
              tr(context, 'edit_profile.change_profile_photo'),
              style: medium16Black,
            ),
            heightSpace,
            heightSpace,
            height5Space,
            imageOptionWidget(
              Icons.camera_alt,
              tr(context, 'edit_profile.camera'),
              darkBlueColor,
              onTap: () async {
                Navigator.pop(context);
                await _pickImage(ImageSource.camera);
              },
            ),
            heightSpace,
            heightSpace,
            imageOptionWidget(
              Icons.photo,
              tr(context, 'edit_profile.gallery'),
              greenColor,
              onTap: () async {
                Navigator.pop(context);
                await _pickImage(ImageSource.gallery);
              },
            ),
            heightSpace,
            heightSpace,
            imageOptionWidget(
              CupertinoIcons.trash_fill,
              tr(context, 'edit_profile.remove_image'),
              redColor,
              onTap: () {
                Navigator.pop(context);
                setState(() {
                  _profileImageFile = null;
                  _profileImageUrl = null;
                  _isRemovingImage = true;
                });
              },
            ),
          ],
        );
      },
    );
  }

  Widget imageOptionWidget(
      IconData icon,
      String title,
      Color color, {
        required VoidCallback onTap,
      }) {
    return InkWell(
      splashColor: Colors.transparent,
      onTap: onTap,
      child: Row(
        children: [
          Container(
            height: 40.0,
            width: 40.0,
            decoration: BoxDecoration(
              color: whiteColor,
              shape: BoxShape.circle,
              boxShadow: boxShadow,
            ),
            alignment: Alignment.center,
            child: Icon(
              icon,
              color: color,
            ),
          ),
          widthSpace,
          width5Space,
          Expanded(
            child: Text(
              title,
              style: regular16Black,
              overflow: TextOverflow.ellipsis,
            ),
          )
        ],
      ),
    );
  }
}
