import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_domain/krow_domain.dart';
import 'package:core_localization/core_localization.dart';

import '../blocs/certificates/certificates_cubit.dart';
import '../blocs/certificates/certificates_state.dart';
import '../widgets/add_certificate_card.dart';
import '../widgets/certificate_card.dart';
import '../widgets/certificate_upload_modal.dart';
import '../widgets/certificates_header.dart';

/// Page for viewing and managing staff certificates.
///
/// Refactored to be stateless and follow clean architecture.
class CertificatesPage extends StatelessWidget {
  const CertificatesPage({super.key});

  @override
  Widget build(BuildContext context) {
    // Dependency Injection: Retrieve the Cubit
    final CertificatesCubit cubit = Modular.get<CertificatesCubit>();

    return BlocBuilder<CertificatesCubit, CertificatesState>(
      bloc: cubit,
      builder: (BuildContext context, CertificatesState state) {
        if (state.status == CertificatesStatus.loading ||
            state.status == CertificatesStatus.initial) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        if (state.status == CertificatesStatus.failure) {
          return Scaffold(
            appBar: AppBar(title: Text(t.staff_certificates.title)),
            body: Center(
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                  child: Text(
                    state.errorMessage != null
                        ? translateErrorKey(state.errorMessage!)
                        : t.staff_certificates.error_loading,
                  textAlign: TextAlign.center,
                  style: UiTypography.body2r.textSecondary,
                ),
              ),
            ),
          );
        }

        final List<StaffDocument> documents = state.certificates;

        return Scaffold(
          backgroundColor: UiColors.background, // Matches 0xFFF8FAFC
          body: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                CertificatesHeader(
                  completedCount: state.completedCount,
                  totalCount: state.totalCount,
                ),
                Transform.translate(
                  offset: const Offset(0, -48),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: UiConstants.space5),
                    child: Column(
                      children: <Widget>[
                        ...documents.map((StaffDocument doc) => CertificateCard(
                              document: doc,
                              onUpload: () => _showUploadModal(context, doc),
                              onEditExpiry: () => _showEditExpiryDialog(context, doc),
                              onRemove: () => _showRemoveConfirmation(context, doc),
                              onView: () {
                                UiSnackbar.show(
                                  context,
                                  message: t.staff_certificates.card.opened_snackbar,
                                  type: UiSnackbarType.success,
                                );
                              },
                            )),
                        const SizedBox(height: UiConstants.space4),
                        AddCertificateCard(
                          onTap: () => _showUploadModal(context, null),
                        ),
                        const SizedBox(height: UiConstants.space8),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showUploadModal(BuildContext context, StaffDocument? document) {
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) => CertificateUploadModal(
        document: document,
        onSave: () {
          // TODO: Implement upload via Cubit
          // Modular.get<CertificatesCubit>().uploadCertificate(...);
          Navigator.pop(context);
        },
        onCancel: () => Navigator.pop(context),
      ),
    );
  }

  void _showEditExpiryDialog(BuildContext context, StaffDocument document) {
    _showUploadModal(context, document);
  }

  void _showRemoveConfirmation(BuildContext context, StaffDocument document) {
    showDialog<void>(
      context: context,
      builder: (BuildContext context) => AlertDialog(
        title: Text(t.staff_certificates.delete_modal.title),
        content: Text(t.staff_certificates.delete_modal.message),
        actions: <Widget>[
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(t.staff_certificates.delete_modal.cancel),
          ),
          TextButton(
            onPressed: () {
              // TODO: Implement delete via Cubit
              // Modular.get<CertificatesCubit>().deleteCertificate(document.id);
              Navigator.pop(context);
            },
            style: TextButton.styleFrom(foregroundColor: UiColors.destructive),
            child: Text(t.staff_certificates.delete_modal.confirm),
          ),
        ],
      ),
    );
  }
}
