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 '../../domain/entities/group.dart';

/// 그룹 상세 다이얼로그 사용자 액션 유형이다.
enum GroupDetailDialogAction { created, updated, deleted, restored }

/// 그룹 상세 다이얼로그 종료 시 반환되는 결과이다.
class GroupDetailDialogResult {
  const GroupDetailDialogResult({required this.action, required this.message});

  final GroupDetailDialogAction action;
  final String message;
}

typedef GroupCreateCallback = Future<Group?> Function(GroupInput input);
typedef GroupUpdateCallback = Future<Group?> Function(int id, GroupInput input);
typedef GroupDeleteCallback = Future<bool> Function(int id);
typedef GroupRestoreCallback = Future<Group?> Function(int id);

/// 그룹 상세 다이얼로그를 호출해 생성/수정/삭제/복구를 통합 처리한다.
Future<GroupDetailDialogResult?> showGroupDetailDialog({
  required BuildContext context,
  required intl.DateFormat dateFormat,
  Group? group,
  required GroupCreateCallback onCreate,
  required GroupUpdateCallback onUpdate,
  required GroupDeleteCallback onDelete,
  required GroupRestoreCallback onRestore,
}) {
  final groupValue = group;
  final isEdit = groupValue != null;
  final title = isEdit ? '그룹 상세' : '그룹 등록';
  final description = isEdit
      ? '그룹 기본 정보와 권한 상태를 확인하고 관리합니다.'
      : '새로운 그룹 정보를 입력하세요.';

  final metadata = groupValue == null
      ? const <SuperportDetailMetadata>[]
      : [
          SuperportDetailMetadata.text(
            label: 'ID',
            value: groupValue.id?.toString() ?? '-',
          ),
          SuperportDetailMetadata.text(
            label: '기본 여부',
            value: groupValue.isDefault ? '기본 그룹' : '일반 그룹',
          ),
          SuperportDetailMetadata.text(
            label: '사용 여부',
            value: groupValue.isActive ? '사용중' : '미사용',
          ),
          SuperportDetailMetadata.text(
            label: '삭제 여부',
            value: groupValue.isDeleted ? '삭제됨' : '정상',
          ),
          SuperportDetailMetadata.text(
            label: '생성일시',
            value: groupValue.createdAt == null
                ? '-'
                : dateFormat.format(groupValue.createdAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '변경일시',
            value: groupValue.updatedAt == null
                ? '-'
                : dateFormat.format(groupValue.updatedAt!.toLocal()),
          ),
          SuperportDetailMetadata.text(
            label: '비고',
            value: groupValue.note?.isEmpty ?? true ? '-' : groupValue.note!,
          ),
        ];

  return showSuperportDetailDialog<GroupDetailDialogResult>(
    context: context,
    title: title,
    description: description,
    summary: groupValue == null
        ? null
        : Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                groupValue.groupName,
                style: ShadTheme.of(context).textTheme.h4,
              ),
              if (groupValue.description?.isNotEmpty ?? false) ...[
                const SizedBox(height: 4),
                Text(
                  groupValue.description!,
                  style: ShadTheme.of(context).textTheme.muted,
                ),
              ],
            ],
          ),
    summaryBadges: groupValue == null
        ? const []
        : [
            if (groupValue.isDefault)
              const ShadBadge(child: Text('기본 그룹'))
            else
              const ShadBadge.outline(child: Text('일반 그룹')),
            if (groupValue.isActive)
              const ShadBadge(child: Text('사용중'))
            else
              const ShadBadge.outline(child: Text('미사용')),
            if (groupValue.isDeleted)
              const ShadBadge.destructive(child: Text('삭제됨')),
          ],
    metadata: metadata,
    sections: [
      _GroupEditSection(
        id: isEdit ? _GroupDetailSections.edit : _GroupDetailSections.create,
        label: isEdit ? '수정' : '등록',
        group: groupValue,
        onSubmit: (input) async {
          if (groupValue == null) {
            final created = await onCreate(input);
            if (created == null) {
              return null;
            }
            return const GroupDetailDialogResult(
              action: GroupDetailDialogAction.created,
              message: '그룹을 등록했습니다.',
            );
          }
          final groupId = groupValue.id;
          if (groupId == null) {
            return null;
          }
          final updated = await onUpdate(groupId, input);
          if (updated == null) {
            return null;
          }
          return const GroupDetailDialogResult(
            action: GroupDetailDialogAction.updated,
            message: '그룹을 수정했습니다.',
          );
        },
      ),
      if (groupValue != null)
        SuperportDetailDialogSection(
          id: groupValue.isDeleted
              ? _GroupDetailSections.restore
              : _GroupDetailSections.delete,
          label: groupValue.isDeleted ? '복구' : '삭제',
          icon: groupValue.isDeleted ? LucideIcons.history : LucideIcons.trash2,
          builder: (_) => _GroupDangerSection(
            group: groupValue,
            onDelete: () async {
              final groupId = groupValue.id;
              if (groupId == null) {
                return null;
              }
              final success = await onDelete(groupId);
              if (!success) {
                return null;
              }
              return const GroupDetailDialogResult(
                action: GroupDetailDialogAction.deleted,
                message: '그룹을 삭제했습니다.',
              );
            },
            onRestore: () async {
              final groupId = groupValue.id;
              if (groupId == null) {
                return null;
              }
              final restored = await onRestore(groupId);
              if (restored == null) {
                return null;
              }
              return const GroupDetailDialogResult(
                action: GroupDetailDialogAction.restored,
                message: '그룹을 복구했습니다.',
              );
            },
          ),
        ),
    ],
    emptyPlaceholder: const Text('표시할 그룹 정보가 없습니다.'),
    initialSectionId: groupValue == null
        ? _GroupDetailSections.create
        : _GroupDetailSections.edit,
  );
}

/// 그룹 상세 다이얼로그 섹션 식별자이다.
class _GroupDetailSections {
  static const edit = 'edit';
  static const delete = 'delete';
  static const restore = 'restore';
  static const create = 'create';
}

/// 그룹 생성/수정을 담당하는 섹션이다.
class _GroupEditSection extends SuperportDetailDialogSection {
  _GroupEditSection({
    required super.id,
    required super.label,
    required Group? group,
    required Future<GroupDetailDialogResult?> Function(GroupInput input)
    onSubmit,
  }) : super(
         icon: LucideIcons.pencil,
         builder: (context) => _GroupForm(group: group, onSubmit: onSubmit),
       );
}

/// 그룹 삭제/복구를 실행하는 위험 영역이다.
class _GroupDangerSection extends StatelessWidget {
  const _GroupDangerSection({
    required this.group,
    required this.onDelete,
    required this.onRestore,
  });

  final Group group;
  final Future<GroupDetailDialogResult?> Function() onDelete;
  final Future<GroupDetailDialogResult?> Function() onRestore;

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    final isDeleted = group.isDeleted;
    final description = 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 (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 _GroupForm extends StatefulWidget {
  const _GroupForm({required this.group, required this.onSubmit});

  final Group? group;
  final Future<GroupDetailDialogResult?> Function(GroupInput input) onSubmit;

  bool get _isEdit => group != null;

  @override
  State<_GroupForm> createState() => _GroupFormState();
}

class _GroupFormState extends State<_GroupForm> {
  late final TextEditingController _nameController;
  late final TextEditingController _descriptionController;
  late final TextEditingController _noteController;
  late final ValueNotifier<bool> _isDefaultNotifier;
  late final ValueNotifier<bool> _isActiveNotifier;
  String? _nameError;
  String? _submitError;
  bool _isSubmitting = false;

  bool get _isEdit => widget._isEdit;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(
      text: widget.group?.groupName ?? '',
    );
    _descriptionController = TextEditingController(
      text: widget.group?.description ?? '',
    );
    _noteController = TextEditingController(text: widget.group?.note ?? '');
    _isDefaultNotifier = ValueNotifier<bool>(widget.group?.isDefault ?? false);
    _isActiveNotifier = ValueNotifier<bool>(widget.group?.isActive ?? true);
  }

  @override
  void dispose() {
    _nameController.dispose();
    _descriptionController.dispose();
    _noteController.dispose();
    _isDefaultNotifier.dispose();
    _isActiveNotifier.dispose();
    super.dispose();
  }

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

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _GroupFormField(
          label: '그룹명',
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ShadInput(
                controller: _nameController,
                readOnly: _isEdit,
                onChanged: (_) {
                  if (_nameController.text.trim().isNotEmpty) {
                    setState(() {
                      _nameError = null;
                    });
                  }
                },
              ),
              if (_nameError != null)
                Padding(
                  padding: const EdgeInsets.only(top: 6),
                  child: Text(
                    _nameError!,
                    style: theme.textTheme.small.copyWith(
                      color: theme.colorScheme.destructive,
                    ),
                  ),
                ),
            ],
          ),
        ),
        const SizedBox(height: 16),
        _GroupFormField(
          label: '설명',
          child: ShadTextarea(
            controller: _descriptionController,
            minHeight: 96,
            maxHeight: 220,
          ),
        ),
        const SizedBox(height: 16),
        _GroupFormField(
          label: '기본 여부',
          child: ValueListenableBuilder<bool>(
            valueListenable: _isDefaultNotifier,
            builder: (_, value, __) {
              return Row(
                children: [
                  ShadSwitch(
                    value: value,
                    onChanged: _isSubmitting
                        ? null
                        : (next) => _isDefaultNotifier.value = next,
                  ),
                  const SizedBox(width: 8),
                  Text(value ? '기본 그룹' : '일반 그룹'),
                ],
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        _GroupFormField(
          label: '사용 여부',
          child: ValueListenableBuilder<bool>(
            valueListenable: _isActiveNotifier,
            builder: (_, value, __) {
              return Row(
                children: [
                  ShadSwitch(
                    value: value,
                    onChanged: _isSubmitting
                        ? null
                        : (next) => _isActiveNotifier.value = next,
                  ),
                  const SizedBox(width: 8),
                  Text(value ? '사용' : '미사용'),
                ],
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        _GroupFormField(
          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 {
    final name = _nameController.text.trim();

    setState(() {
      _nameError = name.isEmpty ? '그룹명을 입력하세요.' : null;
      _submitError = null;
    });

    if (_nameError != null) {
      return;
    }

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

    final description = _descriptionController.text.trim();
    final note = _noteController.text.trim();
    final input = GroupInput(
      groupName: name,
      description: description.isEmpty ? null : description,
      isDefault: _isDefaultNotifier.value,
      isActive: _isActiveNotifier.value,
      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);
    }
  }
}

/// 그룹 폼 필드 공통 레이아웃이다.
class _GroupFormField extends StatelessWidget {
  const _GroupFormField({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,
      ],
    );
  }
}

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