import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/emotion_provider.dart';
import 'package:intl/intl.dart';

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

  @override
  State<TrackerScreen> createState() => _TrackerScreenState();
}

class CompactMoodView extends StatelessWidget {
  const CompactMoodView({super.key});

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<EmotionProvider>(context);
    final lastEntry = provider.entries.isNotEmpty ? provider.entries.first : null;
    final emotions = [
      {'label': 'Très bien', 'emoji': '😊', 'color': const Color(0xFF4CAF50)},
      {'label': 'Bien', 'emoji': '🙂', 'color': const Color(0xFF8BC34A)},
      {'label': 'Neutre', 'emoji': '😐', 'color': const Color(0xFFFFC107)},
      {'label': 'Pas top', 'emoji': '🙁', 'color': const Color(0xFFFF9800)},
      {'label': 'Stressé', 'emoji': '😫', 'color': const Color(0xFFF44336)},
    ];

    return Container(
      padding: const EdgeInsets.all(16),
      color: const Color(0xFF000022),
      child: Column(
        children: [
          const Text(
            'CESIZen',
            style: TextStyle(
              color: Color(0xFF000080),
              fontWeight: FontWeight.bold,
              fontSize: 18,
            ),
          ),
          const SizedBox(height: 10),
          Expanded(
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Section Dernière Humeur
                Expanded(
                  flex: 1,
                  child: Column(
                    children: [
                      const Text(
                        'Dernière humeur',
                        style: TextStyle(color: Colors.white70, fontSize: 14),
                      ),
                      const SizedBox(height: 20),
                      if (lastEntry != null)
                        Container(
                          padding: const EdgeInsets.all(20),
                          decoration: BoxDecoration(
                            color: const Color(0xFF000080).withOpacity(0.3),
                            borderRadius: BorderRadius.circular(20),
                          ),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(
                                _getEmojiForEmotion(lastEntry.emotion, emotions),
                                style: const TextStyle(fontSize: 40),
                              ),
                              const SizedBox(height: 10),
                              Text(
                                lastEntry.emotion,
                                style: const TextStyle(
                                  color: Colors.white,
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const SizedBox(height: 5),
                              Text(
                                DateFormat('dd/MM HH:mm').format(lastEntry.createdAt),
                                style: const TextStyle(color: Colors.white54, fontSize: 12),
                              ),
                            ],
                          ),
                        )
                      else
                        const Center(
                          child: Text(
                            'Aucune donnée',
                            style: TextStyle(color: Colors.white38),
                          ),
                        ),
                    ],
                  ),
                ),
                const VerticalDivider(color: Colors.white24, width: 32),
                // Section Choix de l'humeur
                Expanded(
                  flex: 1,
                  child: Column(
                    children: [
                      const Text(
                        'Comment allez-vous ?',
                        style: TextStyle(color: Colors.white70, fontSize: 14),
                      ),
                      const SizedBox(height: 10),
                      Expanded(
                        child: GridView.builder(
                          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            childAspectRatio: 2.5,
                            crossAxisSpacing: 10,
                            mainAxisSpacing: 10,
                          ),
                          itemCount: emotions.length,
                          itemBuilder: (context, index) {
                            final mood = emotions[index];
                            return ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(horizontal: 8),
                                backgroundColor: (mood['color'] as Color).withOpacity(0.2),
                                foregroundColor: Colors.white,
                                elevation: 0,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                              ),
                              onPressed: () {
                                provider.addEmotion(mood['label'] as String, "");
                              },
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  Text(mood['emoji'] as String, style: const TextStyle(fontSize: 18)),
                                  const SizedBox(width: 8),
                                  Flexible(
                                    child: Text(
                                      mood['label'] as String,
                                      style: const TextStyle(fontSize: 12),
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _getEmojiForEmotion(String label, List<Map<String, dynamic>> emotions) {
    try {
      final match = emotions.firstWhere(
        (e) => e['label'] == label,
      );
      return match['emoji'] as String;
    } catch (_) {
      return '😐';
    }
  }
}

class _TrackerScreenState extends State<TrackerScreen> {
  @override
  void initState() {
    super.initState();
    Future.microtask(() =>
        Provider.of<EmotionProvider>(context, listen: false).loadEmotions());
  }

  void _showAddEmotionDialog() {
    String selectedEmotion = 'Bien';
    final noteController = TextEditingController();
    final emotions = ['Très bien', 'Bien', 'Neutre', 'Pas top', 'Stressé'];

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          title: const Text('Comment vous sentez-vous ?'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              DropdownButton<String>(
                value: selectedEmotion,
                isExpanded: true,
                items: emotions.map((String value) {
                  return DropdownMenuItem<String>(
                    value: value,
                    child: Text(value),
                  );
                }).toList(),
                onChanged: (newValue) {
                  setDialogState(() => selectedEmotion = newValue!);
                },
              ),
              const SizedBox(height: 20),
              TextField(
                controller: noteController,
                decoration: const InputDecoration(
                  labelText: 'Note (optionnel)',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('ANNULER'),
            ),
            ElevatedButton(
              onPressed: () async {
                final success = await Provider.of<EmotionProvider>(context, listen: false)
                    .addEmotion(selectedEmotion, noteController.text);
                if (mounted) {
                  Navigator.pop(context);
                  if (!success) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('Erreur lors de l\'ajout')),
                    );
                  }
                }
              },
              child: const Text('ENREGISTRER'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final provider = Provider.of<EmotionProvider>(context);

    return Scaffold(
      appBar: AppBar(title: const Text('Journal des Émotions')),
      body: provider.isLoading
          ? const Center(child: CircularProgressIndicator())
          : provider.entries.isEmpty
              ? const Center(child: Text('Aucune entrée pour le moment.'))
              : ListView.builder(
                  itemCount: provider.entries.length,
                  padding: const EdgeInsets.all(16),
                  itemBuilder: (context, index) {
                    final entry = provider.entries[index];
                    return Card(
                      margin: const EdgeInsets.only(bottom: 12),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
                      child: ListTile(
                        leading: _getEmotionIcon(entry.emotion),
                        title: Text(
                          entry.emotion,
                          style: const TextStyle(fontWeight: FontWeight.bold),
                        ),
                        subtitle: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            if (entry.note != null && entry.note!.isNotEmpty)
                              Text(entry.note!),
                            Text(
                              DateFormat('dd/MM/yyyy HH:mm').format(entry.createdAt),
                              style: const TextStyle(fontSize: 12, color: Colors.grey),
                            ),
                          ],
                        ),
                        trailing: IconButton(
                          icon: const Icon(Icons.delete_outline, color: Colors.red),
                          onPressed: () => provider.deleteEmotion(entry.id!),
                        ),
                      ),
                    );
                  },
                ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showAddEmotionDialog,
        backgroundColor: const Color(0xFF000080),
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  Widget _getEmotionIcon(String emotion) {
    IconData icon;
    Color color;
    switch (emotion) {
      case 'Très bien':
        icon = Icons.sentiment_very_satisfied;
        color = const Color(0xFF4CAF50);
        break;
      case 'Bien':
        icon = Icons.sentiment_satisfied;
        color = const Color(0xFF8BC34A);
        break;
      case 'Neutre':
        icon = Icons.sentiment_neutral;
        color = const Color(0xFFFFC107);
        break;
      case 'Pas top':
        icon = Icons.sentiment_dissatisfied;
        color = const Color(0xFFFF9800);
        break;
      case 'Stressé':
        icon = Icons.sentiment_very_dissatisfied;
        color = const Color(0xFFF44336);
        break;
      default:
        icon = Icons.sentiment_neutral;
        color = Colors.grey;
    }
    return CircleAvatar(
      backgroundColor: color.withOpacity(0.1),
      child: Icon(icon, color: color),
    );
  }
}
