import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../cart/cart_state.dart';

final cafeDetailProvider =
    FutureProvider.autoDispose.family<Map<String, dynamic>?, String>((ref, slug) {
  return ref.watch(publicApiProvider).getCafe(slug);
});

final cafeReviewsProvider =
    FutureProvider.autoDispose.family<List<Map<String, dynamic>>, String>((ref, slug) {
  return ref.watch(publicApiProvider).getReviews(slug);
});

class CafeDetailScreen extends ConsumerStatefulWidget {
  const CafeDetailScreen({super.key, required this.slug});

  final String slug;

  @override
  ConsumerState<CafeDetailScreen> createState() => _CafeDetailScreenState();
}

class _CafeDetailScreenState extends ConsumerState<CafeDetailScreen> {
  final _nameController = TextEditingController();
  final _commentController = TextEditingController();
  int _rating = 5;
  bool _submitting = false;

  @override
  void dispose() {
    _nameController.dispose();
    _commentController.dispose();
    super.dispose();
  }

  Future<void> _submitReview() async {
    final name = _nameController.text.trim();
    if (name.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('نام خود را وارد کنید')),
      );
      return;
    }
    setState(() => _submitting = true);
    try {
      await ref.read(publicApiProvider).createReview(
            widget.slug,
            authorName: name,
            rating: _rating,
            comment: _commentController.text.trim(),
          );
      _commentController.clear();
      ref.invalidate(cafeReviewsProvider(widget.slug));
      ref.invalidate(cafeDetailProvider(widget.slug));
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('نظر شما ثبت شد')),
        );
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('خطا: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _submitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final cafeAsync = ref.watch(cafeDetailProvider(widget.slug));
    final reviewsAsync = ref.watch(cafeReviewsProvider(widget.slug));

    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        appBar: AppBar(title: const Text('جزئیات کافه')),
        body: cafeAsync.when(
          loading: () => const Center(child: CircularProgressIndicator()),
          error: (e, _) => Center(child: Text('خطا: $e')),
          data: (cafe) {
            if (cafe == null) {
              return const Center(child: Text('کافه یافت نشد'));
            }
            final name = cafe['name'] as String? ?? widget.slug;
            final avg = (cafe['averageRating'] as num?)?.toDouble() ?? 0;
            final count = cafe['reviewCount'] as int? ?? 0;
            final description = cafe['description'] as String?;
            final address = cafe['address'] as String?;
            final city = cafe['city'] as String?;

            return ListView(
              padding: const EdgeInsets.all(16),
              children: [
                Text(name, style: Theme.of(context).textTheme.headlineSmall),
                const SizedBox(height: 8),
                Row(
                  children: [
                    const Icon(Icons.star, color: Colors.amber, size: 20),
                    const SizedBox(width: 4),
                    Text('${avg.toStringAsFixed(1)} ($count نظر)'),
                  ],
                ),
                if (city != null || address != null) ...[
                  const SizedBox(height: 8),
                  Text(
                    [city, address].where((e) => e != null && e.isNotEmpty).join(' — '),
                    style: Theme.of(context).textTheme.bodyMedium,
                  ),
                ],
                if (description != null && description.isNotEmpty) ...[
                  const SizedBox(height: 12),
                  Text(description),
                ],
                const SizedBox(height: 16),
                Row(
                  children: [
                    Expanded(
                      child: FilledButton.icon(
                        onPressed: () => context.push('/cafe/${widget.slug}/menu'),
                        icon: const Icon(Icons.restaurant_menu),
                        label: const Text('منو'),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Expanded(
                      child: OutlinedButton.icon(
                        onPressed: () => context.push('/cafe/${widget.slug}/reserve'),
                        icon: const Icon(Icons.event_seat_outlined),
                        label: const Text('رزرو'),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 24),
                Text('نظرات', style: Theme.of(context).textTheme.titleMedium),
                const SizedBox(height: 8),
                reviewsAsync.when(
                  loading: () => const Padding(
                    padding: EdgeInsets.all(16),
                    child: Center(child: CircularProgressIndicator()),
                  ),
                  error: (e, _) => Text('خطا در بارگذاری نظرات: $e'),
                  data: (reviews) {
                    if (reviews.isEmpty) {
                      return const Text('هنوز نظری ثبت نشده است.');
                    }
                    return Column(
                      children: reviews.map((r) {
                        final author = r['authorName'] as String? ?? '';
                        final rating = r['rating'] as int? ?? 0;
                        final comment = r['comment'] as String?;
                        final reply = r['ownerReply'] as String?;
                        return Card(
                          margin: const EdgeInsets.only(bottom: 8),
                          child: ListTile(
                            title: Text(author),
                            subtitle: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text('★' * rating + '☆' * (5 - rating)),
                                if (comment != null && comment.isNotEmpty) Text(comment),
                                if (reply != null && reply.isNotEmpty)
                                  Padding(
                                    padding: const EdgeInsets.only(top: 8),
                                    child: Text(
                                      'پاسخ کافه: $reply',
                                      style: const TextStyle(color: Colors.teal),
                                    ),
                                  ),
                              ],
                            ),
                          ),
                        );
                      }).toList(),
                    );
                  },
                ),
                const SizedBox(height: 24),
                Text('ثبت نظر', style: Theme.of(context).textTheme.titleMedium),
                const SizedBox(height: 8),
                TextField(
                  controller: _nameController,
                  decoration: const InputDecoration(
                    labelText: 'نام',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: List.generate(5, (i) {
                    final star = i + 1;
                    return IconButton(
                      onPressed: () => setState(() => _rating = star),
                      icon: Icon(
                        star <= _rating ? Icons.star : Icons.star_border,
                        color: Colors.amber,
                      ),
                    );
                  }),
                ),
                TextField(
                  controller: _commentController,
                  maxLines: 3,
                  decoration: const InputDecoration(
                    labelText: 'نظر (اختیاری)',
                    border: OutlineInputBorder(),
                  ),
                ),
                const SizedBox(height: 12),
                FilledButton(
                  onPressed: _submitting ? null : _submitReview,
                  child: _submitting
                      ? const SizedBox(
                          height: 20,
                          width: 20,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : const Text('ارسال نظر'),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
