import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../shell/nav_bar_config.dart';
import '../../core/theme/app_colors.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_model.dart';
import '../../core/i18n/app_localizations.dart';
import 'expense_list_controller.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final expense = mockExpenses.firstWhere(
      (e) => e.id == id,
      orElse: () => mockExpenses.first,
    );
    final l10n = AppLocalizations.of(context);

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

  Widget _buildStatusBanner(ExpenseModel expense) {
    final (icon, color, label) = switch (expense.status) {
      'approved' => (Icons.check_circle, AppColors.success, '已通过'),
      'rejected' => (Icons.cancel, AppColors.danger, '已拒绝'),
      'draft' => (Icons.edit, AppColors.statusGray, '草稿'),
      _ => (Icons.schedule, AppColors.warning, '审批中'),
    };
    final approverText = switch (expense.status) {
      'approved' when expense.approvalRecords.isNotEmpty =>
        '审批人：${expense.approvalRecords.last.approverName}',
      'rejected' when expense.approvalRecords.isNotEmpty =>
        '拒绝人：${expense.approvalRecords.last.approverName}',
      'pending' when expense.currentApproverId.isNotEmpty =>
        '当前审批人：${expense.currentApproverId}',
      _ => '',
    };
    return StatusBanner(
      icon: icon,
      statusText: label,
      subText: approverText,
      color: color,
    );
  }

  Widget _buildSubmitTime(ExpenseModel expense) {
    return Padding(
      padding: const EdgeInsets.only(left: 4, top: 4),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          '提交时间：${du.DateUtils.formatDateTime(expense.createTime)}',
          style: const TextStyle(
            fontSize: AppFontSizes.caption,
            color: AppColors.textPlaceholder,
          ),
        ),
      ),
    );
  }

  Widget _buildBasicInfoSection(ExpenseModel expense) {
    return FormSection(
      title: '基本信息',
      children: [
        FormFieldRow(
          label: '申请人',
          value: expense.applicantName,
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '所属部门',
          value: expense.deptName,
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '费用类型',
          value: expense.expenseType,
          readOnly: true,
          showArrow: false,
        ),
        Container(
          height: 44,
          padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const Text(
                '报销金额',
                style: TextStyle(
                  fontSize: AppFontSizes.body,
                  color: AppColors.textSecondary,
                ),
              ),
              Text(
                '¥${expense.totalAmount.toStringAsFixed(2)}',
                style: const TextStyle(
                  fontSize: AppFontSizes.subtitle,
                  fontWeight: FontWeight.w700,
                  color: AppColors.amountPrimary,
                ),
              ),
            ],
          ),
        ),
        FormFieldRow(
          label: '关联项目',
          value: expense.projectName.isNotEmpty ? expense.projectName : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '预算科目',
          value: expense.budgetSubjectId.isNotEmpty
              ? expense.budgetSubjectId
              : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
      ],
    );
  }

  Widget _buildAccountSection(ExpenseModel expense) {
    return FormSection(
      title: '收款账户',
      children: [
        FormFieldRow(
          label: '开户银行',
          value: expense.accountName.isNotEmpty ? expense.accountName : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '账户名称',
          value: expense.accountName.isNotEmpty ? expense.accountName : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '银行账号',
          value: expense.accountId.isNotEmpty ? expense.accountId : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
      ],
    );
  }

  Widget _buildDetailSection(ExpenseModel expense) {
    return FormSection(
      title: '费用明细',
      children: [
        // Table header
        Container(
          height: 36,
          padding: const EdgeInsets.symmetric(horizontal: 8),
          decoration: BoxDecoration(
            color: AppColors.bgPage,
            borderRadius: BorderRadius.circular(4),
          ),
          child: Row(
            children: [
              const Expanded(
                flex: 3,
                child: Text(
                  '费用项目',
                  style: TextStyle(
                    fontSize: AppFontSizes.caption,
                    fontWeight: FontWeight.w500,
                    color: AppColors.textSecondary,
                  ),
                ),
              ),
              Expanded(
                flex: 2,
                child: Text(
                  '金额',
                  textAlign: TextAlign.right,
                  style: const TextStyle(
                    fontSize: AppFontSizes.caption,
                    fontWeight: FontWeight.w500,
                    color: AppColors.textSecondary,
                  ),
                ),
              ),
            ],
          ),
        ),
        if (expense.details.isEmpty)
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Text(
              '暂无明细数据',
              style: TextStyle(
                fontSize: AppFontSizes.body,
                color: AppColors.textPlaceholder,
              ),
            ),
          )
        else
          ...expense.details.map(
            (d) => Container(
              height: 28,
              child: Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Text(
                      d.expenseDesc,
                      style: const TextStyle(
                        fontSize: AppFontSizes.body,
                        color: AppColors.textPrimary,
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 2,
                    child: Text(
                      '¥${d.totalAmount.toStringAsFixed(2)}',
                      textAlign: TextAlign.right,
                      style: const TextStyle(
                        fontSize: AppFontSizes.body,
                        fontWeight: FontWeight.w500,
                        color: AppColors.amountPrimary,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        if (expense.details.isNotEmpty) ...[
          Container(height: 1, color: AppColors.border),
          Container(
            height: 36,
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '合计',
                  style: TextStyle(
                    fontSize: AppFontSizes.body,
                    fontWeight: FontWeight.w600,
                    color: AppColors.textPrimary,
                  ),
                ),
                Text(
                  '¥${expense.totalAmount.toStringAsFixed(2)}',
                  style: const TextStyle(
                    fontSize: AppFontSizes.subtitle,
                    fontWeight: FontWeight.w700,
                    color: AppColors.amountPrimary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildInvoiceSection(ExpenseModel expense) {
    final hasInvoices = expense.invoiceImages.isNotEmpty;

    return FormSection(
      title: '发票附件',
      children: [
        if (!hasInvoices)
          const Padding(
            padding: EdgeInsets.symmetric(vertical: 8),
            child: Text(
              '暂无发票附件',
              style: TextStyle(
                fontSize: AppFontSizes.body,
                color: AppColors.textPlaceholder,
              ),
            ),
          )
        else
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: expense.invoiceImages.map((url) {
              return Container(
                width: 80,
                height: 80,
                decoration: BoxDecoration(
                  color: AppColors.bgPage,
                  borderRadius: BorderRadius.circular(4),
                  border: Border.all(
                    color: AppColors.border,
                    strokeAlign: BorderSide.strokeAlignInside,
                  ),
                ),
                child: const Center(
                  child: Icon(
                    Icons.image_outlined,
                    size: 24,
                    color: AppColors.textPlaceholder,
                  ),
                ),
              );
            }).toList(),
          ),
      ],
    );
  }

  Widget _buildComplianceSection(ExpenseModel expense) {
    final checks = ['发票信息与报销一致', '发票金额与报销金额一致', '发票日期在有效期内', '发票抬头为公司全称'];

    return FormSection(
      title: '发票合规检查',
      children: checks.map((text) {
        return Container(
          height: 44,
          child: Row(
            children: [
              Icon(Icons.check_circle, size: 16, color: AppColors.success),
              const SizedBox(width: 8),
              Text(
                text,
                style: const TextStyle(
                  fontSize: AppFontSizes.body,
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  Widget _buildApprovalSection(ExpenseModel expense) {
    return FormSection(
      title: '审批流程',
      children: [
        ApprovalTimeline(
          records: expense.approvalRecords,
          chain: expense.approvalChain,
          currentApproverId: expense.currentApproverId,
        ),
      ],
    );
  }

  Widget _buildArchiveSection(ExpenseModel expense) {
    return FormSection(
      title: '财务归档',
      children: [
        FormFieldRow(
          label: '凭证号',
          value: expense.voucherNo.isNotEmpty ? expense.voucherNo : null,
          hint: '-',
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '归档日期',
          value: du.DateUtils.formatDate(expense.updateTime),
          readOnly: true,
          showArrow: false,
        ),
        FormFieldRow(
          label: '归档人',
          value: '财务部',
          readOnly: true,
          showArrow: false,
        ),
      ],
    );
  }

  Widget _buildBottomBar(BuildContext context, ExpenseModel expense) {
    final canWithdraw =
        expense.status == 'pending' || expense.status == 'draft';

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

    return ActionBar(
      showLeft: false,
      centerLabel: '撤回申请',
      rightLabel: '提交审批',
      onCenterTap: () {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(const SnackBar(content: Text('已撤回')));
        context.pop();
      },
      onRightTap: null,
    );
  }
}
