import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dio/dio.dart';
import '../../core/api_client.dart';
import '../profile/profile_screen.dart';

class StoriesScreen extends ConsumerStatefulWidget {
  const StoriesScreen({super.key});

  @override
  ConsumerState<StoriesScreen> createState() => _StoriesScreenState();
}

class _StoriesScreenState extends ConsumerState<StoriesScreen> {
  List<dynamic> _stories = [];

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

  Future<void> _loadStories() async {
    try {
      final response =
          await ref.read(apiClientProvider).client.get('/stories/feed');
      setState(() {
        _stories = response.data;
      });
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Stories yüklenemedi: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(title: const Text('Stories')),
      body: _stories.isEmpty
          ? Center(
              child: Text(
                'Henüz story yok.',
                style: TextStyle(color: scheme.onSurfaceVariant),
              ),
            )
          : ListView.separated(
              padding: const EdgeInsets.fromLTRB(12, 12, 12, 20),
              itemCount: _stories.length,
              separatorBuilder: (_, __) => const SizedBox(height: 12),
              itemBuilder: (context, index) {
                final story = _stories[index];
                return Card(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      ListTile(
                        leading: CircleAvatar(
                            backgroundImage: story['avatar_url'] != null
                                ? NetworkImage(story['avatar_url'])
                                : null,
                            child: story['avatar_url'] == null
                                ? Text(story['username'][0].toUpperCase())
                                : null),
                        title: Text(story['display_name']),
                        subtitle: Text(
                          story['created_at'],
                          style: TextStyle(color: scheme.onSurfaceVariant),
                        ),
                        onTap: () {
                          Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (_) => ProfileScreen(
                                      userId: story['user_id'])));
                        },
                      ),
                      if (story['type'] == 'text')
                        Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Text(story['content'] ?? '',
                              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600, letterSpacing: -0.2)),
                        ),
                      if (story['type'] == 'image' &&
                          story['media_url'] != null)
                        ClipRRect(
                          borderRadius: const BorderRadius.vertical(bottom: Radius.circular(20)),
                          child: Image.network(story['media_url'], fit: BoxFit.cover),
                        ),
                    ],
                  ),
                );
              },
            ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _showAddStoryDialog();
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  void _showAddStoryDialog() {
    final textController = TextEditingController();

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => Padding(
        padding: EdgeInsets.only(
            bottom: MediaQuery.of(context).viewInsets.bottom,
            left: 16,
            right: 16,
            top: 16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('New Story',
                    style:
                        TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
                IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.close)),
              ],
            ),
            const SizedBox(height: 16),
            TextField(
              controller: textController,
              decoration: const InputDecoration(hintText: 'Bir şeyler yaz… (Max 155)'),
              maxLines: 4,
              maxLength: 155, // Client-side limit
              buildCounter: (context,
                  {required currentLength, required isFocused, maxLength}) {
                return Text('$currentLength/$maxLength');
              },
            ),
            const SizedBox(height: 16),
            FilledButton(
              onPressed: () async {
                final text = textController.text.trim();
                if (text.isNotEmpty) {
                  Navigator.pop(context); // Close first
                  await _postStory(text);
                }
              },
              child: const Text('Paylaş'),
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  Future<void> _postStory(String content) async {
    try {
      await ref.read(apiClientProvider).client.post('/stories', data: {
        'type': 'text',
        'content': content,
      });
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Story posted successfully!')));
      }
      _loadStories();
    } catch (e) {
      if (mounted) {
        String errorMessage = 'Failed to post story';
        if (e is DioException) {
          if (e.response?.statusCode == 429) {
            errorMessage = 'Daily story limit (3) reached!';
          } else if (e.response?.statusCode == 400) {
            errorMessage = 'Content too long or invalid.';
          } else if (e.response?.data != null &&
              e.response?.data['error'] != null) {
            errorMessage = e.response?.data['error'];
          }
        }

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(errorMessage), backgroundColor: Theme.of(context).colorScheme.error),
        );
      }
    }
  }
}
