import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
import 'package:flux/features/master_data/products/ui/product_dialogs.dart';

class ModelsList extends StatelessWidget {
  final ProductState state;
  const ModelsList(this.state, {super.key});

  @override
  Widget build(BuildContext context) {
    if (state.selectedBrand == null) {
      return const Center(
        child: Text("Seleziona un brand per gestire i modelli"),
      );
    }

    if (state.status == ProductStatus.loading && state.models.isEmpty) {
      return const Center(child: CircularProgressIndicator());
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              "Modelli di ${state.selectedBrand!.name}",
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            ElevatedButton.icon(
              onPressed: () => showModelDialog(context),
              icon: const Icon(Icons.add),
              label: const Text("NUOVO MODELLO"),
            ),
          ],
        ),
        const SizedBox(height: 16),
        Expanded(
          child: ListView.separated(
            itemCount: state.models.length,
            separatorBuilder: (_, _) => const Divider(height: 1),
            itemBuilder: (context, index) {
              final model = state.models[index];
              return ListTile(
                title: Text(model.name),
                subtitle: Text(
                  model.nameWithBrand,
                ), // Quello gestito dal trigger!
                trailing: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      icon: const Icon(Icons.edit_outlined),
                      onPressed: () => showModelDialog(context, model: model),
                    ),
                    IconButton(
                      icon: Icon(
                        model.isActive
                            ? Icons.visibility_outlined
                            : Icons.visibility_off_outlined,
                        color: model.isActive ? context.accent : Colors.grey,
                      ),
                      onPressed: () =>
                          context.read<ProductsCubit>().toggleStatus(
                            Tables.models,
                            model.id!,
                            model.isActive,
                          ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}
