import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/features/home/dashboard_task_list/blocs/dashboard_task_list_cubit.dart';
import 'package:go_router/go_router.dart';
import 'package:flux/features/tasks/models/task_status.dart';

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

  @override
  Widget build(BuildContext context) {
    return _DashboardTasksCardContent();
  }
}

class _DashboardTasksCardContent extends StatelessWidget {
  const _DashboardTasksCardContent();

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    const color =
        Colors.orange; // Colore arancione per distinguerla dai Ticket blu

    return Card(
      elevation: 0,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(16),
        side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)),
      ),
      child: InkWell(
        onTap: () => context.pushNamed(
          Routes.tasks,
        ), // Porta alla lista completa (TaskListScreen)
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // --- HEADER DELLA CARD ---
              Row(
                children: [
                  Container(
                    padding: const EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      color: color.withValues(alpha: 0.1),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: const Icon(
                      Icons.assignment_outlined, // Icona a tema ToDo
                      color: color,
                      size: 20,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      "I Miei Task",
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 16,
                        color: context.primaryText,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 12),

              // --- CORPO DELLA CARD (LA LISTA REAL-TIME) ---
              Expanded(
                child: BlocBuilder<DashboardTaskListCubit, DashboardTaskListState>(
                  builder: (context, state) {
                    if (state.status == DashboardTaskListStatus.loading ||
                        state.status == DashboardTaskListStatus.initial) {
                      return const Center(child: CircularProgressIndicator());
                    }

                    if (state.status == DashboardTaskListStatus.failure) {
                      return Center(
                        child: Text(
                          "Errore di caricamento ${state.errorMessage}",
                          style: TextStyle(color: theme.colorScheme.error),
                        ),
                      );
                    }

                    if (state.tasks.isEmpty) {
                      return Center(
                        child: Text(
                          "Nessun task in sospeso. Ottimo lavoro!",
                          style: TextStyle(
                            color: context.secondaryText,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      );
                    }

                    return ListView.separated(
                      itemCount: state.tasks.length,
                      separatorBuilder: (context, index) => Divider(
                        height: 1,
                        color: theme.dividerColor.withValues(alpha: 0.3),
                      ),
                      itemBuilder: (context, index) {
                        final task = state.tasks[index];

                        // Definisci il colore in base allo stato del task
                        final statusColor = task.status == TaskStatus.inProgress
                            ? Colors.blue
                            : Colors.grey.shade400;

                        // Formattiamo la data (o indichiamo se non c'è)
                        final dueDateString = task.dueDate != null
                            ? "${task.dueDate!.day}/${task.dueDate!.month}"
                            : "Nessuna";

                        // Controllo Ninja: Il task è già scaduto rispetto a oggi?
                        final isOverdue =
                            task.dueDate != null &&
                            task.dueDate!.isBefore(DateTime.now());

                        return InkWell(
                          onTap: () => context.pushNamed(
                            Routes.taskForm,
                            extra:
                                task, // Passiamo direttamente il modello intero se il tuo router lo accetta!
                            pathParameters: {'id': task.id ?? 'new'},
                          ),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                  width: 8,
                                  height: 30,
                                  decoration: BoxDecoration(
                                    color: statusColor,
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Expanded(
                                  flex: 7,
                                  child: Text(
                                    task.title,
                                    style: TextStyle(
                                      fontWeight: FontWeight.w600,
                                      color: context.primaryText,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                Expanded(
                                  flex: 3,
                                  child: Align(
                                    alignment: Alignment.centerRight,
                                    child: Text(
                                      dueDateString,
                                      style: TextStyle(
                                        color: isOverdue
                                            ? theme.colorScheme.error
                                            : context.secondaryText,
                                        fontSize: 12,
                                        fontWeight: isOverdue
                                            ? FontWeight.bold
                                            : FontWeight.normal,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
