// lib/screens/members/member_details.dart
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

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

/// ======================================================
/// MEMBER MODEL (UNCHANGED – FULL)
/// ======================================================
class MemberDetail {
  final int id;
  final String? profileImage;
  final String? profileImageUrlFromApi;
  final String fullName;
  final String? roles;
  final String? qualification;
  final String companyName;
  final String? businessType;
  final String? phone;
  final String? email;
  final String? ridNo;
  final String? businessGiven;
  final String? businessReceived;
  final String? rToR;
  final String? referrals;
  final String? visitors;
  final String? positions;
  final String? powerTeam;
  final String? address;
  final String? dob;
  final String? anniversary;
  final String? companyOpenDate;
  final String? points;
  final String? status;
  final String? createdAt;
  final String? updatedAt;

  MemberDetail({
    required this.id,
    this.profileImage,
    this.profileImageUrlFromApi,
    required this.fullName,
    this.roles,
    this.qualification,
    required this.companyName,
    this.businessType,
    this.phone,
    this.email,
    this.ridNo,
    this.businessGiven,
    this.businessReceived,
    this.rToR,
    this.referrals,
    this.visitors,
    this.positions,
    this.powerTeam,
    this.address,
    this.dob,
    this.anniversary,
    this.companyOpenDate,
    this.points,
    this.status,
    this.createdAt,
    this.updatedAt,
  });

  static String? _toStr(dynamic v) => v == null ? null : v.toString();

  factory MemberDetail.fromMergedMap(Map<String, dynamic> m) {
    final idRaw = m['id'] ?? m['ID'] ?? m['Id'] ?? 0;
    final id = idRaw is int ? idRaw : int.tryParse(idRaw.toString()) ?? 0;

    return MemberDetail(
      id: id,
      profileImage: _toStr(m['profile_image']),
      profileImageUrlFromApi: _toStr(m['profile_image_url']),
      fullName: _toStr(m['full_name']) ?? '',
      roles: _toStr(m['roles']),
      qualification: _toStr(m['qualification']),
      companyName: _toStr(m['company_name']) ?? '',
      businessType: _toStr(m['business_type']),
      phone: _toStr(m['phone']),
      email: _toStr(m['email']),
      ridNo: _toStr(m['rid_no']),
      businessGiven: _toStr(m['business_given']),
      businessReceived: _toStr(m['business_received']),
      rToR: _toStr(m['r_to_r']),
      referrals: _toStr(m['referrals']),
      visitors: _toStr(m['visitors']),
      positions: _toStr(m['positions']),
      powerTeam: _toStr(m['power_team']),
      address: _toStr(m['address']),
      dob: _toStr(m['dob']),
      anniversary: _toStr(m['anniversary']),
      companyOpenDate: _toStr(m['company_open_date']),
      points: _toStr(m['points']),
      status: _toStr(m['status']),
      createdAt: _toStr(m['created_at']),
      updatedAt: _toStr(m['updated_at']),
    );
  }

  String get profileImageUrl {
    if ((profileImageUrlFromApi ?? '').isNotEmpty) {
      return profileImageUrlFromApi!;
    }
    if ((profileImage ?? '').isEmpty) return '';
    return 'https://rmbferodeunited.in/uploads/profile_photo/$profileImage';
  }
}

/// ======================================================
/// MEMBER DETAILS SCREEN
/// ======================================================
class MemberDetailsScreen extends StatefulWidget {
  final MemberDetail? member;
  final int? memberId;

  const MemberDetailsScreen({
    Key? key,
    this.member,
    this.memberId,
  })  : assert(member != null || memberId != null),
        super(key: key);

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

class _MemberDetailsScreenState extends State<MemberDetailsScreen> {
  static const apiBase =
      'https://rmbferodeunited.in/api/members_detail.php';

  late Future<MemberDetail> _futureDetail;
  bool _showRawJson = false;
  String _rawJson = '';

  @override
  void initState() {
    super.initState();
    _checkRID();
    final id = widget.member?.id ?? widget.memberId!;
    _futureDetail = _fetchMember(id);
  }

  Future<void> _checkRID() async {
    final prefs = await SharedPreferences.getInstance();
    if ((prefs.getString('rid_no') ?? '').isEmpty) {
      if (!mounted) return;
      Navigator.pushNamedAndRemoveUntil(context, '/login', (_) => false);
    }
  }

  Future<MemberDetail> _fetchMember(int id) async {
    final res = await http.get(Uri.parse('$apiBase?id=$id'));
    _rawJson = res.body;

    if (res.statusCode != 200) {
      throw Exception('Failed to fetch member');
    }

    final decoded = json.decode(res.body);
    final Map<String, dynamic> merged = {};

    if (decoded is Map) {
      merged.addAll(decoded.map((k, v) => MapEntry(k.toString(), v)));
    }

    if (decoded is List && decoded.isNotEmpty && decoded.first is Map) {
      merged.addAll(
        (decoded.first as Map)
            .map((k, v) => MapEntry(k.toString(), v)),
      );
    }

    return MemberDetail.fromMergedMap(merged);
  }

  Future<void> _callNow(String phone) async {
    final uri = Uri.parse('tel:$phone');
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    }
  }

  Widget _row(BuildContext context, String key, String? value) {
    final label =
        getTranslate(context, key) ?? key.split('.').last.replaceAll('_', ' ');
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 6),
      child: Row(
        children: [
          SizedBox(width: 130, child: Text(label, style: semibold14Black33)),
          Expanded(
            child: Text(
              value?.isNotEmpty == true ? value! : '-',
              style: medium14Grey,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final title =
        getTranslate(context, 'members.details') ?? 'Member Details';

    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor, // your primary color
        elevation: 0,
        leading: const BackButton(
          color: Colors.white, // white back arrow
        ),
        title: GestureDetector(
          onLongPress: () => setState(() => _showRawJson = !_showRawJson),
          child: const Text(
            'Member Details',
            style: TextStyle(
              color: Colors.white, // white text
              fontSize: 18,        // font size 18
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ),
      body: FutureBuilder<MemberDetail>(
        future: _futureDetail,
        builder: (context, snap) {
          if (snap.connectionState == ConnectionState.waiting) {
            return const Center(child: CupertinoActivityIndicator());
          }
          if (snap.hasError) {
            return Center(child: Text(snap.error.toString()));
          }

          final m = snap.data!;

          return Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(fixPadding * 1.8),
                  child: Column(
                    children: [
                      /// TOP CARD
                      Container(
                        padding: const EdgeInsets.all(fixPadding),
                        decoration: BoxDecoration(
                          color: whiteColor,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: blackColor.withOpacity(0.06),
                              blurRadius: 8,
                            ),
                          ],
                        ),
                        child: Column(
                          children: [
                            CircleAvatar(
                              radius: 46,
                              backgroundImage: m.profileImageUrl.isNotEmpty
                                  ? NetworkImage(m.profileImageUrl)
                                  : null,
                              backgroundColor: d9EAF4Color,
                              child: m.profileImageUrl.isEmpty
                                  ? Text(
                                m.fullName[0].toUpperCase(),
                                style: semibold24Black33,
                              )
                                  : null,
                            ),
                            const SizedBox(height: 12),
                            Text(m.fullName, style: semibold18Black33),
                            Text(m.companyName, style: medium14Grey),
                            const SizedBox(height: 14),

                            /// CENTERED CALL BUTTON
                            SizedBox(
                              width: double.infinity,
                              child: ElevatedButton.icon(
                                icon: const Icon(Icons.call),
                                label: const Text('Call Me'),
                                onPressed: m.phone != null
                                    ? () => _callNow(m.phone!)
                                    : null,
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: blueColor,
                                  padding: const EdgeInsets.symmetric(
                                    vertical: 14,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 16),

                      /// INFORMATION
                      Container(
                        padding: const EdgeInsets.all(fixPadding),
                        decoration: BoxDecoration(
                          color: whiteColor,
                          borderRadius: BorderRadius.circular(12),
                          boxShadow: [
                            BoxShadow(
                              color: blackColor.withOpacity(0.04),
                              blurRadius: 6,
                            ),
                          ],
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('Information', style: semibold16Black33),
                            _row(context, 'members.qualification', m.qualification),
                            _row(context, 'members.company_name', m.companyName),
                            _row(context, 'members.business_type', m.businessType),
                            _row(context, 'members.phone', m.phone),
                            _row(context, 'members.email', m.email),
                            _row(context, 'members.rid_no', m.ridNo),
                            _row(context, 'members.r_to_r', m.rToR),
                            _row(context, 'members.referrals', m.referrals),
                            _row(context, 'members.visitors', m.visitors),
                            _row(context, 'members.positions', m.positions),
                            _row(context, 'members.power_team', m.powerTeam),
                            _row(context, 'members.address', m.address),
                            _row(context, 'members.dob', m.dob),
                            _row(context, 'members.anniversary', m.anniversary),
                            _row(context, 'members.company_open_date',
                                m.companyOpenDate),
                            _row(context, 'members.points', m.points),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              /// RAW JSON DEBUG
              AnimatedCrossFade(
                firstChild: const SizedBox.shrink(),
                secondChild: Container(
                  padding: const EdgeInsets.all(12),
                  color: Colors.black12,
                  child: SingleChildScrollView(
                    child: Text(
                      _rawJson,
                      style: const TextStyle(fontSize: 12),
                    ),
                  ),
                ),
                crossFadeState: _showRawJson
                    ? CrossFadeState.showSecond
                    : CrossFadeState.showFirst,
                duration: const Duration(milliseconds: 200),
              ),
            ],
          );
        },
      ),
    );
  }
}
