import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/features/attachments/blocs/attachments_bloc.dart';
import 'package:flux/features/attachments/models/attachment_model.dart';
import 'package:flux/features/attachments/ui/attachment_viewer_screen.dart';
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:flux/features/tickets/models/ticket_status_extension.dart';
import 'package:go_router/go_router.dart';

class TicketListCard extends StatelessWidget {
  final TicketModel ticket;
  final bool isSelected;
  final bool isSelectionMode;
  final bool isDesktop;

  const TicketListCard({
    super.key, // <-- Buona pratica aggiungere il super.key
    required this.ticket,
    required this.isSelected,
    required this.isSelectionMode,
    required this.isDesktop,
  });

  void _openFile({
    required BuildContext context,
    required AttachmentModel file,
  }) {
    // 1. Catturiamo il BLoC dalla pagina corrente prima di navigare
    final operationFilesBloc = context.read<AttachmentsBloc>();
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (viewerContext) => BlocProvider.value(
          value: operationFilesBloc,
          child: AttachmentViewerScreen(
            attachment: file,
            onRename: (newName) {
              // Spara l'evento al BLoC e lui farà il resto!
              operationFilesBloc.add(RenameAttachmentEvent(file, newName));
            },
            onDelete: () {
              operationFilesBloc.add(DeleteSpecificAttachmentEvent(file));
            },
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final statusColor = ticket.ticketStatus.color;
    final statusIcon = ticket.ticketStatus.icon;

    // Tocco Ninja: Ricaviamo l'iniziale del cliente per l'avatar!
    final customerName = ticket.customer?.name ?? '?';
    final initial = customerName.isNotEmpty
        ? customerName[0].toUpperCase()
        : '?';

    return Card(
      // 1. Sfondo leggermente colorato se selezionato
      color: isSelected ? Colors.blue.withValues(alpha: 0.1) : null,
      margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
      clipBehavior: Clip.antiAlias,
      child: IntrinsicHeight(
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // LA STRISCIA COLORATA LATERALE (Intoccabile, è bellissima)
            Container(width: 6, color: statusColor),
            Center(
              child: Padding(
                padding: const EdgeInsets.only(left: 16.0),
                child: isDesktop
                    ? Checkbox(
                        value: isSelected,
                        onChanged: (_) {
                          if (ticket.id != null) {
                            context
                                .read<TicketListCubit>()
                                .toggleTicketSelection(ticket);
                          }
                        },
                      )
                    : GestureDetector(
                        onTap: () {
                          if (ticket.id != null) {
                            context
                                .read<TicketListCubit>()
                                .toggleTicketSelection(ticket);
                          }
                        },
                        child: AnimatedSwitcher(
                          duration: const Duration(milliseconds: 300),
                          transitionBuilder: (child, animation) =>
                              ScaleTransition(scale: animation, child: child),
                          child: isSelected
                              ? const CircleAvatar(
                                  key: ValueKey('selected'),
                                  backgroundColor: Colors.blue,
                                  child: Icon(Icons.check, color: Colors.white),
                                )
                              : CircleAvatar(
                                  key: const ValueKey('unselected'),
                                  backgroundColor: Colors.grey.shade200,
                                  child: Text(
                                    initial, // L'iniziale del cliente!
                                    style: TextStyle(
                                      color: Colors.grey.shade700,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                        ),
                      ),
              ),
            ),
            Expanded(
              child: ListTile(
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 8.0,
                ),

                // ----------------------------------------
                title: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Text(
                        ticket.customer?.name ?? 'Cliente Sconosciuto',
                        style: const TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                        ),
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    if (ticket.shippingDocument != null &&
                        ticket.shippingDocument!.attachments.isNotEmpty) ...[
                      IconButton(
                        icon: const Icon(
                          Icons.picture_as_pdf,
                          color: Colors.redAccent,
                        ),
                        onPressed: () {
                          final attachments =
                              ticket.shippingDocument!.attachments;

                          if (attachments.length == 1) {
                            // CASO 1: C'è solo il DDT. Apriamo SUBITO il Document Viewer!
                            _openFile(
                              context: context,
                              file: attachments.first,
                            );
                          } else {
                            // CASO 2: Più allegati. Mostriamo una BottomSheet fulminea per far scegliere all'utente.
                            showModalBottomSheet(
                              context: context,
                              builder: (context) => ListView.builder(
                                shrinkWrap: true,
                                itemCount: attachments.length,
                                itemBuilder: (context, index) {
                                  final file = attachments[index];
                                  return ListTile(
                                    leading: Icon(
                                      file.extension == 'pdf'
                                          ? Icons.picture_as_pdf
                                          : Icons.image,
                                    ),
                                    title: Text(file.name),
                                    subtitle: Text(
                                      '${(file.fileSize / 1024).toStringAsFixed(1)} KB',
                                    ),
                                    onTap: () {
                                      Navigator.pop(
                                        context,
                                      ); // Chiude la scelta
                                      _openFile(
                                        context: context,
                                        file: file,
                                      ); // Apre il viewer
                                    },
                                  );
                                },
                              ),
                            );
                          }
                        },
                      ),
                    ],

                    // IL BADGE DELLO STATO
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: statusColor.withValues(alpha: 0.1),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: statusColor.withValues(alpha: 0.5),
                        ),
                      ),

                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(statusIcon, size: 14, color: statusColor),
                          const SizedBox(width: 4),
                          Text(
                            ticket.ticketStatus.displayValue,
                            style: TextStyle(
                              fontSize: 12,
                              color: statusColor,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                subtitle: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 4),
                    Text(
                      ticket.targetModelName ?? ticket.ticketType.displayValue,
                      style: const TextStyle(fontWeight: FontWeight.w500),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      ticket.createdAt != null
                          ? 'Creato il: ${ticket.createdAt!.day}/${ticket.createdAt!.month}/${ticket.createdAt!.year}'
                          : '',
                      style: TextStyle(
                        color: Colors.grey.shade600,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),

                // --- 3. GESTIONE DEI TAP PER LA SELEZIONE ---
                onTap: () {
                  if (isSelectionMode) {
                    // Modalità selezione attiva: un tap normale seleziona/deseleziona
                    if (ticket.id != null) {
                      context.read<TicketListCubit>().toggleTicketSelection(
                        ticket,
                      );
                    }
                  } else {
                    // Modalità normale: entra nel dettaglio del ticket
                    context.pushNamed(
                      Routes.ticketForm,
                      pathParameters: {'id': ticket.id!},
                      extra: (ticket: ticket, createdBy: null),
                    );
                  }
                },
                onLongPress: () {
                  // Pressione lunga: forza la selezione (utile per iniziare il workflow)
                  if (!isSelectionMode && ticket.id != null) {
                    context.read<TicketListCubit>().toggleTicketSelection(
                      ticket,
                    );
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
