import 'dart:async';

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

import '../../../../../widgets/components/superport_detail_dialog.dart';
import '../../../group/domain/entities/group.dart';
import '../../../menu/domain/entities/menu.dart';
import '../../domain/entities/group_permission.dart';

/// 그룹 권한 상세 다이얼로그 결과 유형이다.
enum GroupPermissionDetailDialogAction { created, updated, deleted, restored }

/// 그룹 권한 상세 다이얼로그에서 반환되는 결과이다.
class GroupPermissionDetailDialogResult {
  const GroupPermissionDetailDialogResult({
    required this.action,
    required this.message,
  });

  final GroupPermissionDetailDialogAction action;
  final String message;
}

typedef GroupPermissionCreateCallback =
    Future<GroupPermission?> Function(GroupPermissionInput input);
typedef GroupPermissionUpdateCallback =
    Future<GroupPermission?> Function(int id, GroupPermissionInput input);
typedef GroupPermissionDeleteCallback = Future<bool> Function(int id);
typedef GroupPermissionRestoreCallback =
    Future<GroupPermission?> Function(int id);

/// 그룹 권한 상세 다이얼로그를 표시한다.
Future<GroupPermissionDetailDialogResult?> showGroupPermissionDetailDialog({
  required BuildContext context,
  required intl.DateFormat dateFormat,
  GroupPermission? permission,
  required List<Group> groups,
  required bool isLoadingGroups,
  required List<MenuItem> menus,
  required bool isLoadingMenus,
  required GroupPermissionCreateCallback onCreate,
  required GroupPermissionUpdateCallback onUpdate,
  required GroupPermissionDeleteCallback onDelete,
  required GroupPermissionRestoreCallback onRestore,
}) {
  final permissionValue = permission;
  final isEdit = permissionValue != null;
  final title = isEdit ? '그룹 권한 상세' : '그룹 권한 등록';
  final description = isEdit
      ? '그룹과 메뉴에 부여된 CRUD 권한을 확인하고 변경합니다.'
      : '그룹-메뉴 권한을 신규로 연결하세요.';

  List<Widget> buildSummaryBadges(GroupPermission? value) {
    if (value == null) {
      return const [];
    }
    Widget badge(String label, bool enabled, {bool destructive = false}) {
      if (enabled) {
        if (destructive) {
          return ShadBadge.destructive(child: Text(label));
        }
        return ShadBadge(child: Text(label));
      }
      return ShadBadge.outline(child: Text(label));
    }

    return [
      badge('사용중', value.isActive),
      if (value.isDeleted) const ShadBadge.destructive(child: Text('삭제됨')),
      badge('생성', value.canCreate),
      badge('조회', value.canRead),
      badge('수정', value.canUpdate),
      badge('삭제', value.canDelete, destructive: true),
    ];
  }

  final metadata = permissionValue == null
      ? const <SuperportDetailMetadata>[]
      : [
          SuperportDetailMetadata.text(
            label: 'ID',
            value: permissionValue.id?.toString() ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '그룹',
            value: permissionValue.group.groupName,
          ),
          SuperportDetailMetadata.text(
            label: '메뉴',
            value: permissionValue.menu.menuName,
          ),
          SuperportDetailMetadata.text(
            label: '메뉴 경로',
            value: permissionValue.menu.path?.isEmpty ?? true
                ? '-'
                : permissionValue.menu.path!,
          ),
          SuperportDetailMetadata.text(
            label: '생성 권한',
            value: permissionValue.canCreate ? '허용' : '차단',
          ),
          SuperportDetailMetadata.text(
            label: '조회 권한',
            value: permissionValue.canRead ? '허용' : '차단',
          ),
          SuperportDetailMetadata.text(
            label: '수정 권한',
            value: permissionValue.canUpdate ? '허용' : '차단',
          ),
          SuperportDetailMetadata.text(
            label: '삭제 권한',
            value: permissionValue.canDelete ? '허용' : '차단',
          ),
          SuperportDetailMetadata.text(
            label: '사용 여부',
            value: permissionValue.isActive ? '사용중' : '미사용',
          ),
          SuperportDetailMetadata.text(
            label: '삭제 여부',
            value: permissionValue.isDeleted ? '삭제됨' : '정상',
          ),
          SuperportDetailMetadata.text(
            label: '비고',
            value: permissionValue.note?.isEmpty ?? true
                ? '-'
                : permissionValue.note!,
          ),
          SuperportDetailMetadata.text(
            label: '생성일시',
            value: permissionValue.createdAt == null
                ? '-'
                : dateFormat.format(permissionValue.createdAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '변경일시',
            value: permissionValue.updatedAt == null
                ? '-'
                : dateFormat.format(permissionValue.updatedAt!.toLocal()),
          ),
        ];

  return showSuperportDetailDialog<GroupPermissionDetailDialogResult>(
    context: context,
    title: title,
    description: description,
    summary: permissionValue == null
        ? null
        : Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                permissionValue.group.groupName,
                style: ShadTheme.of(context).textTheme.h4,
              ),
              const SizedBox(height: 4),
              Text(
                '→ ${permissionValue.menu.menuName}',
                style: ShadTheme.of(context).textTheme.muted,
              ),
            ],
          ),
    summaryBadges: buildSummaryBadges(permissionValue),
    metadata: metadata,
    sections: [
      _GroupPermissionEditSection(
        id: isEdit
            ? _GroupPermissionDetailSections.edit
            : _GroupPermissionDetailSections.create,
        label: isEdit ? '수정' : '등록',
        permission: permissionValue,
        groups: groups,
        menus: menus,
        isLoadingGroups: isLoadingGroups,
        isLoadingMenus: isLoadingMenus,
        onSubmit: (input) async {
          if (permissionValue == null) {
            final created = await onCreate(input);
            if (created == null) {
              return null;
            }
            return const GroupPermissionDetailDialogResult(
              action: GroupPermissionDetailDialogAction.created,
              message: '권한을 등록했습니다.',
            );
          }
          final permissionId = permissionValue.id;
          if (permissionId == null) {
            return null;
          }
          final updated = await onUpdate(permissionId, input);
          if (updated == null) {
            return null;
          }
          return const GroupPermissionDetailDialogResult(
            action: GroupPermissionDetailDialogAction.updated,
            message: '권한을 수정했습니다.',
          );
        },
      ),
      if (permissionValue != null)
        SuperportDetailDialogSection(
          id: permissionValue.isDeleted
              ? _GroupPermissionDetailSections.restore
              : _GroupPermissionDetailSections.delete,
          label: permissionValue.isDeleted ? '복구' : '삭제',
          icon: permissionValue.isDeleted
              ? LucideIcons.history
              : LucideIcons.trash2,
          builder: (_) => _GroupPermissionDangerSection(
            permission: permissionValue,
            onDelete: () async {
              final permissionId = permissionValue.id;
              if (permissionId == null) {
                return null;
              }
              final success = await onDelete(permissionId);
              if (!success) {
                return null;
              }
              return const GroupPermissionDetailDialogResult(
                action: GroupPermissionDetailDialogAction.deleted,
                message: '권한을 삭제했습니다.',
              );
            },
            onRestore: () async {
              final permissionId = permissionValue.id;
              if (permissionId == null) {
                return null;
              }
              final restored = await onRestore(permissionId);
              if (restored == null) {
                return null;
              }
              return const GroupPermissionDetailDialogResult(
                action: GroupPermissionDetailDialogAction.restored,
                message: '권한을 복구했습니다.',
              );
            },
          ),
        ),
    ],
    emptyPlaceholder: const Text('표시할 권한 정보가 없습니다.'),
    initialSectionId: permissionValue == null
        ? _GroupPermissionDetailSections.create
        : _GroupPermissionDetailSections.edit,
  );
}

/// 그룹 권한 상세 섹션 식별자.
class _GroupPermissionDetailSections {
  static const edit = 'edit';
  static const delete = 'delete';
  static const restore = 'restore';
  static const create = 'create';
}

/// 그룹 권한 입력 섹션이다.
class _GroupPermissionEditSection extends SuperportDetailDialogSection {
  _GroupPermissionEditSection({
    required super.id,
    required super.label,
    required GroupPermission? permission,
    required List<Group> groups,
    required List<MenuItem> menus,
    required bool isLoadingGroups,
    required bool isLoadingMenus,
    required Future<GroupPermissionDetailDialogResult?> Function(
      GroupPermissionInput input,
    )
    onSubmit,
  }) : super(
         icon: LucideIcons.pencil,
         builder: (context) => _GroupPermissionForm(
           permission: permission,
           groups: groups,
           menus: menus,
           isLoadingGroups: isLoadingGroups,
           isLoadingMenus: isLoadingMenus,
           onSubmit: onSubmit,
         ),
       );
}

/// 권한 삭제/복구용 위험 섹션이다.
class _GroupPermissionDangerSection extends StatelessWidget {
  const _GroupPermissionDangerSection({
    required this.permission,
    required this.onDelete,
    required this.onRestore,
  });

  final GroupPermission permission;
  final Future<GroupPermissionDetailDialogResult?> Function() onDelete;
  final Future<GroupPermissionDetailDialogResult?> Function() onRestore;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final description = permission.isDeleted
        ? '복구하면 권한이 다시 활성화되고 권한 동기화가 진행됩니다.'
        : '삭제하면 권한이 비활성화되어 접근이 차단됩니다.';

    return Padding(
      padding: const EdgeInsets.only(top: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(description, style: theme.textTheme.small),
          const SizedBox(height: 16),
          if (permission.isDeleted)
            ShadButton(
              onPressed: () async {
                final navigator = Navigator.of(context, rootNavigator: true);
                final result = await onRestore();
                if (result != null && navigator.mounted) {
                  navigator.pop(result);
                }
              },
              child: const Text('복구'),
            )
          else
            ShadButton.destructive(
              onPressed: () async {
                final navigator = Navigator.of(context, rootNavigator: true);
                final result = await onDelete();
                if (result != null && navigator.mounted) {
                  navigator.pop(result);
                }
              },
              child: const Text('삭제'),
            ),
        ],
      ),
    );
  }
}

/// 그룹 권한 입력 폼을 담당한다.
class _GroupPermissionForm extends StatefulWidget {
  const _GroupPermissionForm({
    required this.permission,
    required this.groups,
    required this.menus,
    required this.isLoadingGroups,
    required this.isLoadingMenus,
    required this.onSubmit,
  });

  final GroupPermission? permission;
  final List<Group> groups;
  final List<MenuItem> menus;
  final bool isLoadingGroups;
  final bool isLoadingMenus;
  final Future<GroupPermissionDetailDialogResult?> Function(
    GroupPermissionInput input,
  )
  onSubmit;

  bool get _isEdit => permission != null;

  @override
  State<_GroupPermissionForm> createState() => _GroupPermissionFormState();
}

class _GroupPermissionFormState extends State<_GroupPermissionForm> {
  int? _selectedGroup;
  int? _selectedMenu;
  late bool _canCreate;
  late bool _canRead;
  late bool _canUpdate;
  late bool _canDelete;
  late bool _isActive;
  late final TextEditingController _noteController;
  String? _groupError;
  String? _menuError;
  String? _submitError;
  bool _isSubmitting = false;

  bool get _isEdit => widget._isEdit;

  @override
  void initState() {
    super.initState();
    final permission = widget.permission;
    _selectedGroup = permission?.group.id;
    _selectedMenu = permission?.menu.id;
    _canCreate = permission?.canCreate ?? false;
    _canRead = permission?.canRead ?? true;
    _canUpdate = permission?.canUpdate ?? false;
    _canDelete = permission?.canDelete ?? false;
    _isActive = permission?.isActive ?? true;
    _noteController = TextEditingController(text: permission?.note ?? '');
  }

  @override
  void dispose() {
    _noteController.dispose();
    super.dispose();
  }

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _GroupPermissionFormField(
          label: '그룹',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadSelect<int>(
                initialValue: _selectedGroup,
                placeholder: Text(
                  widget.isLoadingGroups ? '그룹 로딩중...' : '그룹 선택',
                ),
                selectedOptionBuilder: (_, value) {
                  final label = _resolveGroupLabel(value);
                  return Text(label);
                },
                onChanged: _isSubmitting || widget.isLoadingGroups
                    ? null
                    : (value) {
                        setState(() {
                          _selectedGroup = value;
                          _groupError = null;
                        });
                      },
                options: widget.groups
                    .map(
                      (group) => ShadOption<int>(
                        value: group.id!,
                        child: Text(group.groupName),
                      ),
                    )
                    .toList(),
              ),
              if (_groupError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    _groupError!,
                    style: theme.textTheme.small.copyWith(
                      color: theme.colorScheme.destructive,
                    ),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _GroupPermissionFormField(
          label: '메뉴',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadSelect<int>(
                initialValue: _selectedMenu,
                placeholder: Text(
                  widget.isLoadingMenus ? '메뉴 로딩중...' : '메뉴 선택',
                ),
                selectedOptionBuilder: (_, value) {
                  final label = _resolveMenuLabel(value);
                  return Text(label);
                },
                onChanged: _isSubmitting || widget.isLoadingMenus
                    ? null
                    : (value) {
                        setState(() {
                          _selectedMenu = value;
                          _menuError = null;
                        });
                      },
                options: widget.menus
                    .map(
                      (menu) => ShadOption<int>(
                        value: menu.id!,
                        child: Text(menu.menuName),
                      ),
                    )
                    .toList(),
              ),
              if (_menuError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    _menuError!,
                    style: theme.textTheme.small.copyWith(
                      color: theme.colorScheme.destructive,
                    ),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _GroupPermissionToggleRow(
          label: '생성 권한',
          value: _canCreate,
          onChanged: _isSubmitting
              ? null
              : (value) {
                  setState(() {
                    _canCreate = value;
                  });
                },
        ),
        const SizedBox(height: 12),
        _GroupPermissionToggleRow(
          label: '조회 권한',
          value: _canRead,
          onChanged: _isSubmitting
              ? null
              : (value) {
                  setState(() {
                    _canRead = value;
                  });
                },
        ),
        const SizedBox(height: 12),
        _GroupPermissionToggleRow(
          label: '수정 권한',
          value: _canUpdate,
          onChanged: _isSubmitting
              ? null
              : (value) {
                  setState(() {
                    _canUpdate = value;
                  });
                },
        ),
        const SizedBox(height: 12),
        _GroupPermissionToggleRow(
          label: '삭제 권한',
          value: _canDelete,
          onChanged: _isSubmitting
              ? null
              : (value) {
                  setState(() {
                    _canDelete = value;
                  });
                },
        ),
        const SizedBox(height: 16),
        _GroupPermissionFormField(
          label: '사용 여부',
          child: Row(
            children: [
              ShadSwitch(
                value: _isActive,
                onChanged: _isSubmitting
                    ? null
                    : (value) {
                        setState(() {
                          _isActive = value;
                        });
                      },
              ),
              const SizedBox(width: 8),
              Text(_isActive ? '사용' : '미사용'),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _GroupPermissionFormField(
          label: '비고',
          child: ShadTextarea(
            controller: _noteController,
            minHeight: 96,
            maxHeight: 220,
          ),
        ),
        if (_submitError != null) ...[
          const SizedBox(height: 16),
          Text(
            _submitError!,
            style: theme.textTheme.small.copyWith(
              color: theme.colorScheme.destructive,
            ),
          ),
        ],
        const SizedBox(height: 20),
        Align(
          alignment: Alignment.centerRight,
          child: ShadButton(
            onPressed: _isSubmitting ? null : _handleSubmit,
            child: Text(_isEdit ? '저장' : '등록'),
          ),
        ),
      ],
    );
  }

  Future<void> _handleSubmit() async {
    setState(() {
      _groupError = _selectedGroup == null ? '그룹을 선택하세요.' : null;
      _menuError = _selectedMenu == null ? '메뉴를 선택하세요.' : null;
      _submitError = null;
    });

    if (_groupError != null || _menuError != null) {
      return;
    }

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

    final note = _noteController.text.trim();
    final input = GroupPermissionInput(
      groupId: _selectedGroup!,
      menuId: _selectedMenu!,
      canCreate: _canCreate,
      canRead: _canRead,
      canUpdate: _canUpdate,
      canDelete: _canDelete,
      isActive: _isActive,
      note: note.isEmpty ? null : note,
    );
    final navigator = Navigator.of(context, rootNavigator: true);
    final result = await widget.onSubmit(input);

    if (!mounted) {
      return;
    }

    setState(() {
      _isSubmitting = false;
      _submitError = result == null ? '요청 처리에 실패했습니다.' : null;
    });

    if (result != null && navigator.mounted) {
      navigator.pop(result);
    }
  }

  String _resolveGroupLabel(int? id) {
    if (id == null) {
      return widget.isLoadingGroups ? '그룹 로딩중...' : '그룹 선택';
    }
    final group = widget.groups.firstWhere(
      (item) => item.id == id,
      orElse: () => Group(id: id, groupName: '알 수 없음'),
    );
    return group.groupName;
  }

  String _resolveMenuLabel(int? id) {
    if (id == null) {
      return widget.isLoadingMenus ? '메뉴 로딩중...' : '메뉴 선택';
    }
    final menu = widget.menus.firstWhere(
      (item) => item.id == id,
      orElse: () => MenuItem(id: id, menuCode: '', menuName: '알 수 없음'),
    );
    return menu.menuName;
  }
}

/// 폼 필드 레이아웃을 제공하는 위젯이다.
class _GroupPermissionFormField extends StatelessWidget {
  const _GroupPermissionFormField({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 _GroupPermissionToggleRow extends StatelessWidget {
  const _GroupPermissionToggleRow({
    required this.label,
    required this.value,
    required this.onChanged,
  });

  final String label;
  final bool value;
  final ValueChanged<bool>? onChanged;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(label),
        ShadSwitch(value: value, onChanged: onChanged),
      ],
    );
  }
}

/// 개요 섹션에서 사용하는 키-값 구조체이다.
