import 'dart:async';

import 'package:flutter/material.dart';
import 'package:intl/intl.dart' as intl;
import 'package:lucide_icons_flutter/lucide_icons.dart' as lucide;
import 'package:shadcn_ui/shadcn_ui.dart';

import '../../../../widgets/components/feedback.dart';
import '../../../../widgets/components/superport_dialog.dart';
import '../../../../widgets/components/superport_detail_dialog.dart';
import '../../domain/entities/approval.dart';
import '../../domain/entities/approval_template.dart';
import '../../presentation/controllers/approval_controller.dart';

/// 결재 상세 다이얼로그를 표시한다.
///
/// 선택된 결재의 개요, 단계, 이력을 SuperportDetailDialog 패턴으로 노출하며
/// 단계 행위와 템플릿 적용을 동일 팝업 안에서 수행한다.
Future<void> showApprovalDetailDialog({
  required BuildContext context,
  required ApprovalController controller,
  required intl.DateFormat dateFormat,
  required bool canPerformStepActions,
  required bool canApplyTemplate,
}) {
  return showSuperportDialog<void>(
    context: context,
    title: '결재 상세',
    actions: const [],
    headerActions: [
      ShadButton.ghost(
        key: const ValueKey('approval_detail_refresh'),
        onPressed: controller.isLoadingDetail
            ? null
            : () async {
                final selected = controller.selected;
                if (selected?.id == null) {
                  SuperportToast.warning(context, '상세 조회 대상이 없습니다.');
                  return;
                }
                await controller.selectApproval(selected!.id!);
                final error = controller.errorMessage;
                if (error != null && context.mounted) {
                  SuperportToast.error(context, error);
                  controller.clearError();
                  return;
                }
                if (context.mounted) {
                  SuperportToast.success(context, '결재 상세를 새로고침했습니다.');
                }
              },
        child: const Icon(lucide.LucideIcons.refreshCw, size: 16),
      ),
    ],
    body: ApprovalDetailDialogView(
      controller: controller,
      dateFormat: dateFormat,
      canPerformStepActions: canPerformStepActions,
      canApplyTemplate: canApplyTemplate,
    ),
    constraints: const BoxConstraints(maxWidth: 880),
    barrierDismissible: true,
  );
}

class ApprovalDetailDialogView extends StatefulWidget {
  const ApprovalDetailDialogView({
    super.key,
    required this.controller,
    required this.dateFormat,
    required this.canPerformStepActions,
    required this.canApplyTemplate,
  });

  final ApprovalController controller;
  final intl.DateFormat dateFormat;
  final bool canPerformStepActions;
  final bool canApplyTemplate;

  @override
  State<ApprovalDetailDialogView> createState() =>
      _ApprovalDetailDialogViewState();
}

class _ApprovalDetailDialogViewState extends State<ApprovalDetailDialogView> {
  int? _selectedTemplateId;

  @override
  void initState() {
    super.initState();
    _initializeTemplateSelection();
  }

  @override
  void didUpdateWidget(covariant ApprovalDetailDialogView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.controller != widget.controller) {
      _initializeTemplateSelection();
    }
  }

  void _initializeTemplateSelection() {
    final templates = widget.controller.templates;
    if (templates.isEmpty) {
      setState(() => _selectedTemplateId = null);
      return;
    }
    final current = _selectedTemplateId;
    if (current != null &&
        templates.any((template) => template.id == current)) {
      return;
    }
    setState(() => _selectedTemplateId = templates.first.id);
  }

  void _ensureTemplateSelectionValid(List<ApprovalTemplate> templates) {
    if (templates.isEmpty) {
      if (_selectedTemplateId != null) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (!mounted) return;
          setState(() => _selectedTemplateId = null);
        });
      }
      return;
    }
    if (_selectedTemplateId == null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        setState(() => _selectedTemplateId = templates.first.id);
      });
      return;
    }
    final exists = templates.any(
      (template) => template.id == _selectedTemplateId,
    );
    if (!exists) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (!mounted) return;
        setState(() => _selectedTemplateId = templates.first.id);
      });
    }
  }

  Future<void> _handleApplyTemplate(int templateId) async {
    final success = await widget.controller.applyTemplate(templateId);
    if (!mounted) {
      return;
    }
    final error = widget.controller.errorMessage;
    if (error != null) {
      SuperportToast.error(context, error);
      widget.controller.clearError();
      return;
    }
    if (success) {
      SuperportToast.success(context, '결재 템플릿을 적용했습니다.');
    }
  }

  Future<void> _handleStepAction(
    ApprovalStep step,
    ApprovalStepActionType type,
  ) async {
    final result = await _showActionConfirmDialog(step, type);
    if (result == null) {
      return;
    }
    final success = await widget.controller.performStepAction(
      step: step,
      type: type,
      note: result,
    );
    if (!mounted) {
      return;
    }
    final error = widget.controller.errorMessage;
    if (error != null) {
      SuperportToast.error(context, error);
      widget.controller.clearError();
      return;
    }
    if (success) {
      SuperportToast.success(context, _successMessage(type));
    }
  }

  Future<String?> _showActionConfirmDialog(
    ApprovalStep step,
    ApprovalStepActionType type,
  ) async {
    final requireNote = type == ApprovalStepActionType.comment;
    final noteController = TextEditingController();
    String? errorText;
    final confirmed = await showSuperportDialog<String?>(
      context: context,
      title: _dialogTitle(type),
      constraints: const BoxConstraints(maxWidth: 420),
      onSubmit: () {
        final note = noteController.text.trim();
        if (requireNote && note.isEmpty) {
          errorText = '비고를 입력하세요.';
          return;
        }
        Navigator.of(
          context,
          rootNavigator: true,
        ).maybePop(note.isEmpty ? null : note);
      },
      body: StatefulBuilder(
        builder: (dialogContext, setState) {
          final theme = ShadTheme.of(dialogContext);
          final materialTheme = Theme.of(dialogContext);
          return Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '선택 단계: Step ${step.stepOrder}',
                style: theme.textTheme.small,
              ),
              const SizedBox(height: 4),
              Text('승인자: ${step.approver.name}', style: theme.textTheme.small),
              const SizedBox(height: 4),
              Text('현재 상태: ${step.status.name}', style: theme.textTheme.small),
              const SizedBox(height: 12),
              Text(_dialogDescription(type), style: theme.textTheme.muted),
              const SizedBox(height: 12),
              Text('비고', style: theme.textTheme.small),
              const SizedBox(height: 8),
              ShadTextarea(
                controller: noteController,
                minHeight: 120,
                maxHeight: 220,
              ),
              if (requireNote)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    '코멘트에는 비고 입력이 필요합니다.',
                    style: theme.textTheme.muted,
                  ),
                ),
              if (errorText != null)
                Padding(
                  padding: const EdgeInsets.only(top: 8),
                  child: Text(
                    errorText!,
                    style: theme.textTheme.small.copyWith(
                      color: materialTheme.colorScheme.error,
                    ),
                  ),
                ),
            ],
          );
        },
      ),
      actions: [
        ShadButton.ghost(
          onPressed: () =>
              Navigator.of(context, rootNavigator: true).maybePop(),
          child: const Text('취소'),
        ),
        ShadButton(
          onPressed: () {
            final note = noteController.text.trim();
            if (requireNote && note.isEmpty) {
              errorText = '비고를 입력하세요.';
              return;
            }
            Navigator.of(
              context,
              rootNavigator: true,
            ).maybePop(note.isEmpty ? null : note);
          },
          child: Text(_dialogConfirmLabel(type)),
        ),
      ],
    );
    return confirmed;
  }

  List<Widget> _buildSummaryBadges(Approval approval) {
    final badges = <Widget>[ShadBadge(child: Text(approval.status.name))];
    badges.add(
      approval.isActive
          ? const ShadBadge.outline(child: Text('사용중'))
          : const ShadBadge.outline(child: Text('비활성')),
    );
    if (approval.isDeleted) {
      badges.add(const ShadBadge.destructive(child: Text('삭제됨')));
    }
    return badges;
  }

  List<SuperportDetailMetadata> _buildMetadata({
    required Approval approval,
    required bool canProceed,
    required String? cannotProceedReason,
  }) {
    final metadata = <SuperportDetailMetadata>[
      if (approval.id != null)
        SuperportDetailMetadata.text(label: 'ID', value: '${approval.id}'),
      SuperportDetailMetadata.text(label: '결재번호', value: approval.approvalNo),
      SuperportDetailMetadata.text(
        label: '트랜잭션번호',
        value: approval.transactionNo,
      ),
      SuperportDetailMetadata.text(
        label: '현재 단계',
        value: _formatCurrentStep(approval),
      ),
      SuperportDetailMetadata.text(
        label: '상신자',
        value: '${approval.requester.name} (${approval.requester.employeeNo})',
      ),
      SuperportDetailMetadata.text(
        label: '상신일시',
        value: widget.dateFormat.format(approval.requestedAt.toLocal()),
      ),
      SuperportDetailMetadata.text(
        label: '최종결정일시',
        value: _formatDate(approval.decidedAt),
      ),
      SuperportDetailMetadata.text(
        label: '트랜잭션 갱신일시',
        value: _formatDate(approval.transactionUpdatedAt),
      ),
      SuperportDetailMetadata.text(
        label: '사용 상태',
        value: approval.isActive ? '사용중' : '비활성',
      ),
      SuperportDetailMetadata.text(
        label: '삭제 여부',
        value: approval.isDeleted ? '삭제됨' : '정상',
      ),
      SuperportDetailMetadata.text(
        label: '비고',
        value: approval.note?.trim().isEmpty ?? true
            ? '-'
            : approval.note!.trim(),
      ),
      if (!canProceed && cannotProceedReason != null)
        SuperportDetailMetadata.text(
          label: '진행 제한 사유',
          value: cannotProceedReason,
        ),
    ];
    return metadata;
  }

  String _formatCurrentStep(Approval approval) {
    final step = approval.currentStep;
    if (step == null) {
      return '-';
    }
    return 'Step ${step.stepOrder} · ${step.approver.name}';
  }

  String _formatDate(DateTime? value) {
    if (value == null) {
      return '-';
    }
    return widget.dateFormat.format(value.toLocal());
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: widget.controller,
      builder: (context, _) {
        final approval = widget.controller.selected;
        final isLoading = widget.controller.isLoadingDetail;
        final templates = widget.controller.templates;
        final isLoadingTemplates = widget.controller.isLoadingTemplates;
        final isApplyingTemplate = widget.controller.isApplyingTemplate;
        final applyingTemplateId = widget.controller.applyingTemplateId;
        final hasActionOptions = widget.controller.hasActionOptions;
        final isLoadingActions = widget.controller.isLoadingActions;
        final isPerformingAction = widget.controller.isPerformingAction;
        final processingStepId = widget.controller.processingStepId;
        final canProceed = widget.controller.canProceedSelected;
        final cannotProceedReason = widget.controller.cannotProceedReason;
        _ensureTemplateSelectionValid(templates);

        final theme = ShadTheme.of(context);
        if (isLoading) {
          return const Center(child: CircularProgressIndicator());
        }
        if (approval == null) {
          return Center(
            child: Text('선택된 결재 정보가 없습니다.', style: theme.textTheme.muted),
          );
        }

        final summary = Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('결재번호 ${approval.approvalNo}', style: theme.textTheme.h4),
            const SizedBox(height: 4),
            Text(
              '트랜잭션 ${approval.transactionNo}',
              style: theme.textTheme.muted,
            ),
          ],
        );
        final summaryBadges = _buildSummaryBadges(approval);
        final metadata = _buildMetadata(
          approval: approval,
          canProceed: canProceed,
          cannotProceedReason: cannotProceedReason,
        );

        final sections = [
          SuperportDetailDialogSection(
            key: const ValueKey('approval_detail_tab_steps'),
            id: 'steps',
            label: '단계',
            icon: lucide.LucideIcons.listChecks,
            builder: (_) => _ApprovalStepSection(
              approval: approval,
              dateFormat: widget.dateFormat,
              templates: templates,
              isLoadingTemplates: isLoadingTemplates,
              isApplyingTemplate: isApplyingTemplate,
              applyingTemplateId: applyingTemplateId,
              selectedTemplateId: _selectedTemplateId,
              canApplyTemplate: widget.canApplyTemplate,
              canPerformStepActions: widget.canPerformStepActions,
              hasActionOptions: hasActionOptions,
              isLoadingActions: isLoadingActions,
              isPerformingAction: isPerformingAction,
              processingStepId: processingStepId,
              canProceed: canProceed,
              cannotProceedReason: cannotProceedReason,
              onSelectTemplate: (id) => setState(() {
                _selectedTemplateId = id;
              }),
              onApplyTemplate: _handleApplyTemplate,
              onReloadTemplates: () =>
                  widget.controller.loadTemplates(force: true),
              onAction: _handleStepAction,
            ),
          ),
          SuperportDetailDialogSection(
            id: 'histories',
            label: '이력',
            icon: lucide.LucideIcons.history,
            builder: (_) => _ApprovalHistorySection(
              histories: approval.histories,
              dateFormat: widget.dateFormat,
            ),
          ),
        ];

        return SuperportDetailDialog(
          sections: sections,
          summary: summary,
          summaryBadges: summaryBadges,
          metadata: metadata,
          initialSectionId: 'steps',
          emptyPlaceholder: Text(
            '표시할 결재 상세 정보가 없습니다.',
            style: theme.textTheme.muted,
          ),
        );
      },
    );
  }
}

class _ApprovalStepSection extends StatelessWidget {
  const _ApprovalStepSection({
    required this.approval,
    required this.dateFormat,
    required this.templates,
    required this.isLoadingTemplates,
    required this.isApplyingTemplate,
    required this.applyingTemplateId,
    required this.selectedTemplateId,
    required this.canApplyTemplate,
    required this.canPerformStepActions,
    required this.hasActionOptions,
    required this.isLoadingActions,
    required this.isPerformingAction,
    required this.processingStepId,
    required this.canProceed,
    required this.cannotProceedReason,
    required this.onSelectTemplate,
    required this.onApplyTemplate,
    required this.onReloadTemplates,
    required this.onAction,
  });

  final Approval approval;
  final intl.DateFormat dateFormat;
  final List<ApprovalTemplate> templates;
  final bool isLoadingTemplates;
  final bool isApplyingTemplate;
  final int? applyingTemplateId;
  final int? selectedTemplateId;
  final bool canApplyTemplate;
  final bool canPerformStepActions;
  final bool hasActionOptions;
  final bool isLoadingActions;
  final bool isPerformingAction;
  final int? processingStepId;
  final bool canProceed;
  final String? cannotProceedReason;
  final void Function(int?) onSelectTemplate;
  final Future<void> Function(int templateId) onApplyTemplate;
  final Future<void> Function() onReloadTemplates;
  final Future<void> Function(ApprovalStep step, ApprovalStepActionType type)
  onAction;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        _TemplateToolbar(
          templates: templates,
          isLoading: isLoadingTemplates,
          selectedTemplateId: selectedTemplateId,
          isApplyingTemplate: isApplyingTemplate,
          applyingTemplateId: applyingTemplateId,
          canApplyTemplate: canApplyTemplate,
          onSelectTemplate: onSelectTemplate,
          onApplyTemplate: (templateId) async {
            await onApplyTemplate(templateId);
          },
          onReload: onReloadTemplates,
        ),
        const SizedBox(height: 18),
        if (approval.steps.isEmpty)
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: theme.colorScheme.secondary.withValues(alpha: 0.05),
              border: Border.all(color: theme.colorScheme.border),
            ),
            child: Text('등록된 결재 단계가 없습니다.', style: theme.textTheme.muted),
          )
        else
          for (var index = 0; index < approval.steps.length; index++) ...[
            if (index > 0) const SizedBox(height: 12),
            Builder(
              builder: (context) {
                final step = approval.steps[index];
                final isProcessing =
                    isPerformingAction &&
                    processingStepId != null &&
                    processingStepId == step.id;
                final disabledReason = _disabledReason(
                  step,
                  canPerformStepActions,
                  canProceed,
                  cannotProceedReason,
                );
                final enabled = disabledReason == null;
                return ShadCard(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              'Step ${step.stepOrder}',
                              style: theme.textTheme.small.copyWith(
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            ShadBadge(child: Text(step.status.name)),
                          ],
                        ),
                        const SizedBox(height: 12),
                        _KeyValueRow(
                          label: '승인자',
                          value:
                              '${step.approver.name} (${step.approver.employeeNo})',
                        ),
                        _KeyValueRow(
                          label: '배정일시',
                          value: dateFormat.format(step.assignedAt.toLocal()),
                        ),
                        _KeyValueRow(
                          label: '결정일시',
                          value: step.decidedAt == null
                              ? '-'
                              : dateFormat.format(step.decidedAt!.toLocal()),
                        ),
                        if (step.note?.trim().isNotEmpty ?? false)
                          _KeyValueRow(label: '비고', value: step.note!.trim()),
                        const SizedBox(height: 12),
                        Wrap(
                          spacing: 12,
                          runSpacing: 8,
                          children: ApprovalStepActionType.values
                              .map(
                                (type) => _buildActionButton(
                                  context: context,
                                  step: step,
                                  type: type,
                                  enabled: enabled,
                                  isProcessing: isProcessing,
                                  disabledReason: disabledReason,
                                  hasActionOptions: hasActionOptions,
                                  isLoadingActions: isLoadingActions,
                                ),
                              )
                              .toList(),
                        ),
                        if (disabledReason != null)
                          Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(
                              disabledReason,
                              style: theme.textTheme.muted,
                            ),
                          ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ],
        const SizedBox(height: 12),
      ],
    );
  }

  Widget _buildActionButton({
    required BuildContext context,
    required ApprovalStep step,
    required ApprovalStepActionType type,
    required bool enabled,
    required bool isProcessing,
    required String? disabledReason,
    required bool hasActionOptions,
    required bool isLoadingActions,
  }) {
    final theme = ShadTheme.of(context);
    final label = _actionLabel(type);
    final icon = _actionIcon(type);
    final buttonKey = ValueKey<String>(
      'step_action_${step.id ?? step.stepOrder}_${type.name}',
    );
    final child = Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        if (isProcessing) ...[
          SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(
                theme.colorScheme.primary,
              ),
            ),
          ),
          const SizedBox(width: 8),
          Text('$label 처리 중...'),
        ] else ...[
          Icon(icon, size: 16),
          const SizedBox(width: 8),
          Text(label),
        ],
      ],
    );
    final effectiveReason =
        disabledReason ??
        (!hasActionOptions
            ? '사용 가능한 결재 행위가 없습니다.'
            : (isLoadingActions ? '행위를 불러오는 중입니다.' : null));
    final action = enabled ? () => onAction(step, type) : null;

    Widget button;
    switch (type) {
      case ApprovalStepActionType.approve:
        button = ShadButton(key: buttonKey, onPressed: action, child: child);
        break;
      case ApprovalStepActionType.reject:
        button = ShadButton.outline(
          key: buttonKey,
          onPressed: action,
          child: child,
        );
        break;
      case ApprovalStepActionType.comment:
        button = ShadButton.ghost(
          key: buttonKey,
          onPressed: action,
          child: child,
        );
        break;
    }

    if (effectiveReason != null && action == null) {
      return Tooltip(message: effectiveReason, child: button);
    }
    return button;
  }

  String? _disabledReason(
    ApprovalStep step,
    bool canPerform,
    bool canProceed,
    String? cannotProceedReason,
  ) {
    if (!canPerform) {
      return '결재 권한이 없어 단계 행위를 실행할 수 없습니다.';
    }
    if (!canProceed) {
      return cannotProceedReason ?? '현재는 결재 단계를 진행할 수 없습니다.';
    }
    if (step.id == null) {
      return '단계 ID가 없어 행위를 수행할 수 없습니다.';
    }
    return null;
  }

  IconData _actionIcon(ApprovalStepActionType type) {
    switch (type) {
      case ApprovalStepActionType.approve:
        return lucide.LucideIcons.check;
      case ApprovalStepActionType.reject:
        return lucide.LucideIcons.x;
      case ApprovalStepActionType.comment:
        return lucide.LucideIcons.messageCircle;
    }
  }

  String _actionLabel(ApprovalStepActionType type) {
    switch (type) {
      case ApprovalStepActionType.approve:
        return '승인';
      case ApprovalStepActionType.reject:
        return '반려';
      case ApprovalStepActionType.comment:
        return '코멘트';
    }
  }
}

class _ApprovalHistorySection extends StatelessWidget {
  const _ApprovalHistorySection({
    required this.histories,
    required this.dateFormat,
  });

  final List<ApprovalHistory> histories;
  final intl.DateFormat dateFormat;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    if (histories.isEmpty) {
      return Center(child: Text('결재 이력이 없습니다.', style: theme.textTheme.muted));
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        for (var index = 0; index < histories.length; index++) ...[
          if (index > 0) const SizedBox(height: 16),
          Builder(
            builder: (_) {
              final history = histories[index];
              return ShadCard(
                child: Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            history.toStatus.name,
                            style: theme.textTheme.small.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                          Text(
                            dateFormat.format(history.actionAt.toLocal()),
                            style: theme.textTheme.muted,
                          ),
                        ],
                      ),
                      const SizedBox(height: 8),
                      Text(history.approver.name, style: theme.textTheme.small),
                      const SizedBox(height: 4),
                      Text(history.action.name, style: theme.textTheme.muted),
                      if (history.note?.trim().isNotEmpty ?? false) ...[
                        const SizedBox(height: 8),
                        Text(
                          history.note!.trim(),
                          style: theme.textTheme.small,
                        ),
                      ],
                    ],
                  ),
                ),
              );
            },
          ),
        ],
      ],
    );
  }
}

class _TemplateToolbar extends StatelessWidget {
  const _TemplateToolbar({
    required this.templates,
    required this.isLoading,
    required this.selectedTemplateId,
    required this.isApplyingTemplate,
    required this.applyingTemplateId,
    required this.canApplyTemplate,
    required this.onSelectTemplate,
    required this.onApplyTemplate,
    required this.onReload,
  });

  final List<ApprovalTemplate> templates;
  final bool isLoading;
  final int? selectedTemplateId;
  final bool isApplyingTemplate;
  final int? applyingTemplateId;
  final bool canApplyTemplate;
  final void Function(int?) onSelectTemplate;
  final Future<void> Function(int templateId) onApplyTemplate;
  final Future<void> Function() onReload;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    ApprovalTemplate? selectedTemplate;
    if (selectedTemplateId != null) {
      for (final template in templates) {
        if (template.id == selectedTemplateId) {
          selectedTemplate = template;
          break;
        }
      }
    }
    selectedTemplate ??= templates.isEmpty ? null : templates.first;

    Widget applyButton = ShadButton(
      key: const ValueKey('approval_apply_template_button'),
      onPressed:
          !canApplyTemplate || selectedTemplateId == null || isApplyingTemplate
          ? null
          : () => onApplyTemplate(selectedTemplateId!),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (isApplyingTemplate && applyingTemplateId == selectedTemplateId)
            const SizedBox(
              width: 16,
              height: 16,
              child: CircularProgressIndicator(strokeWidth: 2),
            )
          else
            const Icon(lucide.LucideIcons.layoutList, size: 16),
          const SizedBox(width: 8),
          Text(
            isApplyingTemplate && applyingTemplateId == selectedTemplateId
                ? '적용 중...'
                : '템플릿 적용',
          ),
        ],
      ),
    );

    if (!canApplyTemplate) {
      applyButton = Tooltip(message: '템플릿을 적용할 권한이 없습니다.', child: applyButton);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Expanded(
              child: ShadSelect<int>(
                key: ValueKey<int?>(selectedTemplateId),
                placeholder: const Text('템플릿 선택'),
                initialValue: selectedTemplateId,
                onChanged: canApplyTemplate ? onSelectTemplate : null,
                selectedOptionBuilder: (context, value) {
                  if (templates.isEmpty) {
                    return const Text('템플릿 선택');
                  }
                  final match = templates.firstWhere(
                    (template) => template.id == value,
                    orElse: () => templates.first,
                  );
                  return Text(match.name);
                },
                options: templates
                    .map(
                      (template) => ShadOption<int>(
                        value: template.id,
                        child: Text(template.name),
                      ),
                    )
                    .toList(),
              ),
            ),
            const SizedBox(width: 12),
            ShadButton.outline(
              onPressed: isLoading ? null : () => onReload(),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: const [
                  Icon(lucide.LucideIcons.refreshCw, size: 16),
                  SizedBox(width: 6),
                  Text('새로고침'),
                ],
              ),
            ),
            const SizedBox(width: 12),
            applyButton,
          ],
        ),
        if (isLoading)
          Padding(
            padding: const EdgeInsets.only(top: 8),
            child: Row(
              children: [
                const SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(strokeWidth: 2),
                ),
                const SizedBox(width: 8),
                Text('템플릿을 불러오는 중입니다.', style: theme.textTheme.small),
              ],
            ),
          )
        else if (selectedTemplate != null)
          Padding(
            padding: const EdgeInsets.only(top: 8),
            child: Text(
              _templateSummary(selectedTemplate),
              style: theme.textTheme.small,
            ),
          ),
      ],
    );
  }

  String _templateSummary(ApprovalTemplate template) {
    final stepCount = template.steps.length;
    final description = template.description?.trim();
    final buffer = StringBuffer()
      ..write('선택된 템플릿: ${template.name} (단계 $stepCount개)');
    if (description != null && description.isNotEmpty) {
      buffer.write(' · $description');
    }
    return buffer.toString();
  }
}

class _KeyValueRow extends StatelessWidget {
  const _KeyValueRow({required this.label, required this.value});

  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 120,
            child: Text(
              label,
              style: theme.textTheme.small.copyWith(
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          Expanded(child: Text(value, style: theme.textTheme.small)),
        ],
      ),
    );
  }
}

String _dialogTitle(ApprovalStepActionType type) {
  switch (type) {
    case ApprovalStepActionType.approve:
      return '결재 승인';
    case ApprovalStepActionType.reject:
      return '결재 반려';
    case ApprovalStepActionType.comment:
      return '코멘트 작성';
  }
}

String _dialogDescription(ApprovalStepActionType type) {
  switch (type) {
    case ApprovalStepActionType.approve:
      return '해당 단계를 승인하면 다음 결재 단계로 진행합니다.';
    case ApprovalStepActionType.reject:
      return '단계를 반려하면 결재가 반려 상태로 전환됩니다.';
    case ApprovalStepActionType.comment:
      return '승인자에게 전달할 의견을 작성합니다.';
  }
}

String _dialogConfirmLabel(ApprovalStepActionType type) {
  switch (type) {
    case ApprovalStepActionType.approve:
      return '승인';
    case ApprovalStepActionType.reject:
      return '반려';
    case ApprovalStepActionType.comment:
      return '등록';
  }
}

String _successMessage(ApprovalStepActionType type) {
  switch (type) {
    case ApprovalStepActionType.approve:
      return '단계를 승인했습니다.';
    case ApprovalStepActionType.reject:
      return '단계를 반려했습니다.';
    case ApprovalStepActionType.comment:
      return '코멘트를 등록했습니다.';
  }
}
