import 'dart:async';

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

import 'package:superport_v2/features/masters/group/domain/entities/group.dart';
import 'package:superport_v2/features/masters/user/domain/entities/user.dart';
import 'package:superport_v2/features/masters/user/presentation/dialogs/user_detail_dialog.dart';
import 'package:superport_v2/widgets/components/superport_dialog.dart';

import '../../../../../helpers/test_app.dart';

void main() {
  final dateFormat = intl.DateFormat('yyyy-MM-dd HH:mm');
  final groups = [Group(id: 1, groupName: '관리자')];

  Future<UserAccount?> noopCreate(UserInput _) async => null;
  Future<UserAccount?> noopUpdate(int _, UserInput __) async => null;
  Future<bool> noopDelete(int _) async => false;
  Future<UserAccount?> noopRestore(int _) async => null;
  Future<UserAccount?> noopReset(int _) async => null;

  testWidgets('showUserDetailDialog 등록 모드 폼 렌더링', (tester) async {
    await tester.pumpWidget(buildTestApp(const SizedBox.shrink()));
    final context = tester.element(find.byType(SizedBox));

    unawaited(
      showUserDetailDialog(
        context: context,
        dateFormat: dateFormat,
        groupOptions: groups,
        onCreate: noopCreate,
        onUpdate: noopUpdate,
        onDelete: noopDelete,
        onRestore: noopRestore,
        onResetPassword: noopReset,
      ),
    );

    await tester.pumpAndSettle();

    expect(find.text('사용자 등록'), findsOneWidget);
    expect(find.text('사번'), findsOneWidget);
    expect(find.text('그룹'), findsOneWidget);
    expect(find.text('등록'), findsWidgets);
  });

  testWidgets('상세 모드에서 비밀번호 재설정을 실행한다', (tester) async {
    await tester.binding.setSurfaceSize(const Size(1280, 800));
    addTearDown(() => tester.binding.setSurfaceSize(null));

    final user = UserAccount(
      id: 7,
      employeeNo: 'A007',
      employeeName: '홍길동',
      email: 'hong@superport.com',
      mobileNo: '010-1234-5678',
      group: UserGroup(id: 1, groupName: '관리자'),
      createdAt: DateTime(2024, 1, 1, 9),
      updatedAt: DateTime(2024, 1, 2, 10),
      passwordUpdatedAt: DateTime(2024, 1, 2, 9),
    );

    var resetCalled = false;

    await tester.pumpWidget(buildTestApp(const SizedBox.shrink()));
    final context = tester.element(find.byType(SizedBox));

    final dialogFuture = showUserDetailDialog(
      context: context,
      dateFormat: dateFormat,
      user: user,
      groupOptions: groups,
      onCreate: noopCreate,
      onUpdate: noopUpdate,
      onDelete: noopDelete,
      onRestore: noopRestore,
      onResetPassword: (id) async {
        resetCalled = id == 7;
        return user;
      },
    );

    await tester.pumpAndSettle();

    await tester.tap(find.text('보안'));
    await tester.pumpAndSettle();

    final resetButton = find.widgetWithText(ShadButton, '비밀번호 재설정').first;
    await tester.ensureVisible(resetButton);
    await tester.tap(resetButton, warnIfMissed: false);
    await tester.pumpAndSettle();

    expect(find.text('비밀번호 재설정'), findsWidgets);
    final confirmButton = find.widgetWithText(ShadButton, '재설정').last;
    await tester.ensureVisible(confirmButton);
    await tester.tap(confirmButton, warnIfMissed: false);
    await tester.pumpAndSettle();

    final result = await dialogFuture;

    expect(resetCalled, isTrue);
    expect(result?.action, UserDetailDialogAction.passwordReset);
    expect(find.byType(SuperportDialog), findsNothing);
  });

  testWidgets('상세 모드에서 삭제 섹션을 노출한다', (tester) async {
    await tester.binding.setSurfaceSize(const Size(1280, 800));
    addTearDown(() => tester.binding.setSurfaceSize(null));

    final user = UserAccount(
      id: 9,
      employeeNo: 'A009',
      employeeName: '삭제 대상',
      group: UserGroup(id: 1, groupName: '관리자'),
      isActive: true,
      isDeleted: false,
      createdAt: DateTime(2024, 1, 3, 9),
      updatedAt: DateTime(2024, 1, 4, 12),
    );

    await tester.pumpWidget(buildTestApp(const SizedBox.shrink()));
    final context = tester.element(find.byType(SizedBox));

    final dialogFuture = showUserDetailDialog(
      context: context,
      dateFormat: dateFormat,
      user: user,
      groupOptions: groups,
      onCreate: noopCreate,
      onUpdate: noopUpdate,
      onDelete: noopDelete,
      onRestore: noopRestore,
      onResetPassword: noopReset,
    );

    await tester.pumpAndSettle();

    await tester.tap(find.text('삭제').first);
    await tester.pumpAndSettle();

    expect(find.textContaining('삭제하면'), findsOneWidget);
    expect(find.widgetWithText(ShadButton, '삭제'), findsWidgets);

    await tester.tap(find.byTooltip('닫기'), warnIfMissed: false);
    await tester.pumpAndSettle();

    await dialogFuture;
  });
}
