import 'dart:convert';

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

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

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

class _MembersScreenState extends State<MembersScreen> {
  static const String _baseUrl =
      'https://gelite.asia/api/members.php?type=member';

  /// Flat member list
  List<Map<String, dynamic>> members = [];

  bool isLoading = true;
  String? errorMessage;

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

  // =========================
  // ✅ API CALL
  // =========================
  Future<void> fetchMembers() async {
    try {
      final uri = Uri.parse(_baseUrl);

      print('========= MEMBERS API REQUEST =========');
      print('METHOD : GET');
      print('URL    : $uri');

      final response = await http.get(uri);

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

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

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

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

          // ✅ FLATTEN BLOCK STRUCTURE
          for (final blockEntry in data) {
            if (blockEntry is Map &&
                blockEntry['members'] != null &&
                blockEntry['members'] is List) {
              for (final m in blockEntry['members']) {
                if (m is Map) {
                  final member = m.cast<String, dynamic>();
                  print('MEMBER ITEM => ${jsonEncode(member)}');
                  allMembers.add(member);
                }
              }
            }
          }

          setState(() {
            members = allMembers;
            isLoading = false;
          });
        } else {
          setState(() {
            errorMessage = 'Invalid API response format';
            isLoading = false;
          });
        }
      } else {
        setState(() {
          errorMessage = 'Server error: ${response.statusCode}';
          isLoading = false;
        });
      }
    } catch (e) {
      print('API ERROR: $e');
      setState(() {
        errorMessage = 'Failed to load members';
        isLoading = false;
      });
    }
  }

  // =========================
  // ✅ UI
  // =========================
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: whiteColor,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(Icons.arrow_back, color: blackColor),
        ),
        title: Text(
          tr(context, 'members.member'),
          style: medium18Black,
        ),
      ),
      body: Column(
        children: [
          topImage(),
          Expanded(child: buildBody()),
        ],
      ),
    );
  }

  Widget buildBody() {
    if (isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (errorMessage != null) {
      return Center(
        child: Text(errorMessage!, style: regular16Grey),
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.symmetric(vertical: fixPadding),
      physics: const BouncingScrollPhysics(),
      itemCount: members.length,
      itemBuilder: (context, index) => memberTile(members[index]),
    );
  }

  // =========================
  // ✅ MEMBER TILE (uses only profile_photo)
  // =========================
  Widget memberTile(Map<String, dynamic> member) {
    final String name = (member['name'] ?? '').toString();
    final String block = (member['block'] ?? '').toString();

    // ✅ Only profile_photo from API
    final String imageUrl = (member['profile_photo'] ?? '').toString();

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

    return InkWell(
      onTap: () {
        print('CLICKED MEMBER => ${jsonEncode(member)}');

        Navigator.pushNamed(
          context,
          '/memberDetails',
          arguments: member,
        );
      },
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: fixPadding / 2),
        padding: const EdgeInsets.symmetric(
          horizontal: fixPadding * 2,
          vertical: fixPadding,
        ),
        color: whiteColor,
        child: Row(
          children: [
            Container(
              height: 48,
              width: 48,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(6),
                image: DecorationImage(
                  image: imageProvider,
                  fit: BoxFit.cover,
                ),
              ),
            ),
            widthSpace,
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    name,
                    style: regular15Black,
                    overflow: TextOverflow.ellipsis,
                  ),
                  height5Space,
                  Text(
                    block,
                    style: regular14Grey,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // =========================
  // ✅ TOP IMAGE
  // =========================
  Widget topImage() {
    return Container(
      height: 125,
      width: double.infinity,
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage("assets/members/top-image.png"),
          fit: BoxFit.cover,
        ),
      ),
    );
  }
}
