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 '../blocs/tax_forms/tax_forms_cubit.dart';
import '../blocs/tax_forms/tax_forms_state.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: UiColors.primary,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(UiIcons.arrowLeft, color: UiColors.bgPopup),
          onPressed: () => Modular.to.pop(),
        ),
        title: Text(
          'Tax Documents',
          style: UiTypography.headline3m.copyWith(color: UiColors.bgPopup),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(24),
          child: Padding(
            padding: const EdgeInsets.only(
              left: UiConstants.space5,
              right: UiConstants.space5,
              bottom: UiConstants.space5,
            ),
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text(
                    'Complete required forms to start working',
                    style: UiTypography.body3r.copyWith(
                      color: UiColors.bgPopup.withOpacity(0.8),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      body: BlocProvider<TaxFormsCubit>(
        create: (BuildContext context) {
          final TaxFormsCubit cubit = Modular.get<TaxFormsCubit>();
          if (cubit.state.status == TaxFormsStatus.initial) {
            cubit.loadTaxForms();
          }
          return cubit;
        },
        child: BlocBuilder<TaxFormsCubit, TaxFormsState>(
          builder: (BuildContext context, TaxFormsState state) {
            if (state.status == TaxFormsStatus.loading) {
              return const Center(child: CircularProgressIndicator());
            }

            if (state.status == TaxFormsStatus.failure) {
              return Center(
                child: Text(state.errorMessage ?? 'Error loading forms'),
              );
            }

            return SingleChildScrollView(
              padding: const EdgeInsets.symmetric(
                horizontal: UiConstants.space5,
                vertical: UiConstants.space6,
              ),
              child: Column(
                spacing: UiConstants.space6,
                children: <Widget>[
                  _buildProgressOverview(state.forms),
                  ...state.forms.map(_buildFormCard),
                  _buildInfoCard(),
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  Widget _buildProgressOverview(List<TaxForm> forms) {
    final int completedCount = forms
        .where(
          (TaxForm f) =>
              f.status == TaxFormStatus.submitted ||
              f.status == TaxFormStatus.approved,
        )
        .length;
    final int totalCount = forms.length;
    final double progress = totalCount > 0 ? completedCount / totalCount : 0.0;

    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.bgPopup,
        borderRadius: UiConstants.radiusLg,
        border: Border.all(color: UiColors.border),
      ),
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                'Document Progress',
                style: UiTypography.body2m.copyWith(
                  color: UiColors.textPrimary,
                ),
              ),
              Text(
                '$completedCount/$totalCount',
                style: UiTypography.body2m.copyWith(
                  color: UiColors.textSecondary,
                ),
              ),
            ],
          ),
          const SizedBox(height: UiConstants.space3),
          ClipRRect(
            borderRadius: UiConstants.radiusSm,
            child: LinearProgressIndicator(
              value: progress,
              minHeight: 8,
              backgroundColor: UiColors.background,
              valueColor: const AlwaysStoppedAnimation<Color>(UiColors.primary),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFormCard(TaxForm form) {
    // Helper to get icon based on type (could be in entity or a mapper)
    final String icon = form is I9TaxForm ? '🛂' : '📋';

    return GestureDetector(
      onTap: () {
        if (form is I9TaxForm) {
          Modular.to.pushNamed('i9', arguments: form);
        } else if (form is W4TaxForm) {
          Modular.to.pushNamed('w4', arguments: form);
        }
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: UiConstants.space4),
        padding: const EdgeInsets.all(UiConstants.space4),
        decoration: BoxDecoration(
          color: UiColors.bgPopup,
          borderRadius: UiConstants.radiusLg,
          border: Border.all(color: UiColors.border),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              width: 48,
              height: 48,
              decoration: BoxDecoration(
                color: UiColors.primary.withOpacity(0.1),
                borderRadius: UiConstants.radiusLg,
              ),
              child: Center(child: Text(icon, style: UiTypography.headline1m)),
            ),
            const SizedBox(width: UiConstants.space4),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        form.title,
                        style: UiTypography.headline4m.copyWith(
                          color: UiColors.textPrimary,
                        ),
                      ),
                      _buildStatusBadge(form.status),
                    ],
                  ),
                  const SizedBox(height: UiConstants.space1),
                  Text(
                    form.subtitle ?? '',
                    style: UiTypography.body2m.copyWith(
                      fontWeight: FontWeight.w500,
                      color: UiColors.textSecondary,
                    ),
                  ),
                  const SizedBox(height: UiConstants.space1),
                  Text(
                    form.description ?? '',
                    style: UiTypography.body3r.copyWith(
                      color: UiColors.textSecondary,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: UiConstants.space2),
            const Icon(
              UiIcons.chevronRight,
              color: UiColors.textSecondary,
              size: 20,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildStatusBadge(TaxFormStatus status) {
    switch (status) {
      case TaxFormStatus.submitted:
      case TaxFormStatus.approved:
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: UiConstants.space2,
            vertical: UiConstants.space1,
          ),
          decoration: BoxDecoration(
            color: UiColors.tagSuccess,
            borderRadius: UiConstants.radiusLg,
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const Icon(
                UiIcons.success,
                size: 12,
                color: UiColors.textSuccess,
              ),
              const SizedBox(width: UiConstants.space1),
              Text(
                'Completed',
                style: UiTypography.footnote2b.copyWith(
                  color: UiColors.textSuccess,
                ),
              ),
            ],
          ),
        );
      case TaxFormStatus.inProgress:
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: UiConstants.space2,
            vertical: UiConstants.space1,
          ),
          decoration: BoxDecoration(
            color: UiColors.tagPending,
            borderRadius: UiConstants.radiusLg,
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              const Icon(UiIcons.clock, size: 12, color: UiColors.textWarning),
              const SizedBox(width: UiConstants.space1),
              Text(
                'In Progress',
                style: UiTypography.footnote2b.copyWith(
                  color: UiColors.textWarning,
                ),
              ),
            ],
          ),
        );
      default:
        return Container(
          padding: const EdgeInsets.symmetric(
            horizontal: UiConstants.space2,
            vertical: UiConstants.space1,
          ),
          decoration: BoxDecoration(
            color: UiColors.tagValue,
            borderRadius: UiConstants.radiusLg,
          ),
          child: Text(
            'Not Started',
            style: UiTypography.footnote2b.copyWith(
              color: UiColors.textSecondary,
            ),
          ),
        );
    }
  }

  Widget _buildInfoCard() {
    return Container(
      padding: const EdgeInsets.all(UiConstants.space4),
      decoration: BoxDecoration(
        color: UiColors.bgSecondary,
        borderRadius: UiConstants.radiusLg,
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          const Icon(UiIcons.file, color: UiColors.primary, size: 20),
          const SizedBox(width: UiConstants.space3),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  'Why are these needed?',
                  style: UiTypography.headline4m.copyWith(
                    color: UiColors.textPrimary,
                  ),
                ),
                const SizedBox(height: UiConstants.space1),
                Text(
                  'I-9 and W-4 forms are required by federal law to verify your employment eligibility and set up correct tax withholding.',
                  style: UiTypography.body3r.copyWith(
                    color: UiColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
