import "package:flutter/material.dart";
import "package:google_fonts/google_fonts.dart";
import "../theme/ensup_colors.dart";
import "../models/materiel_item.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 de matériels.
class CatalogueScreen extends StatefulWidget {
  const CatalogueScreen({super.key});

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

const _materiels = <MaterielItem>[
  MaterielItem(
    nom: "PC Dell Latitude 5420",
    categorie: "Ordinateur",
    marque: "Dell",
    modele: "Latitude 5420",
    reference: "ENS-PC-001",
    campus: "Paris · Ensitech",
    etatGeneral: "Bon état",
    disponible: true,
    accessoires: ["Chargeur 65W", "Souris sans fil", "Housse de protection", "Câble HDMI"],
    icon: Icons.laptop_mac,
  ),
  MaterielItem(
    nom: "Vidéoprojecteur Epson EB-X51",
    categorie: "Projection",
    marque: "Epson",
    modele: "EB-X51",
    reference: "ENS-VP-003",
    campus: "Paris · Ensitech",
    etatGeneral: "Bon état",
    disponible: true,
    accessoires: ["Télécommande", "Câble HDMI", "Câble VGA"],
    icon: Icons.videocam_outlined,
  ),
  MaterielItem(
    nom: "Chargeur USB-C 65W",
    categorie: "Accessoire",
    marque: "Anker",
    modele: "PowerPort III",
    reference: "ENS-CH-012",
    campus: "Paris · Ensitech",
    etatGeneral: "Bon état",
    disponible: false,
    accessoires: [],
    icon: Icons.power_outlined,
  ),
  MaterielItem(
    nom: "PC Lenovo ThinkPad E14",
    categorie: "Ordinateur",
    marque: "Lenovo",
    modele: "ThinkPad E14",
    reference: "ENS-PC-004",
    campus: "Paris · Ensitech",
    etatGeneral: "Bon état",
    disponible: true,
    accessoires: ["Chargeur 65W", "Souris sans fil", "Housse de protection"],
    icon: Icons.laptop_mac,
  ),
];

const _categories = ["Tous", "Ordinateurs", "Projection", "Câbles", "Accessoires"];

class _CatalogueScreenState extends State<CatalogueScreen> {
  String _recherche = "";
  String _categorie = "Tous";

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

  void _selectionner(BuildContext context, MaterielItem item) {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (_) => DetailScreen(item: item)),
    );
  }

  @override
  Widget build(BuildContext context) {
    final resultats = _resultats;

    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: "Paris · Ensitech",
                      userName: "Lucas Martin",
                      userInitials: "LM",
                      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),
                            Wrap(
                              spacing: 8,
                              runSpacing: 8,
                              children: _categories.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
                                  ? _EmptyState()
                                  : ListView.separated(
                                      itemCount: resultats.length,
                                      separatorBuilder: (_, _) => const SizedBox(height: 10),
                                      itemBuilder: (context, index) {
                                        final item = resultats[index];
                                        return MaterielCard(
                                          item: item,
                                          onSelect: () => _selectionner(context, item),
                                        );
                                      },
                                    ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          const Positioned.fill(child: BrandCorners()),
        ],
      ),
    );
  }
}

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: 14,
            fontWeight: FontWeight.w600,
            color: selected ? Colors.white : EnsupColors.muted,
          ),
        ),
      ),
    );
  }
}

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