import 'dart:async';

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

import '../../../../../core/validation/password_rules.dart';
import '../../../../../widgets/components/superport_detail_dialog.dart';
import '../../../../../widgets/components/superport_dialog.dart';
import '../../../group/domain/entities/group.dart';
import '../../domain/entities/user.dart';

/// 사용자 상세 다이얼로그에서 발생 가능한 액션 종류이다.
enum UserDetailDialogAction {
  created,
  updated,
  deleted,
  restored,
  passwordReset,
}

/// 사용자 상세 다이얼로그가 반환하는 결과 모델이다.
class UserDetailDialogResult {
  const UserDetailDialogResult({
    required this.action,
    required this.message,
    this.user,
  });

  final UserDetailDialogAction action;
  final String message;

  /// 최신 사용자 엔티티. 삭제/비밀번호 초기화 시 null일 수 있다.
  final UserAccount? user;
}

typedef UserCreateCallback = Future<UserAccount?> Function(UserInput input);
typedef UserUpdateCallback =
    Future<UserAccount?> Function(int id, UserInput input);
typedef UserDeleteCallback = Future<bool> Function(int id);
typedef UserRestoreCallback = Future<UserAccount?> Function(int id);
typedef UserResetPasswordCallback = Future<UserAccount?> Function(int id);

/// 사용자 상세 다이얼로그를 노출한다.
Future<UserDetailDialogResult?> showUserDetailDialog({
  required BuildContext context,
  required intl.DateFormat dateFormat,
  required List<Group> groupOptions,
  UserAccount? user,
  required UserCreateCallback onCreate,
  required UserUpdateCallback onUpdate,
  required UserDeleteCallback onDelete,
  required UserRestoreCallback onRestore,
  required UserResetPasswordCallback onResetPassword,
}) {
  final isDetail = user != null;
  final detailUser = user;

  Future<UserDetailDialogResult?> handleCreate(UserInput input) async {
    final created = await onCreate(input);
    if (created == null) {
      return null;
    }
    return UserDetailDialogResult(
      action: UserDetailDialogAction.created,
      message: '사용자를 등록했습니다.',
      user: created,
    );
  }

  Future<UserDetailDialogResult?> handleUpdate(UserInput input) async {
    final userId = user!.id;
    if (userId == null) {
      return null;
    }
    final updated = await onUpdate(userId, input);
    if (updated == null) {
      return null;
    }
    return UserDetailDialogResult(
      action: UserDetailDialogAction.updated,
      message: '사용자를 수정했습니다.',
      user: updated,
    );
  }

  Future<UserDetailDialogResult?> handleDelete() async {
    final current = detailUser;
    final userId = current?.id;
    if (userId == null) {
      return null;
    }
    final success = await onDelete(userId);
    if (!success) {
      return null;
    }
    return const UserDetailDialogResult(
      action: UserDetailDialogAction.deleted,
      message: '사용자를 삭제했습니다.',
    );
  }

  Future<UserDetailDialogResult?> handleRestore() async {
    final current = detailUser;
    final userId = current?.id;
    if (userId == null) {
      return null;
    }
    final restored = await onRestore(userId);
    if (restored == null) {
      return null;
    }
    return UserDetailDialogResult(
      action: UserDetailDialogAction.restored,
      message: '사용자를 복구했습니다.',
      user: restored,
    );
  }

  Future<UserDetailDialogResult?> handleResetPassword() async {
    final current = detailUser;
    final userId = current?.id;
    if (userId == null) {
      return null;
    }
    final updated = await onResetPassword(userId);
    if (updated == null) {
      return null;
    }
    return const UserDetailDialogResult(
      action: UserDetailDialogAction.passwordReset,
      message: '임시 비밀번호를 이메일로 발송했습니다.',
    );
  }

  final sections = <SuperportDetailDialogSection>[
    if (isDetail && detailUser != null)
      SuperportDetailDialogSection(
        id: _UserDetailSections.overview,
        label: '상세',
        icon: LucideIcons.info,
        builder: (_) =>
            _UserOverviewSection(user: detailUser, dateFormat: dateFormat),
      ),
    if (isDetail)
      SuperportDetailDialogSection(
        id: _UserDetailSections.activity,
        label: '최근 활동',
        icon: LucideIcons.history,
        builder: (_) => const _UserActivitySection(),
      ),
    if (isDetail && detailUser != null)
      _UserSecuritySection(
        user: detailUser,
        dateFormat: dateFormat,
        onResetPassword: handleResetPassword,
      ),
    _UserFormSection(
      id: isDetail ? _UserDetailSections.edit : _UserDetailSections.create,
      label: isDetail ? '수정' : '등록',
      user: detailUser,
      groupOptions: groupOptions,
      onSubmit: isDetail ? handleUpdate : handleCreate,
    ),
    if (isDetail && detailUser != null)
      _UserDangerSection(
        user: detailUser,
        onDelete: handleDelete,
        onRestore: handleRestore,
      ),
  ];

  final summary = detailUser == null
      ? null
      : Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              detailUser.employeeName,
              style: ShadTheme.of(context).textTheme.h4,
            ),
            const SizedBox(height: 4),
            Text(
              '사번 ${detailUser.employeeNo}',
              style: ShadTheme.of(context).textTheme.muted,
            ),
          ],
        );

  final summaryBadges = detailUser == null
      ? const <Widget>[]
      : [
          if (detailUser.isActive)
            const ShadBadge(child: Text('사용중'))
          else
            const ShadBadge.outline(child: Text('미사용')),
          if (detailUser.isDeleted)
            const ShadBadge.destructive(child: Text('삭제됨')),
          if (detailUser.forcePasswordChange)
            const ShadBadge.outline(child: Text('비밀번호 변경 필요')),
        ];

  final metadata = detailUser == null
      ? const <SuperportDetailMetadata>[]
      : [
          SuperportDetailMetadata.text(
            label: 'ID',
            value: '${detailUser.id ?? '-'}',
          ),
          SuperportDetailMetadata.text(
            label: '그룹',
            value: detailUser.group?.groupName ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '이메일',
            value: detailUser.email?.isEmpty ?? true ? '-' : detailUser.email!,
          ),
          SuperportDetailMetadata.text(
            label: '연락처',
            value: detailUser.mobileNo?.isEmpty ?? true
                ? '-'
                : detailUser.mobileNo!,
          ),
          SuperportDetailMetadata.text(
            label: '비고',
            value: detailUser.note?.isEmpty ?? true ? '-' : detailUser.note!,
          ),
          SuperportDetailMetadata.text(
            label: '비밀번호 변경일시',
            value: detailUser.passwordUpdatedAt == null
                ? '-'
                : dateFormat.format(detailUser.passwordUpdatedAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '생성일시',
            value: detailUser.createdAt == null
                ? '-'
                : dateFormat.format(detailUser.createdAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '수정일시',
            value: detailUser.updatedAt == null
                ? '-'
                : dateFormat.format(detailUser.updatedAt!.toLocal()),
          ),
        ];

  return showSuperportDetailDialog<UserDetailDialogResult>(
    context: context,
    title: isDetail ? '사용자 상세' : '사용자 등록',
    description: isDetail
        ? '사용자 기본 정보와 권한 상태를 확인하고 관리합니다.'
        : '새 사용자 계정을 등록합니다.',
    sections: sections,
    summary: summary,
    summaryBadges: summaryBadges,
    metadata: metadata,
    emptyPlaceholder: const Text('표시할 사용자 정보가 없습니다.'),
    initialSectionId: isDetail
        ? _UserDetailSections.overview
        : _UserDetailSections.create,
  );
}

/// 사용자 상세 다이얼로그 섹션 ID 모음이다.
class _UserDetailSections {
  static const overview = 'overview';
  static const activity = 'activity';
  static const security = 'security';
  static const edit = 'edit';
  static const delete = 'delete';
  static const restore = 'restore';
  static const create = 'create';
}

/// 사용자 주요 정보를 표시하는 섹션이다.
class _UserOverviewSection extends StatelessWidget {
  const _UserOverviewSection({required this.user, required this.dateFormat});

  final UserAccount user;
  final intl.DateFormat dateFormat;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final rows = <_KeyValueRow>[
      _KeyValueRow('사번', user.employeeNo),
      _KeyValueRow('이메일', user.email?.isEmpty ?? true ? '-' : user.email!),
      _KeyValueRow(
        '연락처',
        user.mobileNo?.isEmpty ?? true ? '-' : user.mobileNo!,
      ),
      _KeyValueRow('그룹', user.group?.groupName ?? '-'),
      _KeyValueRow('사용 여부', user.isActive ? 'Y' : 'N'),
      _KeyValueRow('삭제 여부', user.isDeleted ? 'Y' : 'N'),
      _KeyValueRow('비고', user.note?.isEmpty ?? true ? '-' : user.note!),
      _KeyValueRow(
        '생성일시',
        user.createdAt == null
            ? '-'
            : dateFormat.format(user.createdAt!.toLocal()),
      ),
      _KeyValueRow(
        '수정일시',
        user.updatedAt == null
            ? '-'
            : dateFormat.format(user.updatedAt!.toLocal()),
      ),
    ];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        for (var i = 0; i < rows.length; i++) ...[
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                width: 140,
                child: Text(
                  rows[i].label,
                  style: theme.textTheme.small.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Text(rows[i].value, style: theme.textTheme.small),
              ),
            ],
          ),
          if (i < rows.length - 1) const SizedBox(height: 12),
        ],
      ],
    );
  }
}

/// 사용자 최근 활동 섹션. 실제 데이터가 준비되기 전까지 가이드 문구를 제공한다.
class _UserActivitySection extends StatelessWidget {
  const _UserActivitySection();

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('최근 활동 데이터는 준비 중입니다.', style: theme.textTheme.small),
        const SizedBox(height: 8),
        Text(
          '결재/입출고 이력과 같은 사용자 활동은 추후 통합 대시보드에서 확인할 수 있도록 연동될 예정입니다.',
          style: theme.textTheme.small.copyWith(
            color: theme.colorScheme.mutedForeground,
          ),
        ),
      ],
    );
  }
}

/// 사용자 비밀번호 상태 및 재설정을 포함한 섹션이다.
class _UserSecuritySection extends SuperportDetailDialogSection {
  _UserSecuritySection({
    required this.user,
    required this.dateFormat,
    required this.onResetPassword,
  }) : super(
         id: _UserDetailSections.security,
         label: '보안',
         icon: LucideIcons.shieldCheck,
         builder: (context) => _UserSecurityContent(
           user: user,
           dateFormat: dateFormat,
           onResetPassword: onResetPassword,
         ),
       );

  final UserAccount user;
  final intl.DateFormat dateFormat;
  final Future<UserDetailDialogResult?> Function() onResetPassword;
}

class _UserSecurityContent extends StatefulWidget {
  const _UserSecurityContent({
    required this.user,
    required this.dateFormat,
    required this.onResetPassword,
  });

  final UserAccount user;
  final intl.DateFormat dateFormat;
  final Future<UserDetailDialogResult?> Function() onResetPassword;

  @override
  State<_UserSecurityContent> createState() => _UserSecurityContentState();
}

class _UserSecurityContentState extends State<_UserSecurityContent> {
  bool _isProcessing = false;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _KeyValueColumn(
          label: '비밀번호 변경일시',
          value: widget.user.passwordUpdatedAt == null
              ? '-'
              : widget.dateFormat.format(
                  widget.user.passwordUpdatedAt!.toLocal(),
                ),
        ),
        const SizedBox(height: 12),
        _KeyValueColumn(
          label: '비밀번호 변경 필요',
          value: widget.user.forcePasswordChange ? '예' : '아니오',
        ),
        const SizedBox(height: 16),
        Text(
          '임시 비밀번호를 발급하면 기존 비밀번호는 즉시 무효화되고, 사용자에게 이메일이 발송됩니다.',
          style: theme.textTheme.small.copyWith(
            color: theme.colorScheme.mutedForeground,
          ),
        ),
        const SizedBox(height: 16),
        Align(
          alignment: Alignment.centerLeft,
          child: ShadButton(
            onPressed: _isProcessing ? null : _handleResetPassword,
            child: _isProcessing
                ? const SizedBox(
                    width: 16,
                    height: 16,
                    child: CircularProgressIndicator(strokeWidth: 2),
                  )
                : const Text('비밀번호 재설정'),
          ),
        ),
      ],
    );
  }

  Future<void> _handleResetPassword() async {
    final confirmed = await SuperportDialog.show<bool>(
      context: context,
      dialog: SuperportDialog(
        title: '비밀번호 재설정',
        description:
            '"${widget.user.employeeName}" 사용자의 비밀번호를 재설정하고 임시 비밀번호를 이메일로 발송합니다.',
        actions: [
          ShadButton.ghost(
            onPressed: () =>
                Navigator.of(context, rootNavigator: true).pop(false),
            child: const Text('취소'),
          ),
          ShadButton(
            onPressed: () =>
                Navigator.of(context, rootNavigator: true).pop(true),
            child: const Text('재설정'),
          ),
        ],
      ),
    );

    if (!mounted || confirmed != true) {
      return;
    }

    setState(() {
      _isProcessing = true;
    });
    final navigator = Navigator.of(context, rootNavigator: true);
    final result = await widget.onResetPassword();
    if (!mounted) {
      return;
    }
    setState(() {
      _isProcessing = false;
    });
    if (result != null && navigator.mounted) {
      navigator.pop(result);
    }
  }
}

/// 사용자 등록/수정 폼을 제공하는 섹션이다.
class _UserFormSection extends SuperportDetailDialogSection {
  _UserFormSection({
    required super.id,
    required super.label,
    required this.user,
    required this.groupOptions,
    required this.onSubmit,
  }) : super(
         icon: LucideIcons.pencil,
         builder: (context) => _UserForm(
           user: user,
           groupOptions: groupOptions,
           onSubmit: onSubmit,
         ),
       );

  final UserAccount? user;
  final List<Group> groupOptions;
  final Future<UserDetailDialogResult?> Function(UserInput input) onSubmit;
}

class _UserForm extends StatefulWidget {
  const _UserForm({
    required this.user,
    required this.groupOptions,
    required this.onSubmit,
  });

  final UserAccount? user;
  final List<Group> groupOptions;
  final Future<UserDetailDialogResult?> Function(UserInput input) onSubmit;

  @override
  State<_UserForm> createState() => _UserFormState();
}

class _UserFormState extends State<_UserForm> {
  late final TextEditingController _employeeController;
  late final TextEditingController _nameController;
  late final TextEditingController _emailController;
  late final TextEditingController _phoneController;
  late final TextEditingController _passwordController;
  late final TextEditingController _noteController;
  late final ValueNotifier<int?> _groupIdNotifier;
  late final ValueNotifier<bool> _isActiveNotifier;
  String? _employeeError;
  String? _nameError;
  String? _emailError;
  String? _phoneError;
  String? _groupError;
  String? _passwordError;
  bool _isSubmitting = false;

  bool get _isEdit => widget.user != null;

  @override
  void initState() {
    super.initState();
    final user = widget.user;
    _employeeController = TextEditingController(text: user?.employeeNo ?? '');
    _nameController = TextEditingController(text: user?.employeeName ?? '');
    _emailController = TextEditingController(text: user?.email ?? '');
    _phoneController = TextEditingController(text: user?.mobileNo ?? '');
    _passwordController = TextEditingController();
    _noteController = TextEditingController(text: user?.note ?? '');
    _groupIdNotifier = ValueNotifier<int?>(user?.group?.id);
    _isActiveNotifier = ValueNotifier<bool>(user?.isActive ?? true);

    if (_groupIdNotifier.value == null && widget.groupOptions.length == 1) {
      _groupIdNotifier.value = widget.groupOptions.first.id;
    }
  }

  @override
  void dispose() {
    _employeeController.dispose();
    _nameController.dispose();
    _emailController.dispose();
    _phoneController.dispose();
    _passwordController.dispose();
    _noteController.dispose();
    _groupIdNotifier.dispose();
    _isActiveNotifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final materialTheme = Theme.of(context);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _FormField(
          label: '사번',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                key: const ValueKey('user_form_employee'),
                controller: _employeeController,
                readOnly: _isEdit,
                onChanged: (_) {
                  if (_employeeController.text.trim().isNotEmpty) {
                    setState(() => _employeeError = null);
                  }
                },
              ),
              if (_employeeError != null) _ErrorText(_employeeError!),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _FormField(
          label: '성명',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                key: const ValueKey('user_form_name'),
                controller: _nameController,
                onChanged: (_) {
                  if (_nameController.text.trim().isNotEmpty) {
                    setState(() => _nameError = null);
                  }
                },
              ),
              if (_nameError != null) _ErrorText(_nameError!),
            ],
          ),
        ),
        if (!_isEdit) ...[
          const SizedBox(height: 16),
          _FormField(
            label: '임시 비밀번호',
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                TextField(
                  key: const ValueKey('user_form_password'),
                  controller: _passwordController,
                  obscureText: true,
                  obscuringCharacter: '●',
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    isDense: true,
                    constraints: const BoxConstraints(
                      minHeight: 44,
                      maxHeight: 44,
                    ),
                  ),
                  style: materialTheme.textTheme.bodyMedium,
                  onChanged: (_) {
                    setState(() {
                      _passwordError = null;
                    });
                  },
                ),
                const SizedBox(height: 6),
                Text(
                  '8~24자, 대소문자/숫자/특수문자 각 1자 이상 포함',
                  style: theme.textTheme.small.copyWith(
                    color: theme.colorScheme.mutedForeground,
                  ),
                ),
                if (_passwordError != null) _ErrorText(_passwordError!),
              ],
            ),
          ),
        ],
        const SizedBox(height: 16),
        _FormField(
          label: '이메일',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                key: const ValueKey('user_form_email'),
                controller: _emailController,
                keyboardType: TextInputType.emailAddress,
                onChanged: (_) {
                  if (_emailController.text.trim().isNotEmpty) {
                    setState(() => _emailError = null);
                  }
                },
              ),
              if (_emailError != null) _ErrorText(_emailError!),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _FormField(
          label: '연락처',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                key: const ValueKey('user_form_phone'),
                controller: _phoneController,
                keyboardType: TextInputType.phone,
                onChanged: (_) {
                  if (_phoneController.text.trim().isNotEmpty) {
                    setState(() => _phoneError = null);
                  }
                },
              ),
              if (_phoneError != null) _ErrorText(_phoneError!),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _FormField(
          label: '그룹',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ValueListenableBuilder<int?>(
                valueListenable: _groupIdNotifier,
                builder: (_, value, __) {
                  return ShadSelect<int?>(
                    key: const ValueKey('user_form_group_select'),
                    initialValue: value,
                    placeholder: const Text('그룹을 선택하세요'),
                    selectedOptionBuilder: (context, selected) {
                      if (selected == null) {
                        return const Text('그룹을 선택하세요');
                      }
                      final group = widget.groupOptions.firstWhere(
                        (g) => g.id == selected,
                        orElse: () => Group(id: selected, groupName: ''),
                      );
                      return Text(group.groupName);
                    },
                    onChanged: _isSubmitting
                        ? null
                        : (next) {
                            _groupIdNotifier.value = next;
                            setState(() => _groupError = null);
                          },
                    options: widget.groupOptions
                        .map(
                          (group) => ShadOption<int?>(
                            value: group.id,
                            child: Text(group.groupName),
                          ),
                        )
                        .toList(),
                  );
                },
              ),
              if (_groupError != null) _ErrorText(_groupError!),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _FormField(
          label: '사용 여부',
          child: ValueListenableBuilder<bool>(
            valueListenable: _isActiveNotifier,
            builder: (_, value, __) {
              return ShadSwitch(
                value: value,
                onChanged: _isSubmitting
                    ? null
                    : (next) => _isActiveNotifier.value = next,
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        _FormField(
          label: '비고',
          child: ShadTextarea(
            controller: _noteController,
            minHeight: 96,
            maxHeight: 200,
          ),
        ),
        const SizedBox(height: 20),
        Align(
          alignment: Alignment.centerRight,
          child: ShadButton(
            onPressed: _isSubmitting ? null : _handleSubmit,
            child: Text(_isEdit ? '저장' : '등록'),
          ),
        ),
      ],
    );
  }

  Future<void> _handleSubmit() async {
    final employeeNo = _employeeController.text.trim();
    final name = _nameController.text.trim();
    final email = _emailController.text.trim();
    final phone = _phoneController.text.trim();
    final note = _noteController.text.trim();
    final groupId = _groupIdNotifier.value;

    setState(() {
      _employeeError = employeeNo.isEmpty ? '사번을 입력하세요.' : null;
      _nameError = name.isEmpty ? '성명을 입력하세요.' : null;
      _emailError = email.isEmpty ? '이메일을 입력하세요.' : null;
      _phoneError = phone.isEmpty ? '연락처를 입력하세요.' : null;
      _groupError = groupId == null ? '그룹을 선택하세요.' : null;
      if (!_isEdit) {
        final password = _passwordController.text;
        if (password.isEmpty) {
          _passwordError = '임시 비밀번호를 입력하세요.';
        } else {
          final violations = PasswordRules.validate(password);
          _passwordError = violations.isEmpty
              ? null
              : _describePasswordViolations(violations);
        }
      } else {
        _passwordError = null;
      }
    });

    if (_employeeError != null ||
        _nameError != null ||
        _emailError != null ||
        _phoneError != null ||
        _groupError != null ||
        _passwordError != null) {
      return;
    }

    setState(() {
      _isSubmitting = true;
    });

    final navigator = Navigator.of(context, rootNavigator: true);
    final input = UserInput(
      employeeNo: employeeNo,
      employeeName: name,
      groupId: groupId!,
      email: email.isEmpty ? null : email,
      mobileNo: phone.isEmpty ? null : phone,
      isActive: _isActiveNotifier.value,
      password: _isEdit ? null : _passwordController.text,
      forcePasswordChange: _isEdit ? null : true,
      note: note.isEmpty ? null : note,
    );

    final result = await widget.onSubmit(input);
    if (!mounted) {
      return;
    }
    setState(() {
      _isSubmitting = false;
    });
    if (result != null && navigator.mounted) {
      navigator.pop(result);
    }
  }

  String _describePasswordViolations(List<PasswordRuleViolation> violations) {
    final messages = <String>[];
    for (final violation in violations) {
      switch (violation) {
        case PasswordRuleViolation.tooShort:
          messages.add('최소 8자 이상 입력해야 합니다.');
          break;
        case PasswordRuleViolation.tooLong:
          messages.add('최대 24자 이하로 입력해야 합니다.');
          break;
        case PasswordRuleViolation.missingUppercase:
          messages.add('대문자를 최소 1자 포함해야 합니다.');
          break;
        case PasswordRuleViolation.missingLowercase:
          messages.add('소문자를 최소 1자 포함해야 합니다.');
          break;
        case PasswordRuleViolation.missingDigit:
          messages.add('숫자를 최소 1자 포함해야 합니다.');
          break;
        case PasswordRuleViolation.missingSpecial:
          messages.add('특수문자를 최소 1자 포함해야 합니다.');
          break;
      }
    }
    return messages.join('\n');
  }
}

/// 사용자 삭제/복구를 안내하는 위험 섹션이다.
class _UserDangerSection extends SuperportDetailDialogSection {
  _UserDangerSection({
    required this.user,
    required this.onDelete,
    required this.onRestore,
  }) : super(
         id: user.isDeleted
             ? _UserDetailSections.restore
             : _UserDetailSections.delete,
         label: user.isDeleted ? '복구' : '삭제',
         icon: user.isDeleted ? LucideIcons.history : LucideIcons.trash2,
         builder: (context) => _UserDangerContent(
           user: user,
           onDelete: onDelete,
           onRestore: onRestore,
         ),
         scrollable: false,
       );

  final UserAccount user;
  final Future<UserDetailDialogResult?> Function() onDelete;
  final Future<UserDetailDialogResult?> Function() onRestore;
}

class _UserDangerContent extends StatefulWidget {
  const _UserDangerContent({
    required this.user,
    required this.onDelete,
    required this.onRestore,
  });

  final UserAccount user;
  final Future<UserDetailDialogResult?> Function() onDelete;
  final Future<UserDetailDialogResult?> Function() onRestore;

  @override
  State<_UserDangerContent> createState() => _UserDangerContentState();
}

class _UserDangerContentState extends State<_UserDangerContent> {
  bool _isProcessing = false;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final isDeleted = widget.user.isDeleted;
    final description = isDeleted
        ? '사용자를 복구하면 다시 목록에 노출되고 서비스 로그인에 사용할 수 있습니다.'
        : '삭제하면 사용자가 목록에서 숨겨지고 신규 로그인 시도가 차단됩니다.';
    final actionLabel = isDeleted ? '복구' : '삭제';

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(description, style: theme.textTheme.small),
        const SizedBox(height: 16),
        Align(
          alignment: Alignment.centerLeft,
          child: isDeleted
              ? ShadButton(
                  onPressed: _isProcessing ? null : _handleRestore,
                  child: _isProcessing
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : Text(actionLabel),
                )
              : ShadButton.destructive(
                  onPressed: _isProcessing ? null : _handleDelete,
                  child: _isProcessing
                      ? const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(strokeWidth: 2),
                        )
                      : Text(actionLabel),
                ),
        ),
      ],
    );
  }

  Future<void> _handleDelete() async {
    final confirmed = await SuperportDialog.show<bool>(
      context: context,
      dialog: SuperportDialog(
        title: '사용자 삭제',
        description: '"${widget.user.employeeName}" 사용자를 삭제하시겠습니까?',
        actions: [
          ShadButton.ghost(
            onPressed: () =>
                Navigator.of(context, rootNavigator: true).pop(false),
            child: const Text('취소'),
          ),
          ShadButton.destructive(
            onPressed: () =>
                Navigator.of(context, rootNavigator: true).pop(true),
            child: const Text('삭제'),
          ),
        ],
      ),
    );

    if (confirmed != true) {
      return;
    }

    await _runDangerAction(widget.onDelete);
  }

  Future<void> _handleRestore() async {
    await _runDangerAction(widget.onRestore);
  }

  Future<void> _runDangerAction(
    Future<UserDetailDialogResult?> Function() action,
  ) async {
    setState(() {
      _isProcessing = true;
    });
    final navigator = Navigator.of(context, rootNavigator: true);
    final result = await action();
    if (!mounted) {
      return;
    }
    setState(() {
      _isProcessing = false;
    });
    if (result != null && navigator.mounted) {
      navigator.pop(result);
    }
  }
}

class _FormField extends StatelessWidget {
  const _FormField({required this.label, required this.child});

  final String label;
  final Widget child;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label, style: theme.textTheme.small),
        const SizedBox(height: 6),
        child,
      ],
    );
  }
}

class _ErrorText extends StatelessWidget {
  const _ErrorText(this.message);

  final String message;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Padding(
      padding: const EdgeInsets.only(top: 6),
      child: Text(
        message,
        style: theme.textTheme.small.copyWith(
          color: theme.colorScheme.destructive,
        ),
      ),
    );
  }
}

class _KeyValueRow {
  const _KeyValueRow(this.label, this.value);

  final String label;
  final String value;
}

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

  final String label;
  final String value;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          label,
          style: theme.textTheme.small.copyWith(fontWeight: FontWeight.w600),
        ),
        const SizedBox(height: 4),
        Text(value, style: theme.textTheme.small),
      ],
    );
  }
}
