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

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

  @override
  State<RemindersScreen> createState() => _RemindersScreenState();
}

class _RemindersScreenState extends State<RemindersScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<AppProvider>().loadReminders();
    });
  }

  void _showAddDialog() {
    final titleCtrl = TextEditingController();
    final descCtrl = TextEditingController();
    DateTime selectedDate = DateTime.now().add(const Duration(days: 1));
    String reminderType = 'deadline';

    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (ctx, setDialogState) => AlertDialog(
          backgroundColor: AppColors.navy,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
          title: Text('New Reminder', style: AppTypography.headingMd.copyWith(color: Colors.white)),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: titleCtrl,
                  style: AppTypography.bodyMd.copyWith(color: Colors.white),
                  decoration: InputDecoration(
                    hintText: 'Title',
                    hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: AppColors.glassBorder),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: AppColors.royalBlue),
                    ),
                  ),
                ),
                const SizedBox(height: 12),
                TextField(
                  controller: descCtrl,
                  maxLines: 3,
                  style: AppTypography.bodyMd.copyWith(color: Colors.white),
                  decoration: InputDecoration(
                    hintText: 'Description (optional)',
                    hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: AppColors.glassBorder),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: AppColors.royalBlue),
                    ),
                  ),
                ),
                const SizedBox(height: 12),
                DropdownButtonFormField<String>(
                  value: reminderType,
                  dropdownColor: AppColors.navy,
                  style: AppTypography.bodyMd.copyWith(color: Colors.white),
                  decoration: InputDecoration(
                    labelText: 'Type',
                    labelStyle: AppTypography.bodySm.copyWith(color: AppColors.textMuted),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: BorderSide(color: AppColors.glassBorder),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                      borderSide: const BorderSide(color: AppColors.royalBlue),
                    ),
                  ),
                  items: const [
                    DropdownMenuItem(value: 'deadline', child: Text('Deadline')),
                    DropdownMenuItem(value: 'hearing', child: Text('Hearing')),
                    DropdownMenuItem(value: 'meeting', child: Text('Meeting')),
                    DropdownMenuItem(value: 'follow_up', child: Text('Follow Up')),
                    DropdownMenuItem(value: 'custom', child: Text('Custom')),
                  ],
                  onChanged: (v) => setDialogState(() => reminderType = v ?? 'deadline'),
                ),
                const SizedBox(height: 12),
                GestureDetector(
                  onTap: () async {
                    final picked = await showDatePicker(
                      context: ctx,
                      initialDate: selectedDate,
                      firstDate: DateTime.now(),
                      lastDate: DateTime.now().add(const Duration(days: 365 * 2)),
                      builder: (c, child) => Theme(
                        data: ThemeData.dark().copyWith(
                          colorScheme: const ColorScheme.dark(primary: AppColors.royalBlue, surface: AppColors.navy),
                        ),
                        child: child!,
                      ),
                    );
                    if (picked != null) {
                      final time = await showTimePicker(
                        context: ctx,
                        initialTime: TimeOfDay.now(),
                        builder: (c, child) => Theme(
                          data: ThemeData.dark().copyWith(
                            colorScheme: const ColorScheme.dark(primary: AppColors.royalBlue, surface: AppColors.navy),
                          ),
                          child: child!,
                        ),
                      );
                      setDialogState(() {
                        selectedDate = DateTime(
                          picked.year, picked.month, picked.day,
                          time?.hour ?? 9, time?.minute ?? 0,
                        );
                      });
                    }
                  },
                  child: Container(
                    width: double.infinity,
                    padding: const EdgeInsets.all(14),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10),
                      border: Border.all(color: AppColors.glassBorder),
                    ),
                    child: Row(
                      children: [
                        const Icon(Icons.calendar_today_rounded, color: AppColors.royalBlue, size: 18),
                        const SizedBox(width: 10),
                        Text(
                          '${selectedDate.day}/${selectedDate.month}/${selectedDate.year} at ${selectedDate.hour.toString().padLeft(2, '0')}:${selectedDate.minute.toString().padLeft(2, '0')}',
                          style: AppTypography.bodyMd.copyWith(color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(ctx),
              child: Text('Cancel', style: TextStyle(color: AppColors.textMuted)),
            ),
            TextButton(
              onPressed: () async {
                if (titleCtrl.text.trim().isEmpty) return;
                final title = titleCtrl.text.trim();
                try {
                  await context.read<AppProvider>().addReminder({
                    'title': title,
                    'description': descCtrl.text.trim(),
                    'remind_at': selectedDate.toUtc().toIso8601String(),
                    'reminder_type': reminderType,
                  });
                  if (ctx.mounted) Navigator.pop(ctx);
                  if (context.mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('Reminder "$title" created'),
                        backgroundColor: AppColors.success,
                        behavior: SnackBarBehavior.floating,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                      ),
                    );
                  }
                } catch (e) {
                  if (ctx.mounted) Navigator.pop(ctx);
                  if (context.mounted) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: const Text('Failed to create reminder'),
                        backgroundColor: AppColors.error,
                        behavior: SnackBarBehavior.floating,
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                      ),
                    );
                  }
                }
              },
              child: const Text('Create', style: TextStyle(color: AppColors.royalBlue)),
            ),
          ],
        ),
      ),
    );
  }

  static const _typeIcons = <String, IconData>{
    'deadline': Icons.timer_rounded,
    'hearing': Icons.gavel_rounded,
    'meeting': Icons.people_rounded,
    'follow_up': Icons.replay_rounded,
    'custom': Icons.event_rounded,
  };

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

    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Reminders', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
        actions: [
          IconButton(
            icon: const Icon(Icons.add_rounded, color: AppColors.royalBlue),
            onPressed: _showAddDialog,
          ),
        ],
      ),
      body: provider.reminders.isEmpty
          ? Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.notifications_none_rounded, size: 56, color: AppColors.textMuted),
                  const SizedBox(height: 16),
                  Text('No reminders', style: AppTypography.bodyLg.copyWith(color: AppColors.textMuted)),
                  const SizedBox(height: 8),
                  Text('Never miss a legal deadline again',
                      style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                  const SizedBox(height: 20),
                  GestureDetector(
                    onTap: _showAddDialog,
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(colors: [AppColors.royalBlue, AppColors.royalBlue.withValues(alpha: 0.8)]),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text('Add Reminder', style: AppTypography.button.copyWith(color: Colors.white)),
                    ),
                  ),
                ],
              ),
            )
          : RefreshIndicator(
              color: AppColors.royalBlue,
              backgroundColor: AppColors.navy,
              onRefresh: () => provider.loadReminders(),
              child: ListView.builder(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 100),
              itemCount: provider.reminders.length,
              itemBuilder: (context, i) {
                final r = provider.reminders[i];
                final type = r['reminder_type']?.toString() ?? 'custom';
                return Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: Dismissible(
                    key: Key(r['id']?.toString() ?? '$i'),
                    direction: DismissDirection.endToStart,
                    background: Container(
                      alignment: Alignment.centerRight,
                      padding: const EdgeInsets.only(right: 20),
                      decoration: BoxDecoration(
                        color: AppColors.error.withValues(alpha: 0.2),
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: const Icon(Icons.delete_rounded, color: AppColors.error),
                    ),
                    onDismissed: (_) {
                      final id = r['id']?.toString();
                      if (id != null) {
                        provider.removeReminder(id);
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: const Text('Reminder deleted'),
                            backgroundColor: AppColors.glassSurface,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      }
                    },
                    child: GlassCard(
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        children: [
                          Container(
                            width: 44,
                            height: 44,
                            decoration: BoxDecoration(
                              color: AppColors.royalBlue.withValues(alpha: 0.15),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Icon(_typeIcons[type] ?? Icons.event_rounded,
                                color: AppColors.royalBlue, size: 22),
                          ),
                          const SizedBox(width: 14),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(r['title']?.toString() ?? 'Reminder',
                                    style: AppTypography.bodyLg.copyWith(color: Colors.white)),
                                if (r['description']?.toString().isNotEmpty == true)
                                  Text(r['description'].toString(),
                                      style: AppTypography.bodySm.copyWith(color: AppColors.textSecondary),
                                      maxLines: 1, overflow: TextOverflow.ellipsis),
                                const SizedBox(height: 4),
                                Row(
                                  children: [
                                    Icon(Icons.access_time_rounded, size: 13, color: AppColors.gold),
                                    const SizedBox(width: 4),
                                    Text(timeAgo(r['remind_at']?.toString()),
                                        style: AppTypography.bodySm.copyWith(color: AppColors.gold)),
                                  ],
                                ),
                              ],
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                            decoration: BoxDecoration(
                              color: AppColors.glassSurface,
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: Text(type.replaceAll('_', ' '),
                                style: AppTypography.label.copyWith(color: AppColors.textSecondary)),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
              ),
            ),
    );
  }
}
