// lib/screens/members/members.dart

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

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

import 'member_details.dart';

// ----------------------------------------------------------
// MODEL
// ----------------------------------------------------------
class Member {
  final int id;
  final String? profileImage;
  final String fullName;
  final String companyName;
  final String? phone;
  final String? flatNo;
  final String? blockNo;
  final String positions;
  final String? businessType;

  Member({
    required this.id,
    this.profileImage,
    required this.fullName,
    required this.companyName,
    this.phone,
    this.flatNo,
    this.blockNo,
    required this.positions,
    this.businessType,
  });

  factory Member.fromJson(Map<String, dynamic> json) {
    return Member(
      id: json['id'] is int
          ? json['id']
          : int.tryParse('${json['id']}') ?? 0,
      profileImage: json['profile_image'],
      fullName: json['full_name'] ?? json['fullName'] ?? '',
      companyName: json['company_name'] ?? json['companyName'] ?? '',
      phone: json['phone'],
      flatNo: json['flat_no'],
      blockNo: json['block_no'],
      positions: json['positions'] ?? json['role'] ?? 'Member',
      businessType: json['business_type'] ?? json['businessType'],
    );
  }

  String get profileImageUrl {
    if (profileImage == null || profileImage!.isEmpty) return '';
    const base = 'https://rmbferodeunited.in/uploads/profile_photo/';
    if (profileImage!.startsWith('http')) return profileImage!;
    return '$base$profileImage';
  }
}

// ----------------------------------------------------------
// SCREEN
// ----------------------------------------------------------
class MembersScreen extends StatefulWidget {
  final String teamCode;
  final String teamName;

  const MembersScreen({
    Key? key,
    this.teamCode = 'ALL',
    this.teamName = 'All Members',
  }) : super(key: key);

  @override
  State<MembersScreen> createState() => _MembersScreenState();
}

class _MembersScreenState extends State<MembersScreen> {
  static const apiBase = 'https://rmbferodeunited.in/api/members.php';

  late Future<List<Member>> _futureMembers;

  @override
  void initState() {
    super.initState();
    _futureMembers = _fetchMembers();
  }

  Future<List<Member>> _fetchMembers() async {
    Uri uri;

    if (widget.teamCode.isEmpty ||
        widget.teamCode.toUpperCase() == 'ALL') {
      uri = Uri.parse(apiBase);
    } else {
      uri = Uri.parse(
        '$apiBase?team_code=${Uri.encodeComponent(widget.teamCode)}',
      );
    }

    final res = await http.get(uri);

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

    final decoded = json.decode(res.body);

    List<dynamic> list;
    if (decoded is List) {
      list = decoded;
    } else if (decoded is Map<String, dynamic> &&
        decoded['members'] is List) {
      list = decoded['members'];
    } else {
      list = [];
    }

    final members = list
        .map((e) => Member.fromJson(e as Map<String, dynamic>))
        .toList();

    // 🔹 SORT MEMBERS A → Z BY FULL NAME
    members.sort(
          (a, b) => a.fullName.toLowerCase().compareTo(
        b.fullName.toLowerCase(),
      ),
    );

    return members;
  }

  Future<void> _refresh() async {
    setState(() {
      _futureMembers = _fetchMembers();
    });
    await _futureMembers;
  }

  @override
  Widget build(BuildContext context) {
    final membersTitle =
        getTranslate(context, 'members.members') ?? 'Members';

    final title = widget.teamName.isNotEmpty
        ? widget.teamName
        : membersTitle;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor, // primary background
        elevation: 0,
        iconTheme: const IconThemeData(
          color: Colors.white,         // white back arrow
        ),
        title: Text(
          title,
          style: const TextStyle(
            fontSize: 18,              // font size 18
            fontWeight: FontWeight.w600,
            color: Colors.white,       // white text
          ),
        ),
      ),
      body: FutureBuilder<List<Member>>(
        future: _futureMembers,
        builder: (context, snap) {
          if (snap.connectionState == ConnectionState.waiting) {
            return const Center(child: CupertinoActivityIndicator());
          }

          if (snap.hasError) {
            return Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('Error: ${snap.error}'),
                  const SizedBox(height: 12),
                  ElevatedButton(
                    onPressed: _refresh,
                    child: const Text('Retry'),
                  ),
                ],
              ),
            );
          }

          final list = snap.data ?? [];

          if (list.isEmpty) {
            return RefreshIndicator(
              onRefresh: _refresh,
              child: ListView(
                children: const [
                  SizedBox(height: 150),
                  Center(child: Text('No Members')),
                ],
              ),
            );
          }

          return RefreshIndicator(
            onRefresh: _refresh,
            child: ListView.builder(
              padding: const EdgeInsets.all(12),
              physics: const BouncingScrollPhysics(),
              itemCount: list.length,
              itemBuilder: (context, i) => _memberRow(list[i]),
            ),
          );
        },
      ),
    );
  }

  // ----------------------------------------------------------
  // MEMBER ROW
  // ----------------------------------------------------------
  Widget _memberRow(Member m) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (_) => MemberDetailsScreen(
              member: MemberDetail(
                id: m.id,
                profileImage: m.profileImage,
                fullName: m.fullName,
                roles: m.positions,
                qualification: null,
                companyName: m.companyName,
                businessType: m.businessType,
                phone: m.phone,
                email: null,
                ridNo: null,
                businessGiven: null,
                businessReceived: null,
                rToR: null,
                referrals: null,
                visitors: null,
                positions: m.positions,
                powerTeam: null,
              ),
            ),
          ),
        );
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 14),
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
        decoration: BoxDecoration(
          color: whiteColor,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black12.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 3),
            ),
          ],
        ),
        child: Row(
          children: [
            CircleAvatar(
              radius: 34,
              backgroundColor: d9EAF4Color,
              backgroundImage: m.profileImageUrl.isNotEmpty
                  ? NetworkImage(m.profileImageUrl)
                  : null,
              child: m.profileImageUrl.isEmpty
                  ? Text(
                m.fullName.isNotEmpty
                    ? m.fullName[0].toUpperCase()
                    : '?',
                style: semibold16Black33,
              )
                  : null,
            ),
            const SizedBox(width: 14),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    m.fullName,
                    style: semibold16Black33.copyWith(fontSize: 16.5),
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 6),
                  Text(
                    '${m.companyName}'
                        '${m.businessType != null && m.businessType!.isNotEmpty ? ' · ${m.businessType}' : ''}',
                    style: medium14Grey.copyWith(fontSize: 14.2),
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
