import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../shared/widgets/nav_bar_config.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../shared/widgets/form_section.dart';
import '../../shared/widgets/form_field_row.dart';
import '../../shared/widgets/status_banner.dart';
import '../../shared/widgets/action_bar.dart';
import '../../shared/widgets/approval_timeline.dart';
import 'expense_application_model.dart';
import '../../core/i18n/app_localizations.dart';
import 'expense_application_list_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_colors_extension.dart';

class ExpenseApplicationDetailPage extends ConsumerWidget {
  final String id;
  const ExpenseApplicationDetailPage({super.key, required this.id});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final app = mockExpenseApplications.firstWhere(
      (e) => e.id == id,
      orElse: () => mockExpenseApplications.first,
    );
    final l10n = AppLocalizations.of(context);

    ref
        .read(navBarConfigProvider.notifier)
        .update(
          NavBarConfig(
            title: l10n.get('expenseApplyDetail'),
            showBack: true,
            onBack: () => context.pop(),
          ),
        );
    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                _buildStatusBanner(context, app, colors),
                const SizedBox(height: 4),
                _buildSubmitTime(context, app, colors),
                const SizedBox(height: 16),
                _buildBasicInfoSection(app, l10n, colors),
                const SizedBox(height: 16),
                _buildExpenseDetailSection(app, l10n, colors),
                const SizedBox(height: 16),
                _buildAttachmentSection(l10n, colors),
                const SizedBox(height: 16),
                if (app.approvalRecords.isNotEmpty ||
                    app.approvalChain.isNotEmpty)
                  _buildApprovalSection(l10n, app),
                const SizedBox(height: 16),
              ],
            ),
          ),
        ),
        _buildBottomBar(context, app),
      ],
    );
  }

  Widget _buildStatusBanner(
    BuildContext context,
    ExpenseApplicationModel app,
    AppColorsExtension colors,
  ) {
    final l10n = AppLocalizations.of(context);
    final (icon, color, label) = switch (app.status) {
      'approved' => (Icons.check_circle, colors.success, l10n.get('approved')),
      'rejected' => (Icons.cancel, colors.danger, l10n.get('rejected')),
      'draft' => (Icons.edit, colors.statusGray, l10n.get('draft')),
      _ => (Icons.schedule, colors.warning, l10n.get('pending')),
    };
    final approverText = switch (app.status) {
      'approved' when app.approvalRecords.isNotEmpty =>
        '${l10n.get('approver')}：${app.approvalRecords.last.approverName}',
      'rejected' when app.approvalRecords.isNotEmpty =>
        '${l10n.get('rejecter')}：${app.approvalRecords.last.approverName}',
      'pending' when app.currentApproverId.isNotEmpty =>
        '${l10n.get('currentApprover')}：${app.currentApproverId}',
      _ => '',
    };
    return StatusBanner(
      icon: icon,
      statusText: label,
      subText: approverText,
      color: color,
    );
  }

  Widget _buildSubmitTime(
    BuildContext context,
    ExpenseApplicationModel app,
    AppColorsExtension colors,
  ) {
    final l10n = AppLocalizations.of(context);
    return Padding(
      padding: const EdgeInsets.only(left: 4, top: 4),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          '${l10n.get('submitTimeText')}：${du.DateUtils.formatDateTime(app.createTime)}',
          style: TextStyle(
            fontSize: AppFontSizes.caption,
            color: colors.textPlaceholder,
          ),
        ),
      ),
    );
  }

  Widget _buildBasicInfoSection(
    ExpenseApplicationModel app,
    AppLocalizations l10n,
    AppColorsExtension colors,
  ) {
    String urgencyLabel = switch (app.urgency) {
      'urgent' => l10n.get('urgent'),
      'normal' => l10n.get('normal'),
      _ => app.urgency,
    };

    return FormSection(
      title: l10n.get('basicInfo'),
      children: [
        FormFieldRow(
          label: l10n.get('applicant'),
          value: app.applicantName,
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: l10n.get('department'),
          value: app.deptName,
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: l10n.get('expenseType'),
          value: app.expenseType,
          readOnly: true,
          showArrow: false,
        ),
        Container(
          height: 44,
          padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                l10n.get('expenseAmount'),
                style: TextStyle(
                  fontSize: AppFontSizes.body,
                  color: colors.textSecondary,
                ),
              ),
              Text(
                '¥${app.estimatedAmount.toStringAsFixed(2)}',
                style: TextStyle(
                  fontSize: AppFontSizes.subtitle,
                  fontWeight: FontWeight.w700,
                  color: colors.amountPrimary,
                ),
              ),
            ],
          ),
        ),
        FormFieldRow(
          label: l10n.get('relatedProject'),
          value: app.projectName.isNotEmpty ? app.projectName : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: l10n.get('budgetSubject'),
          value: app.budgetSubjectId.isNotEmpty ? app.budgetSubjectId : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: l10n.get('emergencyLevel'),
          value: urgencyLabel,
          readOnly: true,
          showArrow: false,
        ),
      ],
    );
  }

  Widget _buildExpenseDetailSection(
    ExpenseApplicationModel app,
    AppLocalizations l10n,
    AppColorsExtension colors,
  ) {
    return FormSection(
      title: l10n.get('expenseDetails'),
      children: [
        // Table header
        Container(
          height: 36,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          decoration: BoxDecoration(
            color: colors.bgPage,
            borderRadius: BorderRadius.circular(4),
          ),
          child: Row(
            children: [
              Expanded(
                flex: 3,
                child: Text(
                  l10n.get('expenseProject'),
                  style: TextStyle(
                    fontSize: AppFontSizes.caption,
                    fontWeight: FontWeight.w500,
                    color: colors.textSecondary,
                  ),
                ),
              ),
              Expanded(
                flex: 2,
                child: Text(
                  l10n.get('amount'),
                  textAlign: TextAlign.right,
                  style: TextStyle(
                    fontSize: AppFontSizes.caption,
                    fontWeight: FontWeight.w500,
                    color: colors.textSecondary,
                  ),
                ),
              ),
            ],
          ),
        ),
        if (app.details.isEmpty)
          Padding(
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Text(
              l10n.get('noDetailData'),
              style: TextStyle(
                fontSize: AppFontSizes.body,
                color: colors.textPlaceholder,
              ),
            ),
          )
        else
          ...app.details.map(
            (d) => SizedBox(
              height: 28,
              child: Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Text(
                      d.itemName,
                      style: TextStyle(
                        fontSize: AppFontSizes.body,
                        color: colors.textPrimary,
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Text(
                      '¥${d.estimatedAmount.toStringAsFixed(2)}',
                      textAlign: TextAlign.right,
                      style: TextStyle(
                        fontSize: AppFontSizes.body,
                        fontWeight: FontWeight.w500,
                        color: colors.amountPrimary,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
      ],
    );
  }

  Widget _buildAttachmentSection(
    AppLocalizations l10n,
    AppColorsExtension colors,
  ) {
    return FormSection(
      title: l10n.get('attachments'),
      children: [
        Wrap(
          spacing: 8,
          runSpacing: 8,
          children: List.generate(3, (i) {
            return Container(
              width: 80,
              height: 80,
              decoration: BoxDecoration(
                color: colors.bgPage,
                borderRadius: BorderRadius.circular(4),
                border: Border.all(
                  color: colors.border,
                  strokeAlign: BorderSide.strokeAlignInside,
                ),
              ),
              child: Center(
                child: Icon(
                  Icons.image_outlined,
                  size: 24,
                  color: colors.textPlaceholder,
                ),
              ),
            );
          }),
        ),
      ],
    );
  }

  Widget _buildApprovalSection(
    AppLocalizations l10n,
    ExpenseApplicationModel app,
  ) {
    return FormSection(
      title: l10n.get('approvalFlow'),
      children: [
        ApprovalTimeline(
          records: app.approvalRecords,
          chain: app.approvalChain,
          currentApproverId: app.currentApproverId,
        ),
      ],
    );
  }

  Widget _buildBottomBar(BuildContext context, ExpenseApplicationModel app) {
    final l10n = AppLocalizations.of(context);
    final canWithdraw = app.status == 'pending' || app.status == 'draft';

    if (!canWithdraw) {
      return const SizedBox.shrink();
    }

    return ActionBar(
      showLeft: false,
      centerLabel: l10n.get('withdrawApplication'),
      rightLabel: l10n.get('submitApproval'),
      onCenterTap: () {
        TDToast.showText(l10n.get('withdrawn'), context: context);
        context.pop();
      },
      onRightTap: null,
    );
  }
}
