import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../../teams/application/teams_notifier.dart';
import '../application/profile_notifier.dart';
import '../domain/user_profile.dart';
import 'widgets/role_chip.dart';

/// Public, read-only profile page for any player or manager.
///
/// Anyone (including signed-out viewers) can land here from a team roster or
/// shared link.
class PlayerProfileScreen extends ConsumerWidget {
  const PlayerProfileScreen({super.key, required this.uid});

  final String uid;

  static const double _maxContentWidth = 760;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final async = ref.watch(profileByIdProvider(uid));

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () =>
              context.canPop() ? context.pop() : context.go('/teams'),
        ),
        title: const Text('PLAYER'),
      ),
      body: async.when(
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (e, _) => Center(child: Text('Could not load: $e')),
        data: (profile) {
          if (profile == null) {
            return const Center(child: Text('Player not found.'));
          }
          return Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: _maxContentWidth),
              child: _Body(profile: profile),
            ),
          );
        },
      ),
    );
  }
}

class _Body extends ConsumerWidget {
  const _Body({required this.profile});

  final UserProfile profile;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = Theme.of(context);
    final scheme = theme.colorScheme;

    final hasPhoto = profile.photoUrl != null && profile.photoUrl!.isNotEmpty;
    final initial = profile.displayName.isEmpty
        ? '?'
        : profile.displayName.characters.first;

    final team = profile.hasTeam
        ? ref.watch(teamByIdProvider(profile.teamId!))
        : null;

    return ListView(
      padding: const EdgeInsets.fromLTRB(20, 16, 20, 32),
      children: <Widget>[
        Center(
          child: Container(
            width: 112,
            height: 112,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: scheme.primaryContainer,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: scheme.primary.withValues(alpha: 0.25),
                  blurRadius: 24,
                  spreadRadius: 2,
                ),
              ],
            ),
            child: hasPhoto
                ? CircleAvatar(
                    radius: 56,
                    backgroundColor: scheme.primaryContainer,
                    backgroundImage: NetworkImage(profile.photoUrl!),
                  )
                : Text(
                    initial.toUpperCase(),
                    style: TextStyle(
                      color: scheme.onPrimaryContainer,
                      fontWeight: FontWeight.w800,
                      fontSize: 52,
                    ),
                  ),
          ),
        ),
        const SizedBox(height: 16),
        Center(
          child: Text(
            profile.displayName.isEmpty ? 'Unnamed' : profile.displayName,
            style: theme.textTheme.headlineSmall?.copyWith(
              fontWeight: FontWeight.w800,
            ),
          ),
        ),
        const SizedBox(height: 8),
        Center(child: RoleChip(role: profile.role)),
        if (profile.position != null && profile.position!.isNotEmpty) ...[
          const SizedBox(height: 12),
          Center(
            child: Container(
              padding: const EdgeInsets.symmetric(
                horizontal: 12,
                vertical: 6,
              ),
              decoration: BoxDecoration(
                color: scheme.surfaceContainerHighest,
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
                profile.position!.toUpperCase(),
                style: theme.textTheme.labelMedium?.copyWith(
                  color: scheme.onSurface,
                  letterSpacing: 1.2,
                  fontWeight: FontWeight.w700,
                ),
              ),
            ),
          ),
        ],
        const SizedBox(height: 24),
        if (team != null)
          Card(
            child: ListTile(
              leading: Icon(Icons.groups_outlined, color: scheme.primary),
              title: Text(
                'TEAM',
                style: theme.textTheme.labelSmall?.copyWith(
                  color: scheme.onSurfaceVariant,
                  letterSpacing: 1.2,
                  fontWeight: FontWeight.w700,
                ),
              ),
              subtitle: Padding(
                padding: const EdgeInsets.only(top: 2),
                child: Text(
                  team.name,
                  style: theme.textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
              trailing: const Icon(Icons.chevron_right),
              onTap: () => context.go('/teams/${team.id}'),
            ),
          ),
        if (profile.bio.isNotEmpty) ...[
          const SizedBox(height: 16),
          Text(
            'BIO',
            style: theme.textTheme.labelSmall?.copyWith(
              color: scheme.onSurfaceVariant,
              letterSpacing: 1.2,
              fontWeight: FontWeight.w700,
            ),
          ),
          const SizedBox(height: 6),
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(14),
            decoration: BoxDecoration(
              color: scheme.surfaceContainerHighest,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(color: scheme.outlineVariant),
            ),
            child: Text(
              profile.bio,
              style: theme.textTheme.bodyMedium,
            ),
          ),
        ],
      ],
    );
  }
}
