import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/utils/date_utils.dart' as du;
import '../../shared/widgets/status_banner.dart';
import '../../shared/widgets/approval_timeline.dart';
import 'overtime_model.dart';
import '../../core/i18n/app_localizations.dart';
import 'overtime_list_controller.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_colors_extension.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final overtime = mockOvertimes.firstWhere(
      (e) => e.id == id,
      orElse: () => mockOvertimes.first,
    );
    final l10n = AppLocalizations.of(context);
    final (icon, color, statusText) = _statusProps(
      overtime.status,
      l10n,
      colors,
    );

    return Column(
      children: [
        Expanded(
          child: SingleChildScrollView(
            padding: const EdgeInsets.fromLTRB(16, 16, 16, 32),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                StatusBanner(
                  icon: icon,
                  statusText: statusText,
                  subText: _statusSubText(overtime, l10n),
                  color: color,
                ),
                const SizedBox(height: 8),
                Text(
                  '${l10n.get('submitTimeText')}：${du.DateUtils.formatDateTime(overtime.createTime)}',
                  style: TextStyle(
                    fontSize: AppFontSizes.caption,
                    color: colors.textPlaceholder,
                  ),
                ),
                const SizedBox(height: 16),
                _buildInfoSection(overtime, l10n, colors),
                const SizedBox(height: 16),
                _buildReasonSection(overtime, l10n, colors),
                const SizedBox(height: 16),
                if (overtime.approvalRecords.isNotEmpty ||
                    overtime.approvalChain.isNotEmpty)
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: colors.bgCard,
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: ApprovalTimeline(
                      records: overtime.approvalRecords,
                      chain: overtime.approvalChain,
                      currentApproverId: overtime.currentApproverId,
                    ),
                  ),
              ],
            ),
          ),
        ),
        _buildActionBar(context, overtime),
      ],
    );
  }

  Widget _buildInfoSection(
    OvertimeModel overtime,
    AppLocalizations l10n,
    AppColorsExtension colors,
  ) {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
      decoration: BoxDecoration(
        color: colors.bgCard,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          _infoRow(l10n.get('applicant'), overtime.applicantName, colors),
          _infoRow(l10n.get('department'), overtime.deptName, colors),
          _infoRow(l10n.get('overtimeType'), overtime.otType, colors),
          _infoRow(
            l10n.get('compensationMethod'),
            overtime.compensationType,
            colors,
          ),
          _infoRow(
            l10n.get('netOvertimeHours'),
            '${overtime.otHours.toStringAsFixed(1)}${l10n.get('hours')}',
            colors,
          ),
          _infoRow(
            l10n.get('startTime'),
            du.DateUtils.formatDateTime(overtime.startTime),
            colors,
          ),
          _infoRow(
            l10n.get('endTime'),
            du.DateUtils.formatDateTime(overtime.endTime),
            colors,
          ),
        ],
      ),
    );
  }

  Widget _infoRow(String label, String value, AppColorsExtension colors) {
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(vertical: 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            label,
            style: TextStyle(
              fontSize: AppFontSizes.body,
              color: colors.textSecondary,
            ),
          ),
          Text(
            value,
            style: TextStyle(
              fontSize: AppFontSizes.body,
              color: colors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildReasonSection(
    OvertimeModel overtime,
    AppLocalizations l10n,
    AppColorsExtension colors,
  ) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: colors.bgCard,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            l10n.get('overtimeReason'),
            style: TextStyle(
              fontSize: AppFontSizes.subtitle,
              fontWeight: FontWeight.w600,
              color: colors.textPrimary,
            ),
          ),
          const SizedBox(height: 8),
          Text(
            overtime.reason.isEmpty ? l10n.get('no') : overtime.reason,
            style: TextStyle(
              fontSize: AppFontSizes.body,
              color: colors.textPrimary,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionBar(BuildContext context, OvertimeModel overtime) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final l10n = AppLocalizations.of(context);
    final showWithdraw =
        overtime.status == 'pending' || overtime.status == 'draft';
    if (!showWithdraw) return const SizedBox.shrink();

    return Container(
      height: 72,
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      decoration: BoxDecoration(color: colors.bgCard),
      child: Row(
        children: [
          const Spacer(),
          SizedBox(
            height: 40,
            child: Material(
              color: colors.primary,
              borderRadius: BorderRadius.circular(22),
              child: InkWell(
                onTap: () {
                  // 撤回逻辑，保留接口
                },
                borderRadius: BorderRadius.circular(22),
                child: Center(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 32),
                    child: Text(
                      l10n.get('withdrawApplication'),
                      style: TextStyle(
                        fontSize: AppFontSizes.body,
                        fontWeight: FontWeight.w500,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
          const Spacer(),
        ],
      ),
    );
  }

  (IconData, Color, String) _statusProps(
    String status,
    AppLocalizations l10n,
    AppColorsExtension colors,
  ) {
    switch (status) {
      case 'approved':
        return (Icons.check_circle, colors.success, l10n.get('approved'));
      case 'rejected':
        return (Icons.cancel, colors.danger, l10n.get('rejected'));
      case 'draft':
        return (Icons.edit_note, colors.statusGray, l10n.get('draft'));
      case 'withdrawn':
        return (Icons.cancel_outlined, colors.withdrawnText, l10n.get('withdrawn'));
      default:
        return (Icons.access_time, colors.warning, l10n.get('pending'));
    }
  }

  String _statusSubText(OvertimeModel overtime, AppLocalizations l10n) {
    switch (overtime.status) {
      case 'pending':
        return overtime.currentApproverId.isNotEmpty
            ? '${l10n.get('currentApprover')}：${overtime.currentApproverId}'
            : l10n.get('waitHandle');
      case 'approved':
        final last = overtime.approvalRecords.isNotEmpty
            ? overtime.approvalRecords.last.approverName
            : '';
        return last.isNotEmpty
            ? '${l10n.get('approver')}：$last'
            : l10n.get('approved');
      case 'rejected':
        final last = overtime.approvalRecords.isNotEmpty
            ? overtime.approvalRecords.last.approverName
            : '';
        return last.isNotEmpty
            ? '${l10n.get('rejecter')}：$last'
            : l10n.get('rejected');
      default:
        return '';
    }
  }
}
