import 'package:flutter/material.dart';
import 'package:chepuhagram/domain/services/api_service.dart';

class UserProfileScreen extends StatefulWidget {
  final int userId;
  final String username;
  final String name;

  const UserProfileScreen({
    super.key,
    required this.userId,
    required this.username,
    required this.name,
  });

  @override
  State<UserProfileScreen> createState() => _UserProfileScreenState();
}

class _UserProfileScreenState extends State<UserProfileScreen> {
  Map<String, dynamic>? _userData;
  bool _isLoading = true;
  String? _error;

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  Future<void> _loadUserData() async {
    try {
      final api = ApiService();
      final data = await api.getUserById(widget.userId);
      if (mounted) {
        setState(() {
          _userData = data;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _error = e.toString().replaceAll('Exception: ', '');
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Информация о пользователе'),
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : _error != null
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Icon(Icons.error_outline, size: 48, color: Colors.red),
                      const SizedBox(height: 16),
                      Text(_error!, textAlign: TextAlign.center),
                      const SizedBox(height: 16),
                      ElevatedButton(
                        onPressed: _loadUserData,
                        child: const Text('Повторить'),
                      ),
                    ],
                  ),
                )
              : _buildUserInfo(),
    );
  }

  Widget _buildUserInfo() {
    if (_userData == null) return const SizedBox.shrink();

    return ListView(
      padding: const EdgeInsets.all(16),
      children: [
        // Avatar placeholder
        Center(
          child: CircleAvatar(
            radius: 50,
            backgroundColor: Theme.of(context).primaryColor.withOpacity(0.1),
            child: Text(
              (_userData!['first_name'] != null && _userData!['first_name'].isNotEmpty && 
               _userData!['last_name'] != null && _userData!['last_name'].isNotEmpty)
                  ? '${_userData!['first_name'][0]}${_userData!['last_name'][0]}'.toUpperCase()
                  : (_userData!['first_name'] != null && _userData!['first_name'].isNotEmpty)
                      ? _userData!['first_name'][0].toUpperCase()
                      : (_userData!['username'] != null && _userData!['username'].isNotEmpty)
                          ? _userData!['username'][0].toUpperCase()
                          : '?',
              style: const TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
            ),
          ),
        ),
        const SizedBox(height: 24),

        // Name
        if ((_userData!['first_name'] != null && _userData!['first_name'].isNotEmpty) || 
            (_userData!['last_name'] != null && _userData!['last_name'].isNotEmpty))
          Text(
            '${_userData!['first_name'] ?? ''} ${_userData!['last_name'] ?? ''}'.trim(),
            style: Theme.of(context).textTheme.headlineSmall,
            textAlign: TextAlign.center,
          ),
        const SizedBox(height: 8),

        // Username
        if (_userData!['username'] != null && _userData!['username'].isNotEmpty)
          Text(
            '@${_userData!['username']}',
            style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                  color: Colors.grey[600],
                ),
            textAlign: TextAlign.center,
          ),
        const SizedBox(height: 32),

        // User ID
        _buildInfoTile('ID пользователя', _userData!['id'].toString()),

        // Public Key (if available)
        if (_userData!['public_key'] != null)
          _buildInfoTile('Публичный ключ', _userData!['public_key'], maxLines: 3),

        // About
        if (_userData!['about'] != null && _userData!['about'].isNotEmpty)
          _buildInfoTile('О себе', _userData!['about'], maxLines: 5),

        // Phone
        if (_userData!['phone'] != null && _userData!['phone'].isNotEmpty)
          _buildInfoTile('Телефон', _userData!['phone']),

        // Email
        if (_userData!['email'] != null && _userData!['email'].isNotEmpty)
          _buildInfoTile('Почта', _userData!['email']),

        const SizedBox(height: 16),
        if ((_userData!['username'] == null || _userData!['username'].isEmpty) && 
            (_userData!['first_name'] == null || _userData!['first_name'].isEmpty) && 
            (_userData!['last_name'] == null || _userData!['last_name'].isEmpty) && 
            (_userData!['about'] == null || _userData!['about'].isEmpty) && 
            (_userData!['phone'] == null || _userData!['phone'].isEmpty) && 
            (_userData!['email'] == null || _userData!['email'].isEmpty))
          const Text(
            'Пользователь скрыл дополнительную информацию',
            style: TextStyle(color: Colors.grey),
            textAlign: TextAlign.center,
          ),
      ],
    );
  }

  Widget _buildInfoTile(String label, String value, {int maxLines = 1}) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: 14,
              color: Colors.grey,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            value,
            style: const TextStyle(fontSize: 16),
            maxLines: maxLines,
            overflow: TextOverflow.ellipsis,
          ),
          const Divider(),
        ],
      ),
    );
  }
}