import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import '../../core/api_client.dart';
import '../../core/auth_storage.dart';
import '../../data/user_model.dart';
import '../../data/message_model.dart';
import '../auth/auth_screen.dart';
import '../chat/chat_repository.dart';
import '../chat/chat_screen.dart';
import '../../core/hive_service.dart';
import '../settings/settings_screen.dart';

class ProfileScreen extends ConsumerStatefulWidget {
  final int? userId;
  const ProfileScreen({super.key, this.userId});

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

class _ProfileScreenState extends ConsumerState<ProfileScreen> {
  User? _user;
  bool _loading = true;
  bool _isMe = false;

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

  Future<void> _loadProfile() async {
    try {
      if (widget.userId != null) {
        // Try cache first for other users? Not for now, keep it fresh or cache later
        final response = await ref
            .read(apiClientProvider)
            .client
            .get('/users/${widget.userId}');
        _user = User.fromJson(response.data);
        final myId = await ref.read(authStorageProvider).getUserId();
        _isMe = myId == _user!.id.toString();
      } else {
        // ME: Try cache first
        final cachedMe = HiveService.cacheBox.get('me_profile');
        if (cachedMe != null) {
          // We could decode here, but let's assume network first or use cache as placeholder
          // For optimization, we can show cache then update
        }

        final response = await ref.read(apiClientProvider).client.get('/me');
        _user = User.fromJson(response.data);
        _isMe = true;

        // Cache me
        HiveService.cacheBox.put('me_profile', response.data); // Store Map/JSON
      }
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    } catch (e) {
      if (mounted) setState(() => _loading = false);
    }
  }

  Future<void> _logout() async {
    await ref.read(authStorageProvider).deleteToken();
    if (mounted) {
      Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const AuthScreen()),
          (route) => false);
    }
  }

  void _showEditBioDialog() {
    final bioController = TextEditingController(text: _user!.bio);
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Edit Bio'),
        content: TextField(
          controller: bioController,
          decoration:
              const InputDecoration(hintText: 'Enter your bio (max 155 chars)'),
          maxLines: 3,
          maxLength: 155,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              await _updateBio(bioController.text);
            },
            child: const Text('Save'),
          ),
        ],
      ),
    );
  }

  Future<void> _updateBio(String bio) async {
    try {
      await ref.read(apiClientProvider).client.put('/me', data: {
        'bio': bio,
      });
      _loadProfile();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Error: $e')));
      }
    }
  }

  Future<void> _startChat() async {
    if (_user == null) return;
    try {
      String visitorHash;
      final userId = await ref.read(authStorageProvider).getUserId();

      if (userId != null) {
        visitorHash = 'user_stable_$userId';
      } else {
        visitorHash = await ref.read(authStorageProvider).getVisitorHash();
      }

      final result = await ref
          .read(chatRepositoryProvider)
          .startAnonChat(_user!.linkSlug, visitorHash);
      final conversationId = result['conversation_id'];
      final anonToken = result['token'];
      final visitorUserId = result['visitor_id'];

      final conversation = Conversation(
          id: conversationId != null
              ? int.parse(conversationId.toString())
              : -1,
          otherUser: {
            'id': _user!.id,
            'username': _user!.username,
            'display_name': _user!.displayName,
            'avatar_url': _user!.avatarUrl
          });

      if (mounted) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) => ChatScreen(
                    conversation: conversation,
                    anonToken: anonToken,
                    visitorUserId: visitorUserId?.toString())));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Error: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    if (_loading) return const Center(child: CircularProgressIndicator());
    if (_user == null)
      return const Center(child: Text('Failed to load profile'));

    return Scaffold(
      appBar: AppBar(title: const Text('Profile'), actions: [
        IconButton(
          icon: Icon(Theme.of(context).brightness == Brightness.dark
              ? Icons.light_mode
              : Icons.dark_mode),
          onPressed: () {
            ref.read(themeProvider.notifier).toggleTheme();
          },
        ),
        if (_isMe)
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(builder: (_) => const SettingsScreen()),
              );
            },
          ),
        if (_isMe)
          IconButton(onPressed: _logout, icon: const Icon(Icons.logout))
      ]),
      body: SizedBox(
        width: double.infinity,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  onTap: _isMe ? _pickAndUploadImage : null,
                  child: CircleAvatar(
                    radius: 50,
                    backgroundImage: _user!.avatarUrl != null
                        ? NetworkImage(_user!.avatarUrl!)
                        : null,
                    child: _user!.avatarUrl == null
                        ? Text(_user!.username[0].toUpperCase(),
                            style: const TextStyle(fontSize: 40))
                        : null,
                  ),
                ),
                if (_isMe)
                  Padding(
                    padding: EdgeInsets.only(top: 8.0),
                    child: Text(
                      'Fotoğrafı değiştirmek için dokun',
                      style: TextStyle(fontSize: 12, color: scheme.onSurfaceVariant, fontWeight: FontWeight.w600),
                    ),
                  ),
                const SizedBox(height: 16),
                Text(_user!.displayName ?? _user!.username,
                    style: Theme.of(context).textTheme.headlineMedium),
                const SizedBox(height: 8),
                Text(
                  '@${_user!.username}',
                  style: TextStyle(color: scheme.onSurfaceVariant, fontWeight: FontWeight.w600),
                ),
                if (_user!.bio != null && _user!.bio!.isNotEmpty) ...[
                  const SizedBox(height: 8),
                  Text(_user!.bio!,
                      textAlign: TextAlign.center,
                      style: TextStyle(fontStyle: FontStyle.italic, color: scheme.onSurface)),
                ],
                const SizedBox(height: 24),
                if (_isMe) ...[
                  FilledButton.icon(
                    onPressed: _showEditBioDialog,
                    icon: const Icon(Icons.edit_rounded),
                    label: const Text('Biyografiyi Düzenle'),
                  ),
                  const SizedBox(height: 16),
                  Card(
                    child: ListTile(
                      title: const Text('My Anon Link'),
                      subtitle: Text('anonchat.com/u/${_user!.linkSlug}'),
                      trailing: const Icon(Icons.copy),
                      onTap: () {
                        ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(content: Text('Link copied!')));
                      },
                    ),
                  ),
                  const SizedBox(height: 16),
                  FilledButton.icon(
                      onPressed: () {
                        // Subscribe logic
                      },
                      icon: const Icon(Icons.workspace_premium_rounded),
                      label: const Text('Premium Al'))
                ],
                if (!_isMe) ...[
                  FilledButton.icon(
                    onPressed: _startChat,
                    icon: const Icon(Icons.chat_bubble_rounded),
                    label: const Text('Mesaj Gönder'),
                  )
                ]
              ],
            ),
          ),
        ),
      ),
    );
  }

  Future<void> _pickAndUploadImage() async {
    final picker = ImagePicker();
    final pickedFile = await picker.pickImage(source: ImageSource.gallery);
    if (pickedFile != null) {
      setState(() => _loading = true);
      try {
        String fileName = pickedFile.path.split('/').last;
        FormData formData = FormData.fromMap({
          "avatar":
              await MultipartFile.fromFile(pickedFile.path, filename: fileName),
        });

        final response = await ref
            .read(apiClientProvider)
            .client
            .post('/upload/avatar', data: formData);

        // Update user avatar
        await ref
            .read(apiClientProvider)
            .client
            .put('/me', data: {'avatar_url': response.data['url']});

        await _loadProfile();
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context)
              .showSnackBar(SnackBar(content: Text('Upload failed: $e')));
          setState(() => _loading = false);
        }
      }
    }
  }
}
