// lib/screens/members/teams.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 'members.dart';

class Team {
  final String code;
  final String name;

  Team({
    required this.code,
    required this.name,
  });

  factory Team.fromJson(Map<String, dynamic> json) {
    return Team(
      code: (json['code'] ?? '').toString(),
      name: (json['team_name'] ?? json['teamName'] ?? '').toString(),
    );
  }
}

class TeamsScreen extends StatefulWidget {
  const TeamsScreen({Key? key}) : super(key: key);

  @override
  State<TeamsScreen> createState() => _TeamsScreenState();
}

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

  late Future<List<Team>> _futureTeams;

  @override
  void initState() {
    super.initState();
    _futureTeams = _fetchTeams();
  }

  Future<List<Team>> _fetchTeams() async {
    final uri = Uri.parse('$apiBase?mode=teams');
    final res = await http.get(uri);

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

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

    List<dynamic> rawList;
    if (decoded is Map<String, dynamic>) {
      rawList = (decoded['teams'] ?? []) as List<dynamic>;
    } else if (decoded is List) {
      rawList = decoded;
    } else {
      rawList = [];
    }

    return rawList
        .map((e) => Team.fromJson(e as Map<String, dynamic>))
        .toList();
  }

  Future<void> _refresh() async {
    setState(() {
      _futureTeams = _fetchTeams();
    });
    await _futureTeams;
  }

  void _openMembers(Team team) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (_) => MembersScreen(
          teamCode: team.code,
          teamName: team.name,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final title = getTranslate(context, 'members.teams') ?? 'Teams';

    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0,
        leading: IconButton(
          onPressed: () => Navigator.pushNamedAndRemoveUntil(
              context, '/bottomBar', (route) => false),
          icon: const Icon(Icons.arrow_back, color: Colors.white),
        ),
        title: Text(
          title,
          style: const TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
      body: FutureBuilder<List<Team>>(
        future: _futureTeams,
        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 teams = snap.data ?? [];

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

          return RefreshIndicator(
            onRefresh: _refresh,
            child: ListView.separated(
              padding: const EdgeInsets.all(12),
              itemCount: teams.length,
              separatorBuilder: (_, __) => const SizedBox(height: 8),
              itemBuilder: (context, index) {
                final t = teams[index];
                return InkWell(
                  onTap: () => _openMembers(t),
                  child: Container(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 16, 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: 18,
                          backgroundColor: d9EAF4Color,
                          child: Text(
                            t.name.isNotEmpty
                                ? t.name[0].toUpperCase()
                                : '?',
                            style: semibold16Black33,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            t.name,
                            style: semibold16Black33,
                          ),
                        ),
                        const Icon(Icons.chevron_right, color: greyColor),
                      ],
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}
