import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/settings/document_sequence/blocs/document_sequence_cubit.dart';
import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DocumentSequenceCubit, DocumentSequenceState>(
      builder: (context, state) {
        if (state.status == DocumentSequenceStatus.loading) {
          return const Center(child: CircularProgressIndicator());
        }
        return LayoutBuilder(
          builder: ((context, constraints) {
            final isLargeScreen = constraints.maxWidth >= 600;
            return _buildMainContent(
              state: state,
              isLargeScreen: isLargeScreen,
              context: context,
            );
          }),
        );
      },
    );
  }

  Widget _buildMainContent({
    required BuildContext context,
    required DocumentSequenceState state,
    required bool isLargeScreen,
  }) {
    final year = DateTime.now().year;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.symmetric(vertical: 16.0),
          child: Text(
            "Protocolli e Numerazione",

            style: Theme.of(
              context,
            ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
          ),
        ),

        // Invece di mappare state.sequences, mappiamo i documenti supportati
        ...DocumentType.values.map((docType) {
          // Cerchiamo se c'è già una configurazione nello stato per questo documento
          final existingList = state.sequences
              .where((s) => s.docType == docType.name)
              .toList();
          final existingSeq = existingList.isNotEmpty
              ? existingList.first
              : null;

          // Se esiste usiamo i suoi valori, altrimenti i default
          final prefix = existingSeq?.prefix ?? docType.defaultPrefix;
          final nextValue = existingSeq?.nextValue ?? 1;

          // Anteprima dinamica (aggiornata a 4 zeri come nel DB!)
          final preview =
              "${prefix.isNotEmpty ? '$prefix-' : ''}$year-${nextValue.toString().padLeft(4, '0')}";

          return Card(
            margin: const EdgeInsets.only(bottom: 12),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    docType.label,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      color: Colors.blue,
                    ),
                  ),
                  const SizedBox(height: 12),
                  Row(
                    children: [
                      Expanded(
                        flex: 2,
                        child: TextFormField(
                          initialValue: prefix,
                          decoration: const InputDecoration(
                            labelText: 'Prefisso',
                            hintText: 'es. TCK',
                          ),
                          onChanged: (val) => context
                              .read<DocumentSequenceCubit>()
                              .updateLocalSequence(docType.name, prefix: val),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        flex: 3,
                        child: TextFormField(
                          initialValue: nextValue.toString(),
                          keyboardType: TextInputType.number,
                          decoration: const InputDecoration(
                            labelText: 'Prossimo Numero',
                          ),
                          onChanged: (val) => context
                              .read<DocumentSequenceCubit>()
                              .updateLocalSequence(
                                docType.name,
                                nextValue: int.tryParse(val) ?? 1,
                              ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.surfaceContainer,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        const Icon(
                          Icons.visibility,
                          size: 16,
                          color: Colors.grey,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          "Anteprima prossimo: ",
                          style: TextStyle(
                            color:
                                Colors.grey.shade700, // Idem per la dark mode
                            fontSize: 12,
                          ),
                        ),
                        Flexible(
                          child: Text(
                            preview,
                            style: const TextStyle(
                              fontWeight: FontWeight.bold,
                              fontFamily: 'monospace',
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
        const SizedBox(height: 16),
        SizedBox(
          width: double.infinity,
          child: ElevatedButton.icon(
            onPressed: () =>
                context.read<DocumentSequenceCubit>().saveSequences(),
            icon: const Icon(Icons.save),
            label: const Text("SALVA PROTOCOLLI"),
          ),
        ),
      ],
    );
  }
}
