import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:kasy_kit/components/components.dart';
import 'package:kasy_kit/core/data/models/user.dart';
import 'package:kasy_kit/core/states/user_state_notifier.dart';
import 'package:kasy_kit/core/theme/theme.dart';
import 'package:kasy_kit/features/settings/ui/widgets/avatar_utils.dart';
import 'package:kasy_kit/i18n/translations.g.dart';

/// Diameter used beside chat bubbles.
const double kLlmChatAvatarDiameter = 32;

/// Diameter shown in the empty state hero.
const double kLlmChatEmptyAvatarDiameter = 64;

/// Bundled launcher icon ([flutter_launcher_icons] → `assets/images/icon.png`).
const String kLlmChatAppIconAsset = 'assets/images/icon.png';

/// Project / assistant avatar — app icon when bundled, [KasyAvatar] fallback otherwise.
class LlmChatAssistantAvatar extends StatelessWidget {
  const LlmChatAssistantAvatar({
    super.key,
    this.diameter = kLlmChatAvatarDiameter,
    this.showShadow = false,
  });

  final double diameter;
  final bool showShadow;

  @override
  Widget build(BuildContext context) {
    return KasyAvatar(
      diameter: diameter,
      image: const AssetImage(kLlmChatAppIconAsset),
      icon: KasyIcons.packageOutline,
      fallbackSurface: KasyAvatarFallbackSurface.soft,
      showShadow: showShadow,
      semanticLabel: t.home.cards.assistant_title,
    );
  }
}

/// User avatar resolved from profile photo, initials, or [KasyAvatar] fallback.
class LlmChatUserAvatar extends ConsumerWidget {
  const LlmChatUserAvatar({
    super.key,
    this.diameter = kLlmChatAvatarDiameter,
    this.showShadow = false,
  });

  final double diameter;
  final bool showShadow;

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userStateNotifierProvider).user;
    return switch (user) {
      AuthenticatedUserData(
        :final id,
        :final name,
        :final email,
        :final avatarPath,
      ) =>
        _LlmChatUserAvatarContent(
          diameter: diameter,
          userId: id,
          avatarPath: avatarPath,
          initials: _initialsFrom(name, email),
          showShadow: showShadow,
        ),
      _ => KasyAvatar(
        diameter: diameter,
        icon: KasyIcons.person,
        fallbackSurface: KasyAvatarFallbackSurface.soft,
        tone: KasyAvatarTone.neutral,
        showShadow: showShadow,
      ),
    };
  }

  String? _initialsFrom(String? name, String email) {
    final String? trimmedName = name?.trim();
    if (trimmedName != null && trimmedName.isNotEmpty) {
      return trimmedName;
    }
    final String local = email.split('@').first.trim();
    if (local.isNotEmpty) {
      return local;
    }
    return null;
  }
}

class _LlmChatUserAvatarContent extends StatelessWidget {
  const _LlmChatUserAvatarContent({
    required this.diameter,
    required this.userId,
    required this.avatarPath,
    required this.initials,
    required this.showShadow,
  });

  final double diameter;
  final String? userId;
  final String? avatarPath;
  final String? initials;
  final bool showShadow;

  @override
  Widget build(BuildContext context) {
    final String? path = avatarPath;
    if (path != null && path.isNotEmpty) {
      return _buildAvatar(image: NetworkImage(path));
    }

    final String? id = userId;
    if (id != null) {
      final String? cachedUrl = getCachedAvatarUrl(id);
      if (cachedUrl != null && cachedUrl.isNotEmpty) {
        return _buildAvatar(image: NetworkImage(cachedUrl));
      }

      return FutureBuilder<String>(
        future: resolveAvatarUrl(id),
        builder: (context, snapshot) {
          final String? url = snapshot.data;
          return _buildAvatar(
            image: (url != null && url.isNotEmpty) ? NetworkImage(url) : null,
          );
        },
      );
    }

    return _buildAvatar();
  }

  KasyAvatar _buildAvatar({ImageProvider? image}) {
    return KasyAvatar(
      diameter: diameter,
      image: image,
      initials: initials,
      icon: KasyIcons.person,
      fallbackSurface: KasyAvatarFallbackSurface.soft,
      tone: KasyAvatarTone.neutral,
      showShadow: showShadow,
    );
  }
}
