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 '../blocs/coverage_bloc.dart';
import '../blocs/coverage_event.dart';
import '../blocs/coverage_state.dart';

import '../widgets/coverage_header.dart';
import '../widgets/coverage_quick_stats.dart';
import '../widgets/coverage_shift_list.dart';
import '../widgets/late_workers_alert.dart';

/// Page for displaying daily coverage information.
///
/// Shows shifts, worker statuses, and coverage statistics for a selected date.
class CoveragePage extends StatelessWidget {
  /// Creates a [CoveragePage].
  const CoveragePage({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocProvider<CoverageBloc>(
      create: (BuildContext context) => Modular.get<CoverageBloc>()
        ..add(CoverageLoadRequested(date: DateTime.now())),
      child: Scaffold(
        backgroundColor: UiColors.background,
        body: BlocBuilder<CoverageBloc, CoverageState>(
          builder: (BuildContext context, CoverageState state) {
            return Column(
              children: <Widget>[
                CoverageHeader(
                  selectedDate: state.selectedDate ?? DateTime.now(),
                  coveragePercent: state.stats?.coveragePercent ?? 0,
                  totalConfirmed: state.stats?.totalConfirmed ?? 0,
                  totalNeeded: state.stats?.totalNeeded ?? 0,
                  onDateSelected: (DateTime date) {
                    BlocProvider.of<CoverageBloc>(context).add(
                      CoverageLoadRequested(date: date),
                    );
                  },
                  onRefresh: () {
                    BlocProvider.of<CoverageBloc>(context).add(
                      const CoverageRefreshRequested(),
                    );
                  },
                ),
                Expanded(
                  child: _buildBody(context: context, state: state),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  /// Builds the main body content based on the current state.
  Widget _buildBody({
    required BuildContext context,
    required CoverageState state,
  }) {
    if (state.status == CoverageStatus.loading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    if (state.status == CoverageStatus.failure) {
      return Center(
        child: Padding(
          padding: const EdgeInsets.all(UiConstants.space6),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              const Icon(
                UiIcons.warning,
                size: UiConstants.space12,
                color: UiColors.destructive,
              ),
              const SizedBox(height: UiConstants.space4),
              Text(
                'Failed to load coverage data',
                style: UiTypography.title2m.copyWith(
                  color: UiColors.textPrimary,
                ),
              ),
              const SizedBox(height: UiConstants.space2),
              Text(
                state.errorMessage ?? 'An unknown error occurred',
                style: UiTypography.body2r.copyWith(
                  color: UiColors.mutedForeground,
                ),
                textAlign: TextAlign.center,
              ),
            ],
          ),
        ),
      );
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(UiConstants.space5),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          if (state.stats != null) ...<Widget>[
            CoverageQuickStats(stats: state.stats!),
            const SizedBox(height: UiConstants.space5),
          ],
          if (state.stats != null && state.stats!.late > 0) ...<Widget>[
            LateWorkersAlert(lateCount: state.stats!.late),
            const SizedBox(height: UiConstants.space5),
          ],
          Text(
            'Shifts',
            style: UiTypography.title2b.copyWith(
              color: UiColors.textPrimary,
            ),
          ),
          const SizedBox(height: UiConstants.space3),
          CoverageShiftList(shifts: state.shifts),
        ],
      ),
    );
  }
}
