import 'package:flutter/material.dart';

import 'package:provider/provider.dart';

import 'package:cached_network_image/cached_network_image.dart';

import 'package:pshared/provider/account.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class AccountAvatar extends StatelessWidget {
  final double? size;
  final bool showHeader;
  final String? fallbackUrl;
  final AccountProvider? provider;

  const AccountAvatar({
    super.key,
    this.size,
    this.showHeader = true,
    this.fallbackUrl,
    this.provider,
  });

  @override
  Widget build(BuildContext context) {
    if (provider != null) {
      return _buildAvatar(context, provider!);
    }

    return Consumer<AccountProvider>(
      builder: (context, provider, _) => _buildAvatar(context, provider),
    );
  }

  Widget _buildAvatar(BuildContext context, AccountProvider provider) {
    final avatarUrl = (provider.account?.avatarUrl ?? fallbackUrl)?.trim();
    final hasAvatar = avatarUrl?.isNotEmpty == true;
    final radius = size != null ? size! / 2 : null;
    final double placeholderIconSize = size != null ? size! * 0.55 : 50;

    final avatar = CircleAvatar(
      radius: radius,
      backgroundImage: hasAvatar ? CachedNetworkImageProvider(avatarUrl!) : null,
      child: hasAvatar ? null : Icon(Icons.account_circle, size: placeholderIconSize),
    );

    if (!showHeader) return avatar;

    final loc = AppLocalizations.of(context)!;
    return UserAccountsDrawerHeader(
      accountName: Text(provider.account?.fullName ?? loc.userNamePlaceholder),
      accountEmail: Text(provider.account?.login ?? loc.usernameHint),
      currentAccountPicture: avatar,
    );
  }
}
