// lib/features/admin/tabs/messages/profile_panel.dart

import 'dart:convert';

import 'package:flutter/material.dart';

class ProfilePanel extends StatefulWidget {
  final VoidCallback onBack;
  final String myName;
  final String? myPic;

  const ProfilePanel({
    super.key,
    required this.onBack,
    required this.myName,
    this.myPic,
  });

  @override
  State<ProfilePanel> createState() => _ProfilePanelState();
}

class _ProfilePanelState extends State<ProfilePanel> {
  static const Color _green = Color.fromARGB(255, 2, 105, 48);
  static const Color _gold = Color.fromARGB(255, 204, 117, 4);
  static const Color _ink = Color(0xFF17231C);
  static const Color _muted = Color(0xFF66756C);
  static const Color _border = Color(0xFFE2E8E4);

  late final TextEditingController _nameController;
  late final TextEditingController _aboutController;

  bool _isEditingName = false;
  bool _isEditingAbout = false;
  late String _currentName;
  late String _currentAbout;

  @override
  void initState() {
    super.initState();
    _currentName = widget.myName;
    _currentAbout = 'Available';
    _nameController = TextEditingController(text: _currentName);
    _aboutController = TextEditingController(text: _currentAbout);
  }

  @override
  void dispose() {
    _nameController.dispose();
    _aboutController.dispose();
    super.dispose();
  }

  ImageProvider? _getAvatarProvider(String? imageString) {
    if (imageString == null || imageString.trim().isEmpty) return null;
    final value = imageString.trim();
    if (value.startsWith('http')) return NetworkImage(value);
    try {
      final clean = value.contains(',') ? value.split(',').last : value;
      return MemoryImage(base64Decode(clean.replaceAll(RegExp(r'\s+'), '')));
    } catch (_) {
      return null;
    }
  }

  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: _green,
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  void _saveName() {
    final value = _nameController.text.trim();
    if (value.isEmpty) return;
    setState(() {
      _currentName = value;
      _isEditingName = false;
    });
    _showSnackBar('Name updated successfully');
  }

  void _saveAbout() {
    final value = _aboutController.text.trim();
    if (value.isEmpty) return;
    setState(() {
      _currentAbout = value;
      _isEditingAbout = false;
    });
    _showSnackBar('About updated successfully');
  }

  Widget _editableCard({
    required String title,
    required String description,
    required String currentValue,
    required bool isEditing,
    required TextEditingController controller,
    required VoidCallback onEdit,
    required VoidCallback onSave,
    int maxLength = 50,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(color: _border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Expanded(
                child: Text(
                  title,
                  style: const TextStyle(
                    color: _green,
                    fontSize: 11,
                    letterSpacing: .7,
                    fontWeight: FontWeight.w900,
                  ),
                ),
              ),
              if (!isEditing)
                IconButton(
                  tooltip: 'Edit $title',
                  onPressed: onEdit,
                  icon: const Icon(Icons.edit_outlined, color: _muted, size: 20),
                ),
            ],
          ),
          Text(
            description,
            style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.35),
          ),
          const SizedBox(height: 12),
          if (isEditing)
            Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                  child: TextField(
                    controller: controller,
                    autofocus: true,
                    maxLength: maxLength,
                    minLines: 1,
                    maxLines: 3,
                    decoration: InputDecoration(
                      counterText: '',
                      filled: true,
                      fillColor: const Color(0xFFF5F8F6),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: const BorderSide(color: _border),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: const BorderSide(color: _border),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(12),
                        borderSide: const BorderSide(color: _green, width: 1.3),
                      ),
                    ),
                    onSubmitted: (_) => onSave(),
                  ),
                ),
                const SizedBox(width: 8),
                Material(
                  color: _green,
                  borderRadius: BorderRadius.circular(12),
                  child: InkWell(
                    onTap: onSave,
                    borderRadius: BorderRadius.circular(12),
                    child: const Padding(
                      padding: EdgeInsets.all(11),
                      child: Icon(Icons.check_rounded, color: Colors.white, size: 20),
                    ),
                  ),
                ),
              ],
            )
          else
            Text(
              currentValue,
              style: const TextStyle(
                color: _ink,
                fontSize: 16,
                fontWeight: FontWeight.w700,
                height: 1.35,
              ),
            ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final avatar = _getAvatarProvider(widget.myPic);

    return ColoredBox(
      color: const Color(0xFFF5F7F6),
      child: SafeArea(
        top: false,
        child: Column(
          children: [
            Container(
              height: 66,
              padding: const EdgeInsets.symmetric(horizontal: 12),
              decoration: const BoxDecoration(
                color: Colors.white,
                border: Border(bottom: BorderSide(color: _border)),
              ),
              child: Row(
                children: [
                  IconButton(
                    tooltip: 'Back',
                    onPressed: widget.onBack,
                    icon: const Icon(Icons.arrow_back_rounded, color: _ink),
                  ),
                  const SizedBox(width: 4),
                  const Expanded(
                    child: Text(
                      'Profile',
                      style: TextStyle(
                        color: _ink,
                        fontSize: 18,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final horizontal = constraints.maxWidth > 720
                      ? (constraints.maxWidth - 640) / 2
                      : 12.0;
                  final avatarRadius = constraints.maxWidth < 420 ? 58.0 : 70.0;

                  return ListView(
                    physics: const BouncingScrollPhysics(),
                    padding: EdgeInsets.fromLTRB(horizontal, 20, horizontal, 28),
                    children: [
                      Container(
                        padding: const EdgeInsets.fromLTRB(18, 24, 18, 20),
                        decoration: BoxDecoration(
                          gradient: const LinearGradient(
                            colors: [_green, Color(0xFF0A7C48)],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                          borderRadius: BorderRadius.circular(20),
                          boxShadow: [
                            BoxShadow(
                              color: _green.withOpacity(.18),
                              blurRadius: 22,
                              offset: const Offset(0, 9),
                            ),
                          ],
                        ),
                        child: Column(
                          children: [
                            Stack(
                              clipBehavior: Clip.none,
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(4),
                                  decoration: BoxDecoration(
                                    color: Colors.white.withOpacity(.18),
                                    shape: BoxShape.circle,
                                  ),
                                  child: CircleAvatar(
                                    radius: avatarRadius,
                                    backgroundColor: const Color(0xFFE7ECE9),
                                    backgroundImage: avatar,
                                    child: avatar == null
                                        ? Icon(
                                            Icons.person_rounded,
                                            size: avatarRadius,
                                            color: _green,
                                          )
                                        : null,
                                  ),
                                ),
                                Positioned(
                                  right: 2,
                                  bottom: 2,
                                  child: Material(
                                    color: _gold,
                                    shape: const CircleBorder(),
                                    elevation: 3,
                                    child: InkWell(
                                      customBorder: const CircleBorder(),
                                      onTap: () => _showSnackBar('Opening Image Picker...'),
                                      child: const Padding(
                                        padding: EdgeInsets.all(10),
                                        child: Icon(
                                          Icons.camera_alt_rounded,
                                          color: Colors.white,
                                          size: 20,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            const SizedBox(height: 18),
                            Text(
                              _currentName,
                              textAlign: TextAlign.center,
                              style: const TextStyle(
                                color: Colors.white,
                                fontSize: 21,
                                fontWeight: FontWeight.w900,
                              ),
                            ),
                            const SizedBox(height: 6),
                            Container(
                              padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(.13),
                                borderRadius: BorderRadius.circular(20),
                              ),
                              child: Text(
                                _currentAbout,
                                style: const TextStyle(
                                  color: Color(0xFFE7F2EB),
                                  fontSize: 12,
                                  fontWeight: FontWeight.w700,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(height: 18),
                      _editableCard(
                        title: 'YOUR NAME',
                        description:
                            'This name is shown to your Rockview messaging contacts.',
                        currentValue: _currentName,
                        isEditing: _isEditingName,
                        controller: _nameController,
                        maxLength: 25,
                        onEdit: () {
                          setState(() {
                            _isEditingName = true;
                            _nameController.text = _currentName;
                          });
                        },
                        onSave: _saveName,
                      ),
                      const SizedBox(height: 12),
                      _editableCard(
                        title: 'ABOUT',
                        description:
                            'A short availability or status message visible in your profile.',
                        currentValue: _currentAbout,
                        isEditing: _isEditingAbout,
                        controller: _aboutController,
                        maxLength: 100,
                        onEdit: () {
                          setState(() {
                            _isEditingAbout = true;
                            _aboutController.text = _currentAbout;
                          });
                        },
                        onSave: _saveAbout,
                      ),
                    ],
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
