import 'dart:convert';

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

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

  @override
  State<MemberDetailsScreen> createState() => _MemberDetailsScreenState();
}

class _MemberDetailsScreenState extends State<MemberDetailsScreen> {
  static const String _baseUrl =
      'https://gelite.asia/api/members_details.php';

  Map<String, dynamic>? _memberArg; // from previous page
  Map<String, dynamic>? _memberDetails;

  bool _isLoading = true;
  String? _errorMessage;
  bool _didLoadFromArgs = false;

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (!_didLoadFromArgs) {
      final args = ModalRoute.of(context)?.settings.arguments;
      if (args is Map) {
        _memberArg = args.cast<String, dynamic>();
      } else {
        _memberArg = {};
      }
      _didLoadFromArgs = true;
      _fetchMemberDetails();
      _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,
      );
    }
  }


  // ===============================
  // API CALL (with debug prints)
  // ===============================
  Future<void> _fetchMemberDetails() async {
    try {
      final String? wpNo =
      (_memberArg?['wp_no'] ?? _memberArg?['flatNo'])?.toString();
      final String? id = _memberArg?['id']?.toString();

      if (wpNo == null && id == null) {
        setState(() {
          _errorMessage = 'No member identifier provided';
          _isLoading = false;
        });
        return;
      }

      final Map<String, String> queryParams = {};
      if (wpNo != null && wpNo.isNotEmpty) {
        queryParams['wp_no'] = wpNo;
      } else if (id != null && id.isNotEmpty) {
        queryParams['id'] = id;
      }

      final uri = Uri.parse(_baseUrl).replace(queryParameters: queryParams);

      print('========= MEMBER DETAILS REQUEST =========');
      print('METHOD : GET');
      print('URL    : $uri');
      print('PARAMS : ${jsonEncode(queryParams)}');

      final response = await http.get(uri);

      print('========= MEMBER DETAILS RESPONSE =========');
      print('STATUS : ${response.statusCode}');
      print('BODY   : ${response.body}');

      if (response.statusCode == 200) {
        final dynamic jsonBody = json.decode(response.body);

        print('========= DECODED DETAILS JSON =========');
        print(jsonEncode(jsonBody));

        if (jsonBody is Map &&
            jsonBody['status'] == 'success' &&
            jsonBody['data'] is Map) {
          final Map<String, dynamic> data =
          (jsonBody['data'] as Map).cast<String, dynamic>();

          setState(() {
            _memberDetails = data;
            _isLoading = false;
          });
        } else {
          setState(() {
            _errorMessage = 'Invalid API response format';
            _isLoading = false;
          });
        }
      } else {
        setState(() {
          _errorMessage = 'Server error: ${response.statusCode}';
          _isLoading = false;
        });
      }
    } catch (e) {
      print('DETAILS API ERROR: $e');
      setState(() {
        _errorMessage = 'Failed to load member details';
        _isLoading = false;
      });
    }
  }

  // ===============================
  // UI
  // ===============================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: screenBgColor,
      appBar: AppBar(
        backgroundColor: whiteColor,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(Icons.arrow_back, color: blackColor),
        ),
        title: Text(
          tr(context, 'members.member'),
          style: medium18Black,
        ),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(fixPadding * 2),
          child: Text(
            _errorMessage!,
            style: regular16Grey,
            textAlign: TextAlign.center,
          ),
        ),
      );
    }

    if (_memberDetails == null) {
      return Center(
        child: Text(
          tr(context, 'no_data'),
          style: regular16Grey,
        ),
      );
    }

    final d = _memberDetails!;

    final String name = (d['name'] ?? '').toString();
    final String vertical = (d['vertical'] ?? '').toString();
    final String wpNo = (d['wp_no'] ?? '').toString();
    final String phone = (d['phone_no'] ?? '').toString();
    final String dob = (d['dob'] ?? '').toString();
    final String weddingDate = (d['wedding_date'] ?? '').toString();
    final String bloodGroup = (d['blood_group'] ?? '').toString();
    final String status = (d['status'] ?? '').toString();
    final String kulam = (d['kulam'] ?? '').toString();
    final String kovil = (d['kovil'] ?? '').toString();
    final String homeAddress = (d['home_address'] ?? '').toString();
    final String officeAddress = (d['office_address'] ?? '').toString();
    final String about = (d['about'] ?? '').toString();
    final String dealingBrands = (d['dealing_brands'] ?? '').toString();
    final String profilePhoto = (d['profile_photo'] ?? '').toString();

    ImageProvider imageProvider;
    if (profilePhoto.isNotEmpty) {
      imageProvider = NetworkImage(profilePhoto);
    } else {
      imageProvider = const AssetImage('assets/members/member-1.png');
    }

    return SingleChildScrollView(
      physics: const BouncingScrollPhysics(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // ===== HEADER =====
          Container(
            padding: const EdgeInsets.fromLTRB(16, 24, 16, 24),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                colors: [darkBlueColor, greenColor],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
            ),
            child: Row(
              children: [
                CircleAvatar(
                  radius: 42,
                  backgroundColor: whiteColor,
                  child: CircleAvatar(
                    radius: 38,
                    backgroundImage: imageProvider,
                  ),
                ),
                widthSpace,
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        name,
                        style: medium18White.copyWith(fontSize: 20),
                        overflow: TextOverflow.ellipsis,
                      ),
                      height5Space,
                      if (vertical.isNotEmpty)
                        Text(
                          vertical.toUpperCase(),
                          style: regular14White.copyWith(
                            color: Colors.white70,
                            letterSpacing: 0.4,
                          ),
                        ),
                      height5Space,
                      Row(
                        children: [
                          if (wpNo.isNotEmpty)
                            _smallInfoChip(
                              icon: Icons.badge_outlined,
                              value: wpNo,
                            ),
                          if (wpNo.isNotEmpty && phone.isNotEmpty)
                            widthBox(6),
                          if (phone.isNotEmpty)
                            _smallInfoChip(
                              icon: Icons.phone_iphone,
                              value: phone,
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // ===== CONTENT =====
          Padding(
            padding: const EdgeInsets.all(fixPadding * 1.5),
            child: Column(
              children: [
                _sectionCard(
                  title: tr(context, 'details'),
                  children: [
                    if (dob.isNotEmpty)
                      _detailRow(
                        label: 'Date of Birth',
                        value: dob,
                      ),
                    if (weddingDate.isNotEmpty)
                      _detailRow(
                        label: 'Wedding Date',
                        value: weddingDate,
                      ),
                    if (bloodGroup.isNotEmpty)
                      _detailRow(
                        label: 'Blood Group',
                        value: bloodGroup,
                      ),
                    if (status.isNotEmpty)
                      _detailRow(
                        label: 'Status',
                        value: status,
                      ),
                    if (kulam.isNotEmpty)
                      _detailRow(
                        label: 'Kulam',
                        value: kulam,
                      ),
                    if (kovil.isNotEmpty)
                      _detailRow(
                        label: 'Kovil',
                        value: kovil,
                      ),
                  ],
                ),

                if (homeAddress.isNotEmpty || officeAddress.isNotEmpty)
                  _sectionCard(
                    title: 'Address',
                    children: [
                      if (homeAddress.isNotEmpty)
                        _detailRow(
                          label: 'Home',
                          value: homeAddress,
                          multiline: true,
                        ),
                      if (officeAddress.isNotEmpty)
                        _detailRow(
                          label: 'Office',
                          value: officeAddress,
                          multiline: true,
                        ),
                    ],
                  ),

                if (about.isNotEmpty)
                  _sectionCard(
                    title: 'About',
                    children: [
                      _detailRow(
                        label: '',
                        value: about,
                        multiline: true,
                      ),
                    ],
                  ),

                if (dealingBrands.isNotEmpty)
                  _sectionCard(
                    title: 'Dealing Brands',
                    children: [
                      _detailRow(
                        label: '',
                        value: dealingBrands,
                        multiline: true,
                      ),
                    ],
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ===============================
  // Reusable widgets
  // ===============================

  Widget _smallInfoChip({
    required IconData icon,
    required String value,
  }) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: whiteColor.withOpacity(0.12),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(color: whiteColor.withOpacity(0.3), width: 0.7),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 14, color: whiteColor),
          width5Space,
          Text(
            value,
            style: regular12Grey.copyWith(color: whiteColor),
          ),
        ],
      ),
    );
  }

  Widget _sectionCard({
    required String title,
    required List<Widget> children,
  }) {
    if (children.isEmpty) return const SizedBox.shrink();

    return Container(
      margin: const EdgeInsets.only(bottom: fixPadding * 1.5),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(14),
        boxShadow: [
          BoxShadow(
            color: originalBlackColor.withOpacity(0.06),
            blurRadius: 6,
            offset: const Offset(0, 3),
          ),
        ],
      ),
      child: Column(
        children: [
          // title with colored left bar
          Container(
            padding: const EdgeInsets.symmetric(
              horizontal: fixPadding * 1.3,
              vertical: fixPadding * 0.9,
            ),
            decoration: BoxDecoration(
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(14),
                topRight: Radius.circular(14),
              ),
              color: screenBgColor,
            ),
            child: Row(
              children: [
                Container(
                  width: 4,
                  height: 18,
                  decoration: BoxDecoration(
                    color: primaryColor,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                widthSpace,
                Text(title, style: medium16Black),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(
              fixPadding * 1.4,
              fixPadding,
              fixPadding * 1.4,
              fixPadding,
            ),
            child: Column(
              children: children,
            ),
          ),
        ],
      ),
    );
  }

  Widget _detailRow({
    required String label,
    required String value,
    bool multiline = false,
  }) {
    if (value.isEmpty) return const SizedBox.shrink();

    final labelWidget = label.isEmpty
        ? const SizedBox.shrink()
        : SizedBox(
      width: 110,
      child: Text(
        label,
        style: regular15Black,
      ),
    );

    final valueWidget = Text(
      value,
      style: regular14Grey,
      textAlign: TextAlign.left,
    );

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        crossAxisAlignment:
        multiline ? CrossAxisAlignment.start : CrossAxisAlignment.center,
        children: [
          labelWidget,
          if (label.isNotEmpty) widthBox(6),
          Expanded(child: valueWidget),
        ],
      ),
    );
  }
}
