import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import '../../providers/prayer_provider.dart';
import '../../models/prayer_request.dart';
import '../../theme/app_theme.dart';

class PrayerRequestScreen extends ConsumerWidget {
  const PrayerRequestScreen({super.key});

  void _showAddDialog(BuildContext context, WidgetRef ref) {
    final controller = TextEditingController();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('New Prayer Request',
            style: GoogleFonts.outfit(fontWeight: FontWeight.bold)),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(
            hintText: 'What can we pray for?',
            border: OutlineInputBorder(),
          ),
          maxLines: 3,
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton(
            onPressed: () {
              if (controller.text.isNotEmpty) {
                ref
                    .read(prayerRequestsProvider.notifier)
                    .addRequest(controller.text.trim());
                Navigator.pop(context);
              }
            },
            child: const Text('Add'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final requests = ref.watch(prayerRequestsProvider);
    final theme = Theme.of(context);

    // Separate active and answered
    final active = requests.where((r) => !r.isAnswered).toList();
    final answered = requests.where((r) => r.isAnswered).toList();

    return Scaffold(
      appBar: AppBar(
        title: Text('Prayer Requests',
            style: GoogleFonts.outfit(fontWeight: FontWeight.bold)),
        centerTitle: true,
      ),
      body: requests.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.spa_outlined,
                      size: 64, color: theme.disabledColor),
                  const SizedBox(height: 16),
                  Text(
                    'No prayer requests yet.',
                    style: GoogleFonts.outfit(
                      fontSize: 16,
                      color: theme.textTheme.bodyMedium?.color,
                    ),
                  ),
                  const SizedBox(height: 8),
                  ElevatedButton.icon(
                    onPressed: () => _showAddDialog(context, ref),
                    icon: const Icon(Icons.add),
                    label: const Text('Add First Request'),
                  ),
                ],
              ),
            )
          : ListView(
              padding: const EdgeInsets.all(16),
              children: [
                if (active.isNotEmpty) ...[
                  Text('Active Requests',
                      style: GoogleFonts.outfit(
                          fontWeight: FontWeight.w600,
                          fontSize: 18,
                          color: AppColors.charcoal)),
                  const SizedBox(height: 8),
                  ...active.map((req) => _PrayerCard(request: req)),
                ],
                if (active.isNotEmpty && answered.isNotEmpty)
                  const Divider(height: 32),
                if (answered.isNotEmpty) ...[
                  Text('Answered Prayers',
                      style: GoogleFonts.outfit(
                          fontWeight: FontWeight.w600,
                          fontSize: 18,
                          color: AppColors.sageGreen)),
                  const SizedBox(height: 8),
                  ...answered.map((req) => _PrayerCard(request: req)),
                ],
              ],
            ),
      floatingActionButton: requests.isNotEmpty
          ? FloatingActionButton(
              onPressed: () => _showAddDialog(context, ref),
              child: const Icon(Icons.add),
            )
          : null,
    );
  }
}

class _PrayerCard extends ConsumerWidget {
  final PrayerRequest request;
  const _PrayerCard({required this.request});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final theme = Theme.of(context);
    final isAnswered = request.isAnswered;
    final dateStr = DateFormat('MMM d, yyyy').format(request.createdAt);

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: ListTile(
        contentPadding: const EdgeInsets.all(16),
        title: Text(
          request.request,
          style: GoogleFonts.outfit(
            fontSize: 16,
            fontWeight: FontWeight.w500,
            decoration:
                isAnswered ? TextDecoration.lineThrough : TextDecoration.none,
            color: isAnswered
                ? theme.disabledColor
                : theme.textTheme.bodyLarge?.color,
          ),
        ),
        subtitle: Padding(
          padding: const EdgeInsets.only(top: 8.0),
          child: Text(
            dateStr,
            style: GoogleFonts.outfit(fontSize: 12, color: theme.disabledColor),
          ),
        ),
        trailing: Checkbox(
          value: isAnswered,
          activeColor: AppColors.sageGreen,
          onChanged: (val) {
            ref.read(prayerRequestsProvider.notifier).toggleAnswered(request);
          },
        ),
        onLongPress: () async {
          final confirm = await showDialog<bool>(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('Delete Request?'),
              actions: [
                TextButton(
                    onPressed: () => Navigator.pop(context, false),
                    child: const Text('Cancel')),
                TextButton(
                    onPressed: () => Navigator.pop(context, true),
                    child: const Text('Delete',
                        style: TextStyle(color: Colors.red))),
              ],
            ),
          );
          if (confirm == true) {
            ref.read(prayerRequestsProvider.notifier).deleteRequest(request.id);
          }
        },
      ),
    );
  }
}
