// lib/screens/profile/edit_profile.dart
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;

import 'package:fl_sevengen_society_user_app/localization/localization_const.dart';
import '../../theme/theme.dart';

class IndianPhoneFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue,
      TextEditingValue newValue,
      ) {
    final newText = newValue.text.replaceAll(RegExp(r'[^\d]'), ''); // Keep only digits

    if (newText.length > 10) return oldValue; // Max 10 digits for Indian numbers

    // Format as XXXX-XXXXXX or XXXXX-XXXXX
    final buffer = StringBuffer();
    if (newText.length > 6) {
      buffer.write('${newText.substring(0, 5)}-${newText.substring(5)}');
    } else if (newText.length > 4) {
      buffer.write('${newText.substring(0, 4)}-${newText.substring(4)}');
    } else {
      buffer.write(newText);
    }

    return TextEditingValue(
      text: buffer.toString(),
      selection: TextSelection.collapsed(offset: buffer.length),
      composing: TextRange.empty,
    );
  }
}

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

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

class _EditProfileScreenState extends State<EditProfileScreen> {
  // Controllers for fields
  final TextEditingController _nameCtrl = TextEditingController();
  final TextEditingController _dobCtrl = TextEditingController(); // displayed as dd-MM-yyyy
  final TextEditingController _annivCtrl = TextEditingController(); // dd-MM-yyyy
  final TextEditingController _companyOpenCtrl = TextEditingController(); // dd-MM-yyyy
  final TextEditingController _phoneCtrl = TextEditingController();
  final TextEditingController _emailCtrl = TextEditingController();
  final TextEditingController _addressCtrl = TextEditingController();

  // Image
  File? _pickedImageFile;
  String? _pickedImageDataUri; // base64 data uri for server
  String? _profileImageUrl; // existing server image URL

  // helpers
  final ImagePicker _picker = ImagePicker();

  bool _loading = false; // for update
  bool _fetching = true; // for initial fetch
  String _ridNo = "";

  // TODO: Replace with your actual endpoints
  final String _getUrl = 'https://rmbferodeunited.in/api/profile_get.php'; // expects POST {rid_no}
  final String _updateUrl = 'https://rmbferodeunited.in/api/profile_update.php'; // expects JSON body

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

  @override
  void dispose() {
    _nameCtrl.dispose();
    _dobCtrl.dispose();
    _annivCtrl.dispose();
    _companyOpenCtrl.dispose();
    _phoneCtrl.dispose();
    _emailCtrl.dispose();
    _addressCtrl.dispose();
    super.dispose();
  }

  Future<void> _initAndFetch() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final rid = prefs.getString('rid_no') ?? "";
      if (!mounted) return;
      setState(() {
        _ridNo = rid;
      });

      if (_ridNo.isEmpty) {
        setState(() => _fetching = false);
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Please login to continue.')),
          );
          Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false);
        }
        return;
      }

      await _fetchProfile();
    } catch (e) {
      if (mounted) {
        setState(() => _fetching = false);
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Init failed: $e')));
      }
    }
  }

  // Format phone number for display (from server data)
  String _formatPhoneForDisplay(String phone) {
    final clean = phone.replaceAll(RegExp(r'[^\d]'), '');
    if (clean.length > 6) {
      return '${clean.substring(0, 5)}-${clean.substring(5)}';
    } else if (clean.length > 4) {
      return '${clean.substring(0, 4)}-${clean.substring(4)}';
    }
    return clean;
  }

  // Convert server -> display (supports "YYYY-MM-DD", "YYYY-MM-DD HH:MM:SS", already dd-MM-yyyy)
  String _serverToDisplayDate(String? serverDate) {
    if (serverDate == null) return '';
    final s = serverDate.trim();
    if (s.isEmpty) return '';

    // If already dd-MM-yyyy, return as-is
    if (RegExp(r'^\d{2}-\d{2}-\d{4}$').hasMatch(s)) return s;

    // If format "YYYY-MM-DD" or "YYYY-MM-DD hh:mm:ss"
    final ymdMatch = RegExp(r'^(\d{4})-(\d{2})-(\d{2})').firstMatch(s);
    if (ymdMatch != null) {
      final y = ymdMatch.group(1);
      final m = ymdMatch.group(2);
      final d = ymdMatch.group(3);
      return '${d?.padLeft(2, '0')}-${m?.padLeft(2, '0')}-${y}';
    }

    // If dd/MM/yyyy
    if (RegExp(r'^\d{2}\/\d{2}\/\d{4}$').hasMatch(s)) {
      final parts = s.split('/');
      return '${parts[0].padLeft(2, '0')}-${parts[1].padLeft(2, '0')}-${parts[2]}';
    }

    // Last resort: try DateTime.parse (handles many formats)
    try {
      final dt = DateTime.parse(s);
      return '${dt.day.toString().padLeft(2, '0')}-${dt.month.toString().padLeft(2, '0')}-${dt.year}';
    } catch (_) {
      // nothing we can do — return original
      return s;
    }
  }

  // Convert display (dd-MM-yyyy or dd/MM/yyyy) -> server (YYYY-MM-DD)
  // If empty returns empty string
  String _displayToServerDate(String? displayDate) {
    if (displayDate == null) return '';
    final s = displayDate.trim();
    if (s.isEmpty) return '';

    // If already yyyy-mm-dd (server) just return normalized first 10 chars
    if (RegExp(r'^\d{4}-\d{2}-\d{2}').hasMatch(s)) {
      return s.substring(0, 10);
    }

    // If dd-MM-yyyy or dd/MM/yyyy
    final dmyMatch = RegExp(r'^(\d{2})[-\/](\d{2})[-\/](\d{4})$').firstMatch(s);
    if (dmyMatch != null) {
      final d = dmyMatch.group(1);
      final m = dmyMatch.group(2);
      final y = dmyMatch.group(3);
      return '${y}-${m?.padLeft(2, '0')}-${d?.padLeft(2, '0')}';
    }

    // Last resort: try parsing and format
    try {
      final dt = DateTime.parse(s);
      return '${dt.year}-${dt.month.toString().padLeft(2, '0')}-${dt.day.toString().padLeft(2, '0')}';
    } catch (_) {
      // return empty to avoid sending invalid date
      return '';
    }
  }

  Future<void> _fetchProfile() async {
    if (_ridNo.isEmpty) {
      setState(() => _fetching = false);
      return;
    }

    setState(() => _fetching = true);

    try {
      final uri = Uri.parse(_getUrl);
      final res = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({'rid_no': _ridNo}),
      );

      if (res.statusCode == 200) {
        final Map<String, dynamic> jsonRes = jsonDecode(res.body);
        if (jsonRes['success'] == true && jsonRes['data'] != null) {
          final data = jsonRes['data'];
          if (!mounted) return;
          setState(() {
            _nameCtrl.text = (data['full_name'] ?? '').toString();
            _dobCtrl.text = _serverToDisplayDate((data['dob'] ?? '').toString());
            _annivCtrl.text = _serverToDisplayDate((data['anniversary'] ?? '').toString());
            _companyOpenCtrl.text = _serverToDisplayDate((data['company_open_date'] ?? '').toString());
            _phoneCtrl.text = _formatPhoneForDisplay((data['phone'] ?? '').toString()); // Format for display
            _emailCtrl.text = (data['email'] ?? '').toString();
            _addressCtrl.text = (data['Address'] ?? data['address'] ?? '').toString();
            _profileImageUrl = (data['profile_image'] ?? '').toString();
          });
        } else {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(jsonRes['message'] ?? 'Profile not found')),
            );
          }
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('Server error: ${res.statusCode}')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Fetch failed: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _fetching = false);
    }
  }

  // Pick image from camera or gallery
  Future<void> _pickImage(ImageSource source) async {
    try {
      final XFile? xf = await _picker.pickImage(
        source: source,
        maxWidth: 1200,
        maxHeight: 1200,
        imageQuality: 80,
      );

      if (xf == null) return;

      // Read as bytes and create data-uri for sending to server
      final bytes = await xf.readAsBytes();
      final nm = xf.name.toLowerCase();
      String mime = 'jpeg';
      if (nm.endsWith('.png')) mime = 'png';
      else if (nm.endsWith('.jpg') || nm.endsWith('.jpeg')) mime = 'jpeg';
      final dataUri = 'data:image/$mime;base64,${base64Encode(bytes)}';

      if (!mounted) return;
      setState(() {
        _pickedImageFile = File(xf.path);
        _pickedImageDataUri = dataUri;
        // keep _profileImageUrl until server returns a new url
      });
    } catch (e) {
      if (mounted) {
        // Likely permission denied or other platform error
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Image pick failed: $e')),
        );
      }
    }
  }

  Future<void> _showImageOptions() async {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: whiteColor,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(10.0))),
      builder: (context) {
        return Padding(
          padding: const EdgeInsets.all(fixPadding * 2.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(getTranslate(context, 'edit_profile.add_image'), style: semibold18Black33),
              heightSpace,
              ListTile(
                leading: const Icon(Icons.camera_alt),
                title: Text(getTranslate(context, 'edit_profile.camera')),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.camera);
                },
              ),
              ListTile(
                leading: const Icon(Icons.photo),
                title: Text(getTranslate(context, 'edit_profile.gallery')),
                onTap: () {
                  Navigator.pop(context);
                  _pickImage(ImageSource.gallery);
                },
              ),
              ListTile(
                leading: const Icon(Icons.delete),
                title: Text(getTranslate(context, 'edit_profile.remove')),
                onTap: () {
                  Navigator.pop(context);
                  setState(() {
                    _pickedImageFile = null;
                    _pickedImageDataUri = null;
                    _profileImageUrl = null; // remove existing as well (server will be informed on update)
                  });
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _selectDate(TextEditingController ctrl) async {
    DateTime initial = DateTime.now();
    if (ctrl.text.isNotEmpty) {
      try {
        final parts = ctrl.text.split(RegExp(r'[-\/]'));
        if (parts.length == 3) {
          final d = int.parse(parts[0]);
          final m = int.parse(parts[1]);
          final y = int.parse(parts[2]);
          initial = DateTime(y, m, d);
        }
      } catch (_) {}
    }

    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: initial,
      firstDate: DateTime(1900),
      lastDate: DateTime(2100),
    );

    if (picked != null && mounted) {
      final display = '${picked.day.toString().padLeft(2, '0')}-${picked.month.toString().padLeft(2, '0')}-${picked.year}';
      setState(() {
        ctrl.text = display;
      });
    }
  }

  Future<void> _updateProfile() async {
    if (_ridNo.isEmpty) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('Please login to continue.')));
      }
      return;
    }

    // Basic validation (name)
    if (_nameCtrl.text.trim().isEmpty) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(getTranslate(context, 'edit_profile.enter_your_name'))));
      }
      return;
    }

    // Phone validation (Indian 10-digit mobile) - only if not empty
    final cleanPhone = _phoneCtrl.text.replaceAll('-', '').trim();
    if (cleanPhone.isNotEmpty && (cleanPhone.length != 10 || !RegExp(r'^[6-9]\d{9}$').hasMatch(cleanPhone))) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Enter valid 10-digit Indian mobile number')),
        );
      }
      return;
    }

    setState(() => _loading = true);

    final body = <String, dynamic>{
      'rid_no': _ridNo,
      'full_name': _nameCtrl.text.trim(),
      'dob': _displayToServerDate(_dobCtrl.text.trim()),
      'anniversary': _displayToServerDate(_annivCtrl.text.trim()),
      'company_open_date': _displayToServerDate(_companyOpenCtrl.text.trim()),
      'phone': cleanPhone, // Send clean digits only
      'email': _emailCtrl.text.trim(),
      'Address': _addressCtrl.text.trim(),
    };

    if (_pickedImageDataUri != null) {
      body['profile_image'] = _pickedImageDataUri;
    } else if (_profileImageUrl == null) {
      // If user removed existing image, send empty value so server can clear it
      body['profile_image'] = '';
    }

    try {
      final uri = Uri.parse(_updateUrl);
      final res = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(body),
      );

      if (!mounted) return;

      if (res.statusCode == 200) {
        final Map<String, dynamic> jsonRes = jsonDecode(res.body);
        if (jsonRes['success'] == true) {
          // update local fields if returned
          if (jsonRes['data'] != null) {
            final data = jsonRes['data'];
            setState(() {
              _profileImageUrl = (data['profile_image'] ?? _profileImageUrl ?? '').toString();
              _dobCtrl.text = _serverToDisplayDate((data['dob'] ?? '').toString());
              _annivCtrl.text = _serverToDisplayDate((data['anniversary'] ?? '').toString());
              _companyOpenCtrl.text = _serverToDisplayDate((data['company_open_date'] ?? '').toString());
              _phoneCtrl.text = _formatPhoneForDisplay((data['phone'] ?? '').toString()); // Re-format display
              // clear picked image after successful upload (so UI shows server url)
              _pickedImageFile = null;
              _pickedImageDataUri = null;
            });
          }

          // save core fields to SharedPreferences
          final prefs = await SharedPreferences.getInstance();
          await prefs.setString('full_name', _nameCtrl.text.trim());
          await prefs.setString('email', _emailCtrl.text.trim());
          await prefs.setString('phone', cleanPhone); // Save clean phone
          await prefs.setString('Address', _addressCtrl.text.trim());

          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(jsonRes['message'] ?? 'Profile updated')));
            Navigator.pop(context, true);
          }
        } else {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(jsonRes['message'] ?? 'Update failed')));
          }
        }
      } else {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Server error: ${res.statusCode}')));
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Request failed: $e')));
      }
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  Widget _buildTextField(String label, TextEditingController ctrl,
      {TextInputType keyboard = TextInputType.text, bool readOnly = false, VoidCallback? onTap}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: medium16Grey),
        heightSpace,
        Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            color: whiteColor,
            boxShadow: [BoxShadow(color: blackColor.withOpacity(0.2), blurRadius: 6.0)],
          ),
          child: TextField(
            controller: ctrl,
            readOnly: readOnly,
            onTap: onTap,
            cursorColor: primaryColor,
            style: medium16Black33,
            keyboardType: keyboard,
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: const EdgeInsets.symmetric(horizontal: fixPadding * 1.5),
              hintText: label,
              hintStyle: medium16Grey,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildReadOnlyPhoneField(String label, TextEditingController ctrl) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: medium16Grey),
        heightSpace,
        Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.0),
            color: whiteColor,
            boxShadow: [BoxShadow(color: blackColor.withOpacity(0.2), blurRadius: 6.0)],
          ),
          child: TextField(
            controller: ctrl,
            readOnly: true, // READ ONLY - cannot type
            keyboardType: TextInputType.phone,
            style: medium16Black33,
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: const EdgeInsets.symmetric(horizontal: fixPadding * 1.5),
              hintText: '12345-67890',
              hintStyle: medium16Grey,
            ),
          ),
        ),
      ],
    );
  }

  Widget _userImage(Size size) {
    Widget imageWidget;
    final double avatarRadius = size.height * 0.07;

    if (_pickedImageFile != null) {
      imageWidget = CircleAvatar(radius: avatarRadius, backgroundImage: FileImage(_pickedImageFile!));
    } else if (_profileImageUrl != null && _profileImageUrl!.isNotEmpty) {
      imageWidget = CircleAvatar(radius: avatarRadius, backgroundImage: NetworkImage(_profileImageUrl!));
    } else {
      imageWidget = Container(
        height: avatarRadius * 2,
        width: avatarRadius * 2,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: whiteColor,
          border: Border.all(color: whiteColor, width: 2),
          boxShadow: [BoxShadow(color: shadowColor.withOpacity(0.23), blurRadius: 6.0)],
        ),
        child: ClipOval(child: Image.asset("assets/profile/profile-image.png", fit: BoxFit.cover)),
      );
    }

    return Center(
      child: Stack(
        children: [
          imageWidget,
          Positioned(right: 0, bottom: 0, child: _cameraButton(size)),
        ],
      ),
    );
  }

  Widget _cameraButton(Size size) {
    return GestureDetector(
      onTap: _showImageOptions,
      child: Container(
        height: size.height * 0.047,
        width: size.height * 0.047,
        decoration: const BoxDecoration(shape: BoxShape.circle, color: whiteColor),
        alignment: Alignment.center,
        child: const Icon(Icons.camera_alt_outlined, color: black33Color, size: 21),
      ),
    );
  }

  Widget _updateButton(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
      child: GestureDetector(
        onTap: _loading ? null : _updateProfile,
        child: Container(
          margin: const EdgeInsets.all(fixPadding * 2.0),
          padding: const EdgeInsets.symmetric(horizontal: fixPadding * 2.0, vertical: fixPadding * 1.4),
          width: double.maxFinite,
          decoration: BoxDecoration(
            color: _loading ? primaryColor.withOpacity(0.6) : primaryColor,
            borderRadius: BorderRadius.circular(10.0),
            boxShadow: [BoxShadow(color: primaryColor.withOpacity(0.1), blurRadius: 12.0, offset: const Offset(0, 6))],
          ),
          child: _loading
              ? Row(mainAxisAlignment: MainAxisAlignment.center, children: const [
            SizedBox(height: 18, width: 18, child: CircularProgressIndicator(strokeWidth: 2, valueColor: AlwaysStoppedAnimation<Color>(Colors.white))),
            SizedBox(width: 8),
            Text("Updating...", style: TextStyle(color: Colors.white))
          ])
              : Text(getTranslate(context, 'edit_profile.update'), style: semibold18White, textAlign: TextAlign.center),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    if (_fetching) {
      return const Scaffold(body: Center(child: CircularProgressIndicator()));
    }

    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor, // Changed to primary color
        elevation: 0.0,
        titleSpacing: 0.0,
        centerTitle: false,
        automaticallyImplyLeading: false,
        leading: IconButton(
            onPressed: () => Navigator.pop(context),
            icon: const Icon(Icons.arrow_back, color: Colors.white, size: 18) // White back arrow, size 18
        ),
        title: Text(
            getTranslate(context, 'edit_profile.edit_profile'),
            style: const TextStyle(
              color: Colors.white, // White text color
              fontSize: 18, // Font size 18
              fontWeight: FontWeight.w600, // Assuming semibold18White equivalent
            )
        ),
      ),
      body: ListView(
        padding: const EdgeInsets.all(fixPadding * 2.0),
        physics: const BouncingScrollPhysics(),
        children: [
          _userImage(size),
          heightSpace,
          Center(child: Text(_nameCtrl.text, textAlign: TextAlign.center, style: semibold18Primary)),
          height5Space,
          Center(child: Text(_addressCtrl.text, style: medium14Grey, textAlign: TextAlign.center)),
          heightSpace,
          _buildTextField(getTranslate(context, 'edit_profile.name'), _nameCtrl),
          heightSpace,
          // Date fields (display dd-mm-yyyy)
          GestureDetector(onTap: () => _selectDate(_dobCtrl), child: AbsorbPointer(child: _buildTextField('DOB (dd-mm-yyyy)', _dobCtrl))),
          heightSpace,
          GestureDetector(onTap: () => _selectDate(_annivCtrl), child: AbsorbPointer(child: _buildTextField('Anniversary (dd-mm-yyyy)', _annivCtrl))),
          heightSpace,
          GestureDetector(onTap: () => _selectDate(_companyOpenCtrl), child: AbsorbPointer(child: _buildTextField('Company Open Date (dd-mm-yyyy)', _companyOpenCtrl))),
          heightSpace,
          _buildTextField(getTranslate(context, 'edit_profile.email_address'), _emailCtrl, keyboard: TextInputType.emailAddress),
          heightSpace,
          _buildReadOnlyPhoneField(getTranslate(context, 'edit_profile.phone_number'), _phoneCtrl), // READ ONLY phone field
          heightSpace,
          _buildTextField('Address', _addressCtrl, keyboard: TextInputType.streetAddress),
          const SizedBox(height: 24),
        ],
      ),
      bottomNavigationBar: _updateButton(context),
    );
  }
}
