import 'dart:io';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'profile_setup_screen.dart';

class ProfileScreen extends StatefulWidget {
  const ProfileScreen({super.key});

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  String _nickname = '伴享用户';
  List<String> _interests = [];
  String? _avatarPath;
  bool _loading = true;

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

  Future<void> _loadProfile() async {
    final prefs = await SharedPreferences.getInstance();
    if (!mounted) return;
    setState(() {
      _nickname = prefs.getString('user_nickname') ?? prefs.getString('nickname') ?? '伴享用户';
      _interests = prefs.getStringList('user_interests') ?? prefs.getStringList('interests') ?? [];
      _avatarPath = prefs.getString('user_avatar_path');
      _loading = false;
    });
  }

  bool get _hasAvatar {
    final path = _avatarPath;
    return path != null && path.isNotEmpty && File(path).existsSync();
  }

  Future<void> _openProfileSetup() async {
    await Navigator.push(
      context,
      MaterialPageRoute(builder: (_) => const ProfileSetupScreen()),
    );
    _loadProfile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFFFF8F0),
      appBar: AppBar(title: const Text('我的资料')),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : SingleChildScrollView(
                      padding: const EdgeInsets.fromLTRB(24, 28, 24, 12),
                      child: Column(
                        children: [
                          SizedBox(
                            width: 80,
                            height: 80,
                            child: ClipOval(
                              child: _hasAvatar
                                  ? Image.file(File(_avatarPath!), fit: BoxFit.cover)
                                  : Container(
                                      color: const Color(0xFFFFE7CF),
                                      child: const Icon(
                                        Icons.person,
                                        size: 42,
                                        color: Color(0xFFCC7A2F),
                                      ),
                                    ),
                            ),
                          ),
                          const SizedBox(height: 16),
                          Text(
                            _nickname.isEmpty ? '伴享用户' : _nickname,
                            textAlign: TextAlign.center,
                            style: const TextStyle(
                              fontSize: 28,
                              fontWeight: FontWeight.w700,
                              color: Color(0xFF333333),
                            ),
                          ),
                          const SizedBox(height: 28),
                          if (_interests.isNotEmpty)
                            Wrap(
                              alignment: WrapAlignment.center,
                              spacing: 8,
                              runSpacing: 8,
                              children: _interests
                                  .map(
                                    (interest) => Container(
                                      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                                      decoration: BoxDecoration(
                                        color: const Color(0xFFFFB84D),
                                        borderRadius: BorderRadius.circular(18),
                                      ),
                                      child: Text(
                                        interest,
                                        style: const TextStyle(
                                          color: Colors.white,
                                          fontSize: 13,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                            )
                          else
                            const Text(
                              '还没有设置兴趣标签',
                              style: TextStyle(
                                fontSize: 14,
                                color: Color(0xFF999999),
                              ),
                            ),
                        ],
                      ),
                    ),
            ),
            Padding(
              padding: const EdgeInsets.fromLTRB(24, 0, 24, 24),
              child: SizedBox(
                width: double.infinity,
                height: 52,
                child: ElevatedButton(
                  onPressed: _openProfileSetup,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color(0xFFFF8A3D),
                    foregroundColor: Colors.white,
                  ),
                  child: const Text(
                    '编辑资料',
                    style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
