import "package:flutter/material.dart";
import "package:google_fonts/google_fonts.dart";
import "../demo_identity.dart";
import "../theme/ensup_colors.dart";
import "../models/materiel_item.dart";
import "../services/materiel_service.dart";
import "../widgets/ensup_top_bar.dart";
import "../widgets/brand_corners.dart";
import "../widgets/materiel_card.dart";
import "detail_screen.dart";

/// Catalogue matériel : recherche, filtres par catégorie et liste chargée
/// depuis l'API.
class CatalogueScreen extends StatefulWidget {
  const CatalogueScreen({super.key});

  @override
  State<CatalogueScreen> createState() => _CatalogueScreenState();
}

class _CatalogueScreenState extends State<CatalogueScreen> {
  late Future<List<MaterielItem>> _future;
  String _recherche = "";
  String _categorie = "Tous";
  int? _selectionEnCoursId;

  @override
  void initState() {
    super.initState();
    _future = MaterielService.getCatalogue();
  }

  void _recharger() {
    setState(() => _future = MaterielService.getCatalogue());
  }

  List<String> _categories(List<MaterielItem> materiels) {
    final distinctes = materiels.map((m) => m.categorie).toSet().toList()..sort();
    return ["Tous", ...distinctes];
  }

  List<MaterielItem> _filtrer(List<MaterielItem> materiels) {
    final terme = _recherche.trim().toLowerCase();
    return materiels.where((materiel) {
      final matchTexte = terme.isEmpty || materiel.nom.toLowerCase().contains(terme);
      final matchCategorie = _categorie == "Tous" || materiel.categorie == _categorie;
      return matchTexte && matchCategorie;
    }).toList();
  }

  Future<void> _selectionner(MaterielItem item) async {
    setState(() => _selectionEnCoursId = item.id);
    try {
      final detail = await MaterielService.getDetail(item.id);
      if (!mounted) {
        return;
      }
      Navigator.of(context).push(
        MaterialPageRoute(builder: (_) => DetailScreen(item: detail)),
      );
    } catch (error) {
      if (!mounted) {
        return;
      }
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(error.toString())),
      );
    } finally {
      if (mounted) {
        setState(() => _selectionEnCoursId = null);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: EnsupColors.soft,
      body: Stack(
        children: [
          Center(
            child: ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 1280, maxHeight: 820),
              child: Container(
                margin: const EdgeInsets.all(24),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: EnsupColors.text.withValues(alpha: 0.14),
                      blurRadius: 60,
                      offset: const Offset(0, 18),
                    ),
                  ],
                ),
                clipBehavior: Clip.antiAlias,
                child: Column(
                  children: [
                    EnsupTopBar(
                      brandText: "Catalogue matériel",
                      campusTag: DemoIdentity.campusTag,
                      userName: DemoIdentity.userName,
                      userInitials: DemoIdentity.userInitials,
                      onBack: () => Navigator.of(context).pop(),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.fromLTRB(32, 24, 32, 8),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            _SearchField(
                              onChanged: (value) => setState(() => _recherche = value),
                            ),
                            const SizedBox(height: 14),
                            Expanded(
                              child: FutureBuilder<List<MaterielItem>>(
                                future: _future,
                                builder: (context, snapshot) {
                                  if (snapshot.connectionState == ConnectionState.waiting) {
                                    return const Center(child: CircularProgressIndicator());
                                  }
                                  if (snapshot.hasError) {
                                    return _ErreurState(
                                      message: snapshot.error.toString(),
                                      onRetry: _recharger,
                                    );
                                  }
                                  final materiels = snapshot.data ?? const [];
                                  return _contenu(materiels);
                                },
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          const Positioned.fill(child: BrandCorners()),
        ],
      ),
    );
  }

  Widget _contenu(List<MaterielItem> materiels) {
    final resultats = _filtrer(materiels);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: _categories(materiels).map((categorie) {
            return _CategoryChip(
              label: categorie,
              selected: categorie == _categorie,
              onTap: () => setState(() => _categorie = categorie),
            );
          }).toList(),
        ),
        const SizedBox(height: 16),
        const Divider(color: EnsupColors.line, height: 1),
        const SizedBox(height: 16),
        Expanded(
          child: resultats.isEmpty
              ? const _EmptyState()
              : ListView.separated(
                  itemCount: resultats.length,
                  separatorBuilder: (_, _) => const SizedBox(height: 10),
                  itemBuilder: (context, index) {
                    final item = resultats[index];
                    return Stack(
                      children: [
                        MaterielCard(item: item, onSelect: () => _selectionner(item)),
                        if (_selectionEnCoursId == item.id)
                          const Positioned.fill(
                            child: ColoredBox(
                              color: Color(0x66FFFFFF),
                              child: Center(child: CircularProgressIndicator()),
                            ),
                          ),
                      ],
                    );
                  },
                ),
        ),
      ],
    );
  }
}

class _SearchField extends StatelessWidget {
  const _SearchField({required this.onChanged});

  final ValueChanged<String> onChanged;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: 14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10),
        border: Border.all(color: EnsupColors.line, width: 1.5),
      ),
      child: Row(
        children: [
          const Icon(Icons.search, size: 18, color: EnsupColors.muted),
          const SizedBox(width: 10),
          Expanded(
            child: TextField(
              onChanged: onChanged,
              style: GoogleFonts.titilliumWeb(fontSize: 14, color: EnsupColors.text),
              decoration: InputDecoration(
                isCollapsed: true,
                border: InputBorder.none,
                hintText: "Rechercher un matériel...",
                hintStyle: GoogleFonts.titilliumWeb(fontSize: 14, color: EnsupColors.muted),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _CategoryChip extends StatelessWidget {
  const _CategoryChip({required this.label, required this.selected, required this.onTap});

  final String label;
  final bool selected;
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(999),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
        decoration: BoxDecoration(
          color: selected ? EnsupColors.cyan : Colors.white,
          borderRadius: BorderRadius.circular(999),
          border: Border.all(color: selected ? EnsupColors.cyan : EnsupColors.line, width: 1.5),
        ),
        child: Text(
          label,
          style: GoogleFonts.darkerGrotesque(
            fontSize: 13,
            fontWeight: FontWeight.w600,
            color: selected ? Colors.white : EnsupColors.muted,
          ),
        ),
      ),
    );
  }
}

class _EmptyState extends StatelessWidget {
  const _EmptyState();

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.inventory_2_outlined, size: 40, color: EnsupColors.muted),
          const SizedBox(height: 10),
          Text(
            "Aucun matériel ne correspond",
            style: GoogleFonts.titilliumWeb(fontSize: 14, color: EnsupColors.muted),
          ),
        ],
      ),
    );
  }
}

class _ErreurState extends StatelessWidget {
  const _ErreurState({required this.message, required this.onRetry});

  final String message;
  final VoidCallback onRetry;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.cloud_off_outlined, size: 40, color: EnsupColors.muted),
          const SizedBox(height: 12),
          Text(
            message,
            textAlign: TextAlign.center,
            style: GoogleFonts.titilliumWeb(fontSize: 14, color: EnsupColors.text2),
          ),
          const SizedBox(height: 14),
          OutlinedButton(
            onPressed: onRetry,
            child: Text(
              "Réessayer",
              style: GoogleFonts.darkerGrotesque(fontWeight: FontWeight.w700),
            ),
          ),
        ],
      ),
    );
  }
}
