import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../controllers/home_controller.dart';
import '../models/filament_model.dart';
import '../widgets/filament_card.dart';
import '../widgets/glass_app_bar.dart';
import '../pages/detail_view.dart';

class HomePage extends GetView<HomeController> {
  static const String namedRoute = '/home-page';
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    final homeCtrl = controller;

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: GlassAppBar(
        title: 'Filament Tracker',
        subtitle: 'Verwalte deine Filamente',
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: homeCtrl.openAddDialog,
        backgroundColor: const Color(0xFF7B9FFF),
        foregroundColor: Colors.white,
        tooltip: 'Filament hinzufügen',
        child: const Icon(Icons.add_rounded),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Color(0xFF0D0F14),
              Color(0xFF141824),
              Color(0xFF1A2035),
              Color(0xFF0F1520),
            ],
            stops: [0.0, 0.35, 0.65, 1.0],
          ),
        ),
        child: Obx(() {
          if (homeCtrl.isloading.value) {
            return const Center(child: CircularProgressIndicator());
          }

          if (homeCtrl.filaments.isEmpty) {
            return const Center(
              child: Text(
                'Noch keine Filamente vorhanden.\nKlicke auf "+" um ein Filament hinzuzufügen.',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 16, color: Colors.white70),
              ),
            );
          }

          return LayoutBuilder(
            builder: (context, constraints) {
              final isWide = constraints.maxWidth >= 700;

              return CustomScrollView(
                slivers: [
                  SliverPadding(
                    padding: EdgeInsets.only(
                      top: MediaQuery.of(context).padding.top + 96,
                      left: isWide ? 24 : 16,
                      right: isWide ? 24 : 16,
                      bottom: 96,
                    ),
                    sliver: isWide
                        ? SliverGrid(
                            gridDelegate:
                                const SliverGridDelegateWithMaxCrossAxisExtent(
                                  maxCrossAxisExtent: 560,
                                  mainAxisSpacing: 16,
                                  crossAxisSpacing: 16,
                                  childAspectRatio: 1.3,
                                ),
                            delegate: SliverChildBuilderDelegate(
                              (context, i) =>
                                  _buildCard(homeCtrl, homeCtrl.filaments[i]),
                              childCount: homeCtrl.filaments.length,
                            ),
                          )
                        : SliverList(
                            delegate: SliverChildBuilderDelegate(
                              (context, i) => Padding(
                                padding: const EdgeInsets.only(bottom: 16),
                                child: _buildCard(
                                  homeCtrl,
                                  homeCtrl.filaments[i],
                                ),
                              ),
                              childCount: homeCtrl.filaments.length,
                            ),
                          ),
                  ),
                ],
              );
            },
          );
        }),
      ),
    );
  }

  Widget _buildCard(HomeController ctrl, FilamentModel filament) {
    return FilamentCard(
      filament: filament,
      onTap: () async {
        final result = await Get.toNamed(DetailPage.namedRoute, arguments: filament);
        // 'deleted' → Filament aus der lokalen Liste entfernen
        if (result == 'deleted') {
          ctrl.deleteFilamentLocal(filament);
        }
        // Wurde bearbeitet → geändertes Filament zurück übergeben
        if (result is FilamentModel) {
          ctrl.editFilament(result);
        }
      },
      onEdit: () => ctrl.openEditDialog(filament),
      onDelete: () => ctrl.deleteFilament(filament),
    );
  }
}
