import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/glass_card.dart';

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

  @override
  State<EditProfileScreen> createState() => _EditProfileScreenState();
}

class _EditProfileScreenState extends State<EditProfileScreen> {
  final _nameCtrl = TextEditingController();
  String? _selectedCountry;
  bool _saving = false;
  String? _message;
  bool _isError = false;

  @override
  void initState() {
    super.initState();
    final provider = context.read<AppProvider>();
    _nameCtrl.text = provider.profile?['display_name']?.toString() ??
        provider.profile?['name']?.toString() ?? '';
    // Get country code - backend returns code, ensure we use code for dropdown
    final rawCountry = provider.profile?['country']?.toString() ?? '';
    // Only set if it looks like a valid code
    _selectedCountry = rawCountry.isNotEmpty && rawCountry.length <= 5 ? rawCountry : null;
  }

  Future<void> _save() async {
    if (_nameCtrl.text.trim().isEmpty) return;
    setState(() { _saving = true; _message = null; });
    try {
      await context.read<AppProvider>().updateProfile({
        'display_name': _nameCtrl.text.trim(),
        if (_selectedCountry != null) 'country': _selectedCountry,
      });
      setState(() { _message = 'Profile updated'; _isError = false; });
    } on ApiException catch (e) {
      setState(() { _message = e.message; _isError = true; });
    } catch (_) {
      setState(() { _message = 'Failed to update'; _isError = true; });
    }
    setState(() => _saving = false);
  }

  @override
  void dispose() {
    _nameCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<AppProvider>();

    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Edit Profile', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 40),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Display Name', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
            const SizedBox(height: 8),
            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
              child: TextField(
                controller: _nameCtrl,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: InputDecoration(
                  hintText: 'Your name',
                  hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                  border: InputBorder.none,
                ),
              ),
            ),
            const SizedBox(height: 20),

            Text('Country', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
            const SizedBox(height: 8),
            GlassCard(
              padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
              child: DropdownButtonFormField<String>(
                value: _selectedCountry != null && provider.countries.any((c) => c['code']?.toString() == _selectedCountry)
                    ? _selectedCountry
                    : null,
                hint: Text('Select Country', style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                dropdownColor: AppColors.navy,
                style: AppTypography.bodyMd.copyWith(color: Colors.white),
                decoration: const InputDecoration(border: InputBorder.none),
                items: provider.countries.map<DropdownMenuItem<String>>((c) {
                  return DropdownMenuItem(
                    value: c['code']?.toString() ?? '',
                    child: Text(c['name']?.toString() ?? ''),
                  );
                }).toList(),
                onChanged: (v) => setState(() => _selectedCountry = v),
              ),
            ),
            const SizedBox(height: 24),

            if (_message != null)
              Padding(
                padding: const EdgeInsets.only(bottom: 16),
                child: Text(_message!,
                    style: AppTypography.bodyMd.copyWith(color: _isError ? AppColors.error : AppColors.success)),
              ),

            GestureDetector(
              onTap: _saving ? null : _save,
              child: Container(
                width: double.infinity,
                height: 52,
                decoration: BoxDecoration(
                  gradient: AppColors.blueGradient,
                  borderRadius: BorderRadius.circular(14),
                ),
                child: Center(
                  child: _saving
                      ? const SizedBox(width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                      : Text('Save Changes', style: AppTypography.button.copyWith(color: Colors.white)),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
