import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '../../../core/i18n/app_localizations.dart';
import '../../../core/theme/app_colors_extension.dart';
import '../overtime_apply_model.dart';

/// 查看加班明细弹窗（只读）。
class OvertimeApplyDetailViewDialog extends StatelessWidget {
  final OvertimeApplyDetailModel detail;
  final AppLocalizations l10n;

  const OvertimeApplyDetailViewDialog({
    super.key,
    required this.detail,
    required this.l10n,
  });

  static void show(BuildContext context, OvertimeApplyDetailModel detail) {
    final l10n = AppLocalizations.of(context);
    FocusScope.of(context).unfocus();
    Navigator.push(
      context,
      TDSlidePopupRoute<void>(
        slideTransitionFrom: SlideTransitionFrom.bottom,
        isDismissible: true,
        builder: (_) =>
            OvertimeApplyDetailViewDialog(detail: detail, l10n: l10n),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final colors = Theme.of(context).extension<AppColorsExtension>()!;
    final d = detail;

    final empLabel = d.salName.isNotEmpty
        ? '${d.salNo}/${d.salName}'
        : d.salNo;

    final deptLabel = d.depName.isNotEmpty
        ? '${d.dep}/${d.depName}'
        : (d.dep.isNotEmpty ? d.dep : '-');

    return ConstrainedBox(
      constraints: BoxConstraints(
        maxHeight: MediaQuery.of(context).size.height * 0.8,
      ),
      child: Container(
        decoration: BoxDecoration(
          color: colors.bgCard,
          borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: SafeArea(
          top: false,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题栏
              Padding(
                padding: const EdgeInsets.fromLTRB(20, 20, 12, 8),
                child: Row(
                  children: [
                    const SizedBox(width: 24),
                    Expanded(
                      child: Center(
                        child: Text(
                          l10n.get('overtimeDetails'),
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                    GestureDetector(
                      onTap: () => Navigator.pop(context),
                      child: Icon(Icons.close, color: colors.textSecondary),
                    ),
                  ],
                ),
              ),
              // 内容
              Flexible(
                child: SingleChildScrollView(
                  padding: const EdgeInsets.all(20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _row(l10n.get('employee'), empLabel, colors),
                      _row(l10n.get('dep'), deptLabel, colors),
                      _row(l10n.get('jbType'), _jbTypeLabel(d.jbType), colors),
                      if (d.jbDate != null)
                        _row(l10n.get('applyDate'),
                            _formatDate(d.jbDate!), colors),
                      if (d.startTime != null)
                        _rowWithTag(
                          context,
                          l10n.get('startTime'),
                          _formatDateTime(d.startTime!),
                          _dayOfWeekFromDate(d.startTime!),
                          colors,
                        ),
                      if (d.endTime != null)
                        _rowWithTag(
                          context,
                          l10n.get('endTime'),
                          _formatDateTime(d.endTime!),
                          _dayOfWeekFromDate(d.endTime!),
                          colors,
                        ),
                      _row(l10n.get('overtimeHours'),
                          '${d.jbHours.toStringAsFixed(1)}${l10n.get('hours')}', colors,
                          valueColor: colors.timePrimary),
                      _row(l10n.get('overtimeDays'),
                          d.jbDays.toStringAsFixed(1), colors),
                      if (d.attPeriod.isNotEmpty)
                        _row(l10n.get('attPeriod'), d.attPeriod, colors),
                      if (d.reason.isNotEmpty)
                        _row(l10n.get('overtimeDetailReason'), d.reason, colors),
                      if (d.compensationType.isNotEmpty)
                        _row(l10n.get('compensationType'),
                            _compensationTypeLabel(d.compensationType), colors),
                      if (d.compensationType != 'NO_COMPENSATION' &&
                          d.compensationCount > 0)
                        _row(l10n.get('compensationCount'),
                            d.compensationCount.toStringAsFixed(1), colors),
                      if (d.adr.isNotEmpty)
                        _row(l10n.get('adr'), d.adr, colors),
                      if (d.rem.isNotEmpty)
                        _row(l10n.get('remark'), d.rem, colors),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _row(String label, String value, AppColorsExtension colors,
      {Color? valueColor}) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14,
                color: colors.textSecondary,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14,
                color: valueColor ?? colors.textPrimary,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _rowWithTag(
    BuildContext context,
    String label,
    String value,
    String tag,
    AppColorsExtension colors,
  ) {
    final tdTheme = TDTheme.of(context);
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 100,
            child: Text(
              label,
              style: TextStyle(
                fontSize: 14,
                color: colors.textSecondary,
              ),
            ),
          ),
          Expanded(
            child: Wrap(
              crossAxisAlignment: WrapCrossAlignment.center,
              spacing: 6,
              children: [
                Text(
                  value,
                  style: TextStyle(
                    fontSize: 14,
                    color: colors.textPrimary,
                  ),
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 6),
                  decoration: BoxDecoration(
                    color: tdTheme.brandColor1,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: TDText(
                    tag,
                    font: tdTheme.fontBodySmall,
                    fontWeight: FontWeight.w500,
                    textColor: tdTheme.brandColor7,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime d) {
    return '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')}';
  }

  String _formatDateTime(DateTime d) {
    return '${d.year}-${d.month.toString().padLeft(2, '0')}-${d.day.toString().padLeft(2, '0')} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
  }

  String _jbTypeLabel(String type) {
    switch (type) {
      case 'WORKING_DAY':
        return l10n.get('workingDay');
      case 'REST_DAY':
        return l10n.get('restDay');
      case 'PUBLIC_HOLIDAY':
        return l10n.get('publicHoliday');
      case 'SPECIAL_HOLIDAY':
        return l10n.get('specialHoliday');
      case 'OTHER':
        return l10n.get('other');
      default:
        return type;
    }
  }

  String _compensationTypeLabel(String type) {
    switch (type) {
      case 'OVERTIME_PAY':
        return l10n.get('overtimePay');
      case 'COMPENSATORY_LEAVE':
        return l10n.get('compensatoryLeave');
      case 'NO_COMPENSATION':
        return l10n.get('noCompensation');
      case 'OTHER':
        return l10n.get('other');
      default:
        return type;
    }
  }

  String _dayOfWeekFromDate(DateTime dt) {
    switch (dt.weekday) {
      case 1:
        return l10n.get('monday');
      case 2:
        return l10n.get('tuesday');
      case 3:
        return l10n.get('wednesday');
      case 4:
        return l10n.get('thursday');
      case 5:
        return l10n.get('friday');
      case 6:
        return l10n.get('saturday');
      case 7:
        return l10n.get('sunday');
      default:
        return '';
    }
  }
}
