import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter/services.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';
import 'package:slrpg_app/src/shared/data/repositories/workout_repository.dart';
import '../../../../core/theme/app_theme.dart';
import '../../../../shared/data/repositories/user_repository.dart';
import '../../data/repositories/party_repository.dart';
import '../../domain/entities/party.dart';
import '../../domain/entities/party_member.dart';
import '../../../gamification/presentation/widgets/avatar_renderer.dart';
import '../../../../shared/data/repositories/cycle_repository.dart';

class LobbyScreen extends ConsumerStatefulWidget {
  final String partyId;

  const LobbyScreen({super.key, required this.partyId});

  @override
  ConsumerState<LobbyScreen> createState() => _LobbyScreenState();
}

class _LobbyScreenState extends ConsumerState<LobbyScreen> {
  Future<void> _leaveParty() async {
    final currentUser = await ref.read(userRepositoryProvider).getLocalUser();
    if (currentUser != null) {
      await ref
          .read(partyRepositoryProvider)
          .leaveParty(widget.partyId, currentUser.serverId!);
    }
    if (mounted) context.go('/hub');
  }

  int _calculateRaidHp(int memberCount) {
    const int baseVolumePerPlayer = 50;
    return (baseVolumePerPlayer * memberCount * 1.1).round();
  }

  @override
  Widget build(BuildContext context) {
    final partyAsync = ref.watch(partyStreamProvider(widget.partyId));
    final membersAsync = ref.watch(partyMembersStreamProvider(widget.partyId));
    final currentUser = ref.watch(userRepositoryProvider).getLocalUser();
    final l10n = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        title: Text(l10n.lobbyTitle),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _leaveParty,
        ),
      ),
      body: partyAsync.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (err, _) => Center(child: Text('Error: $err')),
        data: (party) {
          if (party.status == 'active') {
            return FutureBuilder(
              future: _findNextWorkout(),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.done &&
                    snapshot.hasData) {
                  final next = snapshot.data as Map<String, int>;

                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    if (mounted) {
                      context.go('/battle/${party.id}',
                          extra: {'week': next['week'], 'day': next['day']});
                    }
                  });
                  return const Center(child: Text('Entering Battle...'));
                }
                return Center(child: Text(l10n.lobbyStatusActive));
              },
            );
          }

          return Column(
            children: [
              Container(
                width: double.infinity,
                padding: const EdgeInsets.all(24),
                color: AppTheme.surfaceColor,
                child: Column(
                  children: [
                    Text(l10n.lobbyPartyCode,
                        style: TextStyle(color: Colors.grey)),
                    const SizedBox(height: 8),
                    InkWell(
                      onTap: () {
                        Clipboard.setData(ClipboardData(text: party.code));
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(content: Text(l10n.lobbyCodeCopied)),
                        );
                      },
                      child: Text(
                        party.code,
                        style: const TextStyle(
                          fontSize: 48,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 8,
                          color: AppTheme.primaryColor,
                        ),
                      ),
                    ),
                    Text(l10n.lobbyTapToCopy,
                        style: TextStyle(fontSize: 12, color: Colors.grey)),
                  ],
                ),
              ),
              Expanded(
                child: membersAsync.when(
                  loading: () =>
                      const Center(child: CircularProgressIndicator()),
                  error: (e, _) =>
                      Center(child: Text('Error loading members: $e')),
                  data: (members) {
                    return ListView.builder(
                      padding: const EdgeInsets.all(16),
                      itemCount: members.length,
                      itemBuilder: (context, index) {
                        final member = members[index];
                        return _MemberCard(member: member);
                      },
                    );
                  },
                ),
              ),
              FutureBuilder(
                future: currentUser,
                builder: (context, snapshot) {
                  if (!snapshot.hasData) return const SizedBox();
                  final myId = snapshot.data!.serverId;
                  final isHost = party.hostId == myId;

                  final myMember = membersAsync.value
                      ?.where((m) => m.userId == myId)
                      .firstOrNull;
                  final isReady = myMember?.isReady ?? false;

                  return Container(
                    padding: const EdgeInsets.all(16),
                    decoration: const BoxDecoration(
                      color: AppTheme.surfaceColor,
                      border: Border(top: BorderSide(color: Colors.white10)),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor:
                                  isReady ? Colors.grey : AppTheme.primaryColor,
                              padding: const EdgeInsets.symmetric(vertical: 16),
                            ),
                            onPressed: () {
                              ref
                                  .read(partyRepositoryProvider)
                                  .setReady(party.id, !isReady);
                            },
                            child: Text(
                              isReady ? l10n.lobbyNotReady : l10n.lobbyReady,
                              style:
                                  const TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                        if (isHost) ...[
                          const SizedBox(width: 16),
                          Expanded(
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.redAccent,
                                padding:
                                    const EdgeInsets.symmetric(vertical: 16),
                              ),
                              onPressed: () async {
                                final members = membersAsync.value ?? [];
                                final memberCount = members.length;
                                final raidHp = _calculateRaidHp(memberCount);

                                await ref
                                    .read(partyRepositoryProvider)
                                    .startRaid(party.id, customHp: raidHp);
                                // ref
                                //     .read(partyRepositoryProvider)
                                //     .startRaid(party.id);
                              },
                              child: Text(
                                l10n.lobbyStartRaid,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.white),
                              ),
                            ),
                          ),
                        ],
                      ],
                    ),
                  );
                },
              ),
            ],
          );
        },
      ),
    );
  }

  Future<Map<String, int>> _findNextWorkout() async {
    final cycleRepo = ref.read(cycleRepositoryProvider);
    final workoutRepo = ref.read(workoutRepositoryProvider);

    final activeCycle = await cycleRepo.getCurrentCycle();

    int targetWeek = 1;
    int targetDay = 1;

    if (activeCycle != null) {
      final cycleId = activeCycle.serverId ?? activeCycle.id.toString();

      for (int w = 1; w <= 4; w++) {
        for (int d = 1; d <= 3; d++) {
          final workout = await workoutRepo.getWorkoutByWeekDay(
              cycleId: cycleId, week: w, day: d);

          if (workout == null || workout.completedAt == null) {
            return {'week': w, 'day': d};
          }
        }
      }
      return {'week': 1, 'day': 1};
    }

    return {'week': 1, 'day': 1};
  }
}

class _MemberCard extends StatelessWidget {
  final PartyMember member;

  const _MemberCard({required this.member});

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: ListTile(
        leading: SizedBox(
          width: 40,
          height: 40,
          child: member.avatar != null
              ? AvatarRenderer(config: member.avatar!, size: 40)
              : const CircleAvatar(child: Icon(Icons.person)),
        ),
        title: Text(member.username ?? 'Unknown'),
        trailing: member.isReady
            ? const Icon(Icons.check_circle, color: Colors.green)
            : const Icon(Icons.circle_outlined, color: Colors.grey),
      ),
    );
  }
}

final partyStreamProvider =
    StreamProvider.autoDispose.family<Party, String>((ref, partyId) {
  return ref.watch(partyRepositoryProvider).subscribeToParty(partyId);
});

final partyMembersStreamProvider = StreamProvider.autoDispose
    .family<List<PartyMember>, String>((ref, partyId) {
  return ref.watch(partyRepositoryProvider).subscribeToMembers(partyId);
});
