import 'package:flutter/material.dart';

import '../l10n/generated/app_localizations.dart';
import '../src/rust/api.dart' as rust;

/// Bottom sheet that presents richer TeamSpeak client profile data.
class ClientInfoSheet extends StatefulWidget {
  /// Construct a client info sheet.
  const ClientInfoSheet({
    super.key,
    required this.clientName,
    required this.loadProfile,
  });

  /// Display name used while the profile request is loading.
  final String clientName;

  /// Fetch richer profile data from the active protocol connection.
  final Future<rust.BridgeClientProfile> Function() loadProfile;

  @override
  State<ClientInfoSheet> createState() => _ClientInfoSheetState();
}

class _ClientInfoSheetState extends State<ClientInfoSheet> {
  late Future<rust.BridgeClientProfile> _profileFuture;

  @override
  void initState() {
    super.initState();
    _profileFuture = widget.loadProfile();
  }

  void _retry() {
    setState(() {
      _profileFuture = widget.loadProfile();
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return SafeArea(
      top: false,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(20, 10, 20, 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 40,
              height: 4,
              decoration: BoxDecoration(
                color: theme.colorScheme.onSurfaceVariant.withValues(
                  alpha: 0.34,
                ),
                borderRadius: BorderRadius.circular(999),
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: FutureBuilder<rust.BridgeClientProfile>(
                future: _profileFuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState != ConnectionState.done) {
                    return _ClientInfoLoading(name: widget.clientName);
                  }
                  if (snapshot.hasError || !snapshot.hasData) {
                    return _ClientInfoError(
                      name: widget.clientName,
                      onRetry: _retry,
                    );
                  }
                  return _ClientInfoContent(profile: snapshot.data!);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class _ClientInfoLoading extends StatelessWidget {
  const _ClientInfoLoading({required this.name});

  final String name;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final l10n = AppL10n.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _ClientInfoHeader(name: name, subtitle: l10n.clientInfoFetchingProfile),
        const SizedBox(height: 24),
        LinearProgressIndicator(
          minHeight: 3,
          borderRadius: BorderRadius.circular(999),
        ),
        const SizedBox(height: 16),
        Text(l10n.clientInfoLoadingProfile, style: theme.textTheme.bodyMedium),
      ],
    );
  }
}

class _ClientInfoError extends StatelessWidget {
  const _ClientInfoError({required this.name, required this.onRetry});

  final String name;
  final VoidCallback onRetry;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final l10n = AppL10n.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _ClientInfoHeader(
          name: name,
          subtitle: l10n.clientInfoProfileUnavailable,
        ),
        const SizedBox(height: 24),
        Icon(Icons.info_outline, color: theme.colorScheme.error, size: 32),
        const SizedBox(height: 12),
        Text(
          l10n.clientInfoProfileUnavailableBody,
          style: theme.textTheme.bodyMedium,
        ),
        const SizedBox(height: 16),
        FilledButton.icon(
          onPressed: onRetry,
          icon: const Icon(Icons.refresh),
          label: Text(l10n.retryAction),
        ),
      ],
    );
  }
}

class _ClientInfoContent extends StatelessWidget {
  const _ClientInfoContent({required this.profile});

  final rust.BridgeClientProfile profile;

  @override
  Widget build(BuildContext context) {
    final l10n = AppL10n.of(context);
    return ListView(
      children: [
        _ClientInfoHeader(
          name: profile.name,
          subtitle: _joinNonEmpty([
            profile.platform,
            profile.version,
            profile.countryCode,
          ]),
        ),
        const SizedBox(height: 20),
        _InfoSection(
          title: l10n.clientInfoIdentitySection,
          rows: [
            _InfoRowData(l10n.clientInfoClientId, profile.id.toString()),
            _InfoRowData(
              l10n.clientInfoDatabaseId,
              _formatBigInt(profile.databaseId, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoUniqueId,
              _emptyAsHidden(profile.uniqueId, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoDescription,
              _emptyAsHidden(profile.description, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoAvatar,
              _emptyAsNone(profile.avatarPath, l10n),
            ),
          ],
        ),
        _InfoSection(
          title: l10n.clientInfoMembershipSection,
          rows: [
            _InfoRowData(
              l10n.clientInfoServerGroups,
              profile.serverGroups.isEmpty
                  ? l10n.clientInfoUnknown
                  : profile.serverGroups.join(', '),
            ),
            _InfoRowData(
              l10n.clientInfoChannelGroup,
              _emptyAsHidden(profile.channelGroup, l10n),
            ),
            _InfoRowData(l10n.clientInfoChannelId, profile.channel.toString()),
          ],
        ),
        _InfoSection(
          title: l10n.clientInfoConnectionSection,
          rows: [
            _InfoRowData(
              l10n.clientInfoOnline,
              _formatSeconds(profile.onlineSeconds, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoIdle,
              _formatMilliseconds(profile.idleMilliseconds, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoPing,
              _formatMilliseconds(profile.pingMilliseconds, l10n),
            ),
            if (profile.pingDeviationMilliseconds != null)
              _InfoRowData(
                l10n.clientInfoPingDeviation,
                _formatMilliseconds(profile.pingDeviationMilliseconds, l10n),
              ),
            _InfoRowData(
              l10n.clientInfoAddress,
              _emptyAsHidden(profile.clientAddress, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoPacketLossClientToServer,
              _formatLoss(profile.packetLossClientToServerTotal),
            ),
            _InfoRowData(
              l10n.clientInfoPacketLossServerToClient,
              _formatLoss(profile.packetLossServerToClientTotal),
            ),
          ],
        ),
        _InfoSection(
          title: l10n.clientInfoHistorySection,
          rows: [
            _InfoRowData(
              l10n.clientInfoFirstConnected,
              _formatUnix(profile.createdUnixSeconds, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoLastConnected,
              _formatUnix(profile.lastConnectedUnixSeconds, l10n),
            ),
            _InfoRowData(
              l10n.clientInfoConnections,
              _formatBigInt(profile.connectionsTotal, l10n),
            ),
          ],
        ),
        _InfoSection(
          title: l10n.clientInfoTransferSection,
          rows: [
            _InfoRowData(
              l10n.clientInfoDownloadedMonth,
              _formatBytes(profile.bytesDownloadedMonth),
            ),
            _InfoRowData(
              l10n.clientInfoUploadedMonth,
              _formatBytes(profile.bytesUploadedMonth),
            ),
            _InfoRowData(
              l10n.clientInfoDownloadedTotal,
              _formatBytes(profile.bytesDownloadedTotal),
            ),
            _InfoRowData(
              l10n.clientInfoUploadedTotal,
              _formatBytes(profile.bytesUploadedTotal),
            ),
          ],
        ),
      ],
    );
  }
}

class _ClientInfoHeader extends StatelessWidget {
  const _ClientInfoHeader({required this.name, required this.subtitle});

  final String name;
  final String subtitle;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        CircleAvatar(
          radius: 28,
          backgroundColor: theme.colorScheme.primaryContainer,
          foregroundColor: theme.colorScheme.onPrimaryContainer,
          child: Text(
            _initials(name),
            style: theme.textTheme.titleMedium?.copyWith(
              fontWeight: FontWeight.w700,
            ),
          ),
        ),
        const SizedBox(width: 14),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                name,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: theme.textTheme.titleLarge?.copyWith(
                  fontWeight: FontWeight.w700,
                ),
              ),
              if (subtitle.isNotEmpty) ...[
                const SizedBox(height: 4),
                Text(
                  subtitle,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: theme.textTheme.bodyMedium?.copyWith(
                    color: theme.colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ],
          ),
        ),
      ],
    );
  }
}

class _InfoSection extends StatelessWidget {
  const _InfoSection({required this.title, required this.rows});

  final String title;
  final List<_InfoRowData> rows;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Padding(
      padding: const EdgeInsets.only(bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: theme.textTheme.labelLarge?.copyWith(
              color: theme.colorScheme.primary,
              fontWeight: FontWeight.w700,
            ),
          ),
          const SizedBox(height: 8),
          DecoratedBox(
            decoration: BoxDecoration(
              border: Border(
                top: BorderSide(color: theme.dividerColor),
                bottom: BorderSide(color: theme.dividerColor),
              ),
            ),
            child: Column(
              children: [
                for (var i = 0; i < rows.length; i++) ...[
                  _InfoRow(row: rows[i]),
                  if (i != rows.length - 1) const Divider(height: 1),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _InfoRow extends StatelessWidget {
  const _InfoRow({required this.row});

  final _InfoRowData row;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 11),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 132,
            child: Text(
              row.label,
              style: theme.textTheme.bodyMedium?.copyWith(
                color: theme.colorScheme.onSurfaceVariant,
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: SelectableText(
              row.value,
              style: theme.textTheme.bodyMedium?.copyWith(
                fontFeatures: const [FontFeature.tabularFigures()],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _InfoRowData {
  const _InfoRowData(this.label, this.value);

  final String label;
  final String value;
}

String _initials(String value) {
  final trimmed = value.trim();
  if (trimmed.isEmpty) return '?';
  final parts = trimmed.split(RegExp(r'\s+')).where((p) => p.isNotEmpty);
  final chars = parts.take(2).map((p) => p.characters.first.toUpperCase());
  return chars.join();
}

String _joinNonEmpty(Iterable<String> values) {
  return values.where((value) => value.trim().isNotEmpty).join(' / ');
}

String _emptyAsHidden(String value, AppL10n l10n) =>
    value.trim().isEmpty ? l10n.clientInfoHidden : value;

String _emptyAsNone(String value, AppL10n l10n) =>
    value.trim().isEmpty ? l10n.clientInfoNone : value;

String _formatBigInt(BigInt? value, AppL10n l10n) =>
    value?.toString() ?? l10n.clientInfoUnknown;

String _formatUnix(Object? seconds, AppL10n l10n) {
  final raw = _intFromPlatform(seconds);
  if (raw == null || raw <= 0) return l10n.clientInfoUnknown;
  final date = DateTime.fromMillisecondsSinceEpoch(
    raw * 1000,
    isUtc: true,
  ).toLocal();
  return date.toString().split('.').first;
}

String _formatSeconds(Object? seconds, AppL10n l10n) {
  final raw = _intFromPlatform(seconds);
  if (raw == null) return l10n.clientInfoUnknown;
  if (raw < 60) return '$raw s';
  final minutes = raw ~/ 60;
  final hours = minutes ~/ 60;
  if (hours > 0) {
    return '${hours}h ${minutes % 60}m ${raw % 60}s';
  }
  return '${minutes}m ${raw % 60}s';
}

String _formatMilliseconds(Object? milliseconds, AppL10n l10n) {
  final raw = _intFromPlatform(milliseconds);
  if (raw == null) return l10n.clientInfoUnknown;
  if (raw < 1000) return '$raw ms';
  return '${(raw / 1000).toStringAsFixed(2)} s';
}

String _formatBytes(BigInt? value) {
  if (value == null) return 'Unknown';
  final bytes = value.toDouble();
  const units = ['B', 'KB', 'MB', 'GB', 'TB'];
  var amount = bytes;
  var unitIndex = 0;
  while (amount >= 1024 && unitIndex < units.length - 1) {
    amount /= 1024;
    unitIndex++;
  }
  final digits = unitIndex == 0 ? 0 : 1;
  return '${amount.toStringAsFixed(digits)} ${units[unitIndex]}';
}

String _formatLoss(double? value) {
  if (value == null) return 'Unknown';
  return '${(value * 100).toStringAsFixed(2)}%';
}

int? _intFromPlatform(Object? value) {
  if (value == null) return null;
  if (value is int) return value;
  if (value is BigInt) return value.toInt();
  return int.tryParse(value.toString());
}
