import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/widgets/image_upload/blocs/image_upload_cubit.dart';
import 'package:flux/core/widgets/image_upload/ui/image_upload_screen.dart';
import 'package:flux/core/widgets/qr_upload_dialog.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:get_it/get_it.dart';

class SharedFilesSection extends StatelessWidget {
  final String titleNameForUpload;
  // LA NOSTRA CALLBACK MAGICA
  final Future<String?> Function()? onGenerateIdForQr;

  const SharedFilesSection({
    super.key,
    required this.titleNameForUpload,
    this.onGenerateIdForQr,
  });

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              'Allegati e Foto',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),

            BlocBuilder<AttachmentsBloc, AttachmentsState>(
              builder: (context, state) {
                return Row(
                  children: [
                    // --- IL TASTO QR CODE (Ora sempre attivo!) ---
                    Tooltip(
                      message: 'Carica foto con lo smartphone',
                      child: IconButton(
                        icon: const Icon(Icons.qr_code_scanner),
                        color: theme.colorScheme.primary, // Sempre colorato!
                        onPressed: () async {
                          String? targetId = state.parentId;

                          // SE L'ID NON C'È, CHIAMIAMO IL SALVATAGGIO IN BACKGROUND!
                          if (targetId == null) {
                            if (onGenerateIdForQr != null) {
                              ScaffoldMessenger.of(context).showSnackBar(
                                const SnackBar(
                                  content: Text(
                                    'Salvataggio rapido scheda in corso... ⏳',
                                  ),
                                  duration: Duration(seconds: 1),
                                ),
                              );

                              // Aspettiamo che il TicketFormCubit faccia il suo lavoro
                              targetId = await onGenerateIdForQr!();
                            }

                            // Se fallisce (es. validazione form non passata), ci fermiamo
                            if (targetId == null) return;
                          }

                          // GENERAZIONE DEL DEEP LINK AGNOSTICO
                          final companyId = GetIt.I
                              .get<SessionCubit>()
                              .state
                              .company!
                              .id!;
                          final deepLink =
                              'https://flux.catelli.it/upload/${state.parentType.name}/$targetId?companyId=$companyId';

                          if (context.mounted) {
                            showDialog(
                              context: context,
                              builder: (_) => QrUploadDialog(
                                deepLinkUrl: deepLink,
                                title: 'Carica File: $titleNameForUpload',
                              ),
                            );
                          }
                        },
                      ),
                    ),
                    const SizedBox(width: 8),

                    // --- IL TASTO AGGIUNGI CLASSICO (da PC) ---
                    TextButton.icon(
                      icon: const Icon(Icons.add_a_photo),
                      label: const Text('Aggiungi'),
                      onPressed: () {
                        final bloc = context.read<AttachmentsBloc>();
                        Navigator.of(context).push(
                          MaterialPageRoute(
                            builder: (_) => BlocProvider.value(
                              value: bloc,
                              child: BlocProvider<ImageUploadCubit>(
                                create: (context) => ImageUploadCubit(),
                                child: ImageUploadScreen(
                                  title: titleNameForUpload,
                                  companyId: GetIt.I
                                      .get<SessionCubit>()
                                      .state
                                      .company!
                                      .id!,
                                ),
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ],
                );
              },
            ),
          ],
        ),
        const SizedBox(height: 8),

        // --- LA VETRINA DEI FILE (Identica a prima) ---
        BlocBuilder<AttachmentsBloc, AttachmentsState>(
          builder: (context, state) {
            final files = state.allFiles;

            if (state.status == AttachmentsStatus.loading) {
              return const Center(child: CircularProgressIndicator());
            }

            if (files.isEmpty) {
              return Container(
                width: double.infinity,
                padding: const EdgeInsets.all(24),
                decoration: BoxDecoration(
                  color: theme.colorScheme.surface,
                  border: Border.all(
                    color: theme.dividerColor,
                    style: BorderStyle.solid,
                  ),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Column(
                  children: [
                    Icon(
                      Icons.image_not_supported_outlined,
                      color: Colors.grey,
                      size: 32,
                    ),
                    SizedBox(height: 8),
                    Text(
                      'Nessun file allegato',
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              );
            }

            return Wrap(
              spacing: 12,
              runSpacing: 12,
              children: files.map((file) {
                final isImage = [
                  'jpg',
                  'jpeg',
                  'png',
                  'webp',
                ].contains(file.extension.toLowerCase());

                return Container(
                  width: 100,
                  height: 100,
                  decoration: BoxDecoration(
                    color: theme.colorScheme.surface,
                    borderRadius: BorderRadius.circular(12),
                    border: Border.all(color: theme.dividerColor),
                  ),
                  child: Stack(
                    children: [
                      Center(
                        child: isImage
                            ? const Icon(
                                Icons.image,
                                color: Colors.blue,
                                size: 40,
                              )
                            : const Icon(
                                Icons.picture_as_pdf,
                                color: Colors.red,
                                size: 40,
                              ),
                      ),
                      if (file.id == null)
                        Positioned(
                          bottom: 4,
                          left: 4,
                          right: 4,
                          child: Container(
                            padding: const EdgeInsets.symmetric(vertical: 2),
                            decoration: BoxDecoration(
                              color: Colors.orange,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: const Text(
                              'Da salvare',
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 8,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      Positioned(
                        top: -8,
                        right: -8,
                        child: IconButton(
                          icon: const Icon(
                            Icons.cancel,
                            color: Colors.redAccent,
                            size: 20,
                          ),
                          onPressed: () {
                            context.read<AttachmentsBloc>().add(
                              DeleteSpecificAttachmentEvent(file),
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                );
              }).toList(),
            );
          },
        ),
      ],
    );
  }
}
