import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import '../providers/dino_provider.dart';
import '../models/dinosaur.dart';
import 'detail_screen.dart';

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

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

    return Scaffold(
      appBar: AppBar(
        title: const Text(
            "DINO FIELD GUIDE",
            style: TextStyle(letterSpacing: 2, fontWeight: FontWeight.bold)
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.tune),
            onPressed: () => _showSettings(context, provider),
          )
        ],
        // --- INCREASED HEIGHT FOR TWO ROWS OF FILTERS ---
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(170),
          child: Column(
            children: [
              // 1. SEARCH BAR
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: TextField(
                  onChanged: (val) => provider.updateSearch(val),
                  decoration: InputDecoration(
                    hintText: "Search prehistoric records...",
                    prefixIcon: const Icon(Icons.search, color: Colors.green),
                    filled: true,
                    fillColor: Colors.grey.withValues(alpha: 0.1),
                    border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15),
                        borderSide: BorderSide.none
                    ),
                  ),
                ),
              ),

              // 2. DIET FILTER ROW (GREEN)
              _buildFilterRow(
                  context,
                  provider,
                  ["All", "Carnivore", "Herbivore", "Omnivore"],
                  true
              ),

              // 3. CLASSIFICATION FILTER ROW (BLUE)
              _buildFilterRow(
                  context,
                  provider,
                  provider.classifications,
                  false
              ),
            ],
          ),
        ),
      ),
      body: provider.dinos.isEmpty
          ? const Center(child: Text("No records match your filters."))
          : AnimationLimiter(
        child: ListView.builder(
          padding: const EdgeInsets.only(top: 10, bottom: 20),
          itemCount: provider.dinos.length,
          itemBuilder: (context, index) {
            final dino = provider.dinos[index];
            return AnimationConfiguration.staggeredList(
              position: index,
              duration: const Duration(milliseconds: 500),
              child: SlideAnimation(
                verticalOffset: 50.0,
                child: FadeInAnimation(
                  child: _buildDinoCard(context, dino),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  // --- REUSABLE FILTER ROW GENERATOR ---
  Widget _buildFilterRow(BuildContext context, DinoProvider p, List<String> options, bool isDietRow) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      child: Row(
        children: options.map((option) {
          // Determine if this specific chip is selected
          bool isSelected = isDietRow
              ? p.selectedDiet == option
              : p.selectedClassification == option;

          return Padding(
            padding: const EdgeInsets.only(right: 8),
            child: FilterChip(
              label: Text(
                  option,
                  style: TextStyle(
                      fontSize: 11,
                      fontWeight: isSelected ? FontWeight.bold : FontWeight.normal
                  )
              ),
              selected: isSelected,
              onSelected: (_) {
                if (isDietRow) {
                  p.updateDietFilter(option);
                } else {
                  p.updateClassificationFilter(option);
                }
              },
              // GREEN THEME for Diet, BLUE THEME for Classification
              selectedColor: isDietRow
                  ? Colors.green.withValues(alpha: 0.2)
                  : Colors.blue.withValues(alpha: 0.15),
              checkmarkColor: isDietRow ? Colors.green : Colors.blue,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
              side: BorderSide(
                color: isSelected
                    ? (isDietRow ? Colors.green : Colors.blue)
                    : Colors.grey.withValues(alpha: 0.2),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  // --- SETTINGS MODAL ---
  void _showSettings(BuildContext context, DinoProvider p) {
    showModalBottomSheet(
      context: context,
      builder: (context) => Padding(
        padding: const EdgeInsets.symmetric(vertical: 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text("TACTICAL SETTINGS", style: TextStyle(fontWeight: FontWeight.bold, letterSpacing: 1.5)),
            const Divider(),
            SwitchListTile(
              title: const Text("Night Vision Mode"),
              secondary: const Icon(Icons.dark_mode),
              value: p.isDarkMode,
              onChanged: (_) => p.toggleTheme(),
            ),
            SwitchListTile(
              title: const Text("Use Imperial Units (lbs/ft)"),
              secondary: const Icon(Icons.straighten),
              value: !p.isMetric,
              onChanged: (_) => p.toggleUnits(),
            ),
          ],
        ),
      ),
    );
  }

  // --- DINO LIST CARD ---
  Widget _buildDinoCard(BuildContext context, Dinosaur dino) {
    final provider = Provider.of<DinoProvider>(context, listen: false);
    final isFav = provider.isFavorite(dino.name);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 0,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15),
          side: BorderSide(color: Colors.grey.withValues(alpha: 0.1))
      ),
      child: ListTile(
        contentPadding: const EdgeInsets.all(12),
        leading: Hero(
          tag: dino.name,
          child: Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              color: Colors.grey.withValues(alpha: 0.05),
              borderRadius: BorderRadius.circular(12),
            ),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Image.asset(
                  dino.imagePath,
                  fit: BoxFit.contain,
                  errorBuilder: (_, __, ___) => const Icon(Icons.pets, color: Colors.grey)
              ),
            ),
          ),
        ),
        title: Text(dino.name, style: const TextStyle(fontWeight: FontWeight.bold)),
        subtitle: Text("${dino.classification} • ${dino.period}"),
        trailing: Icon(
            isFav ? Icons.favorite : Icons.arrow_forward_ios,
            color: isFav ? Colors.red : Colors.grey.withValues(alpha: 0.5),
            size: 16
        ),
        onTap: () => Navigator.push(
            context,
            MaterialPageRoute(builder: (_) => DetailScreen(dinosaur: dino))
        ),
      ),
    );
  }
}