import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart' as intl;
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:superport_v2/core/services/token_storage.dart';
import 'package:superport_v2/features/approvals/domain/entities/approval_template.dart';
import 'package:superport_v2/features/approvals/template/presentation/dialogs/approval_template_detail_dialog.dart';
import 'package:superport_v2/features/auth/application/auth_service.dart';
import 'package:superport_v2/features/auth/domain/entities/auth_session.dart';
import 'package:superport_v2/features/auth/domain/entities/authenticated_user.dart';
import 'package:superport_v2/features/auth/domain/entities/login_request.dart';
import 'package:superport_v2/features/auth/domain/repositories/auth_repository.dart';
import 'package:superport_v2/widgets/components/superport_detail_dialog.dart';

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

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  final dateFormat = intl.DateFormat('yyyy-MM-dd HH:mm');

  late ApprovalTemplate sampleTemplate;
  late ApprovalTemplateApprover approver1;
  late ApprovalTemplateApprover approver2;

  setUp(() {
    final getIt = GetIt.I;
    if (!getIt.isRegistered<AuthService>()) {
      getIt.registerSingleton<AuthService>(
        _StubAuthService(
          AuthSession(
            accessToken: 'access',
            refreshToken: 'refresh',
            expiresAt: DateTime.now().add(const Duration(hours: 1)),
            user: const AuthenticatedUser(
              id: 1,
              name: '테스터',
              employeeNo: 'E001',
            ),
            permissions: const [],
          ),
        ),
      );
    }

    approver1 = ApprovalTemplateApprover(
      id: 501,
      employeeNo: 'E501',
      name: '1차 승인자',
    );
    approver2 = ApprovalTemplateApprover(
      id: 502,
      employeeNo: 'E502',
      name: '2차 승인자',
    );

    sampleTemplate = ApprovalTemplate(
      id: 10,
      code: 'TEMP-10',
      name: '자산 구매 결재',
      description: '자산 구매 시 사용하는 기본 결재선',
      note: '월별로 재검토 필요',
      isActive: true,
      createdAt: DateTime(2024, 1, 1, 9),
      updatedAt: DateTime(2024, 1, 10, 10),
      steps: [
        ApprovalTemplateStep(
          id: 1001,
          stepOrder: 1,
          approver: approver1,
          note: '팀 리더 확인',
        ),
        ApprovalTemplateStep(
          id: 1002,
          stepOrder: 2,
          approver: approver2,
          note: '경영진 승인',
        ),
      ],
    );
  });

  tearDown(() {
    final getIt = GetIt.I;
    if (getIt.isRegistered<AuthService>()) {
      getIt.unregister<AuthService>();
    }
  });

  testWidgets('템플릿 상세 다이얼로그는 요약과 메타데이터를 info panel에 표시한다', (tester) async {
    await tester.pumpWidget(buildTestApp(const SizedBox.shrink()));
    final context = tester.element(find.byType(SizedBox));

    final resultFuture = showApprovalTemplateDetailDialog(
      context: context,
      dateFormat: dateFormat,
      template: sampleTemplate,
      onCreate: (_, __) => Future.value(null),
      onUpdate: (_, __, ___) => Future.value(sampleTemplate),
      onDelete: (_) => Future.value(false),
      onRestore: (_) => Future.value(null),
    );

    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    expect(find.text('결재 템플릿 상세'), findsAtLeastNWidgets(1));
    expect(find.text(sampleTemplate.name), findsAtLeastNWidgets(1));
    expect(find.text('단계'), findsOneWidget);
    expect(find.text('코드'), findsWidgets);
    expect(find.text('TEMP-10'), findsWidgets);
    expect(find.text('상태'), findsWidgets);
    expect(find.text('생성일시'), findsWidgets);

    expect(find.byType(SuperportDetailDialog), findsOneWidget);
    await tester.tap(find.byTooltip('닫기'), warnIfMissed: false);
    await tester.pump(const Duration(milliseconds: 100));
    expect(await resultFuture, isNull);
  });

  testWidgets('생성 모드에서 필수 정보를 입력하면 onCreate 콜백이 호출된다', (tester) async {
    final createdTemplates = <ApprovalTemplateInput>[];
    final createdSteps = <List<ApprovalTemplateStepInput>>[];

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

    final resultFuture = showApprovalTemplateDetailDialog(
      context: context,
      dateFormat: dateFormat,
      template: null,
      onCreate: (input, steps) async {
        createdTemplates.add(input);
        createdSteps.add(steps);
        return sampleTemplate.copyWith(name: input.name);
      },
      onUpdate: (_, __, ___) => Future.value(null),
      onDelete: (_) => Future.value(false),
      onRestore: (_) => Future.value(null),
    );

    await tester.pump();
    await tester.pumpAndSettle();

    await tester.enterText(
      find.byKey(const ValueKey('template_form_name')),
      '신규 결재 템플릿',
    );
    await tester.enterText(
      find.byKey(const ValueKey('template_step_0_order')),
      '1',
    );

    final approverFieldFinder = find.byKey(
      const ValueKey('template_step_0_approver'),
    );
    final approverFieldState = tester.state(approverFieldFinder) as dynamic;
    approverFieldState.widget.idController.text = approver1.id.toString();
    await tester.pump();

    final submitButton = tester.widget<ShadButton>(
      find.widgetWithText(ShadButton, '등록'),
    );
    expect(submitButton.onPressed, isNotNull);
    submitButton.onPressed!();
    await tester.pump();
    await tester.pumpAndSettle();
    expect(createdTemplates, isNotEmpty);

    final result = await resultFuture;
    expect(result, isNotNull);
    expect(result!.action, ApprovalTemplateDetailAction.created);
    expect(createdTemplates, hasLength(1));
    expect(createdTemplates.first.name, '신규 결재 템플릿');
    expect(createdSteps.single.first.approverId, approver1.id);
  });

  testWidgets('삭제 탭에서 삭제 버튼을 누르면 onDelete 콜백이 호출되어 결과가 반환된다', (tester) async {
    var deleteCalled = false;

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

    final resultFuture = showApprovalTemplateDetailDialog(
      context: context,
      dateFormat: dateFormat,
      template: sampleTemplate,
      onCreate: (_, __) => Future.value(null),
      onUpdate: (_, __, ___) => Future.value(sampleTemplate),
      onDelete: (_) async {
        deleteCalled = true;
        return true;
      },
      onRestore: (_) => Future.value(null),
    );

    await tester.pump();
    await tester.pumpAndSettle();

    final tabsFinder = find.descendant(
      of: find.byType(SuperportDetailDialog),
      matching: find.byType(ShadTabs<String>),
    );
    final tabsState = tester.state(tabsFinder);
    final controller =
        (tabsState as dynamic).controller as ShadTabsController<String>;
    controller.select('delete');
    await tester.pump(const Duration(milliseconds: 100));

    final deleteButtonFinder = find.byWidgetPredicate(
      (widget) =>
          widget is ShadButton &&
          widget.variant == ShadButtonVariant.destructive &&
          widget.child is Text &&
          (widget.child as Text).data == '삭제',
    );
    expect(deleteButtonFinder, findsOneWidget);
    final deleteButton = tester.widget<ShadButton>(deleteButtonFinder);
    expect(deleteButton.onPressed, isNotNull);
    deleteButton.onPressed!();
    await tester.pump();
    await tester.pump(const Duration(milliseconds: 100));

    final result = await resultFuture;
    expect(deleteCalled, isTrue);
    expect(result, isNotNull);
    expect(result!.action, ApprovalTemplateDetailAction.deleted);
  });
}

class _StubAuthService extends AuthService {
  _StubAuthService(this._session)
    : super(
        repository: _FakeAuthRepository(),
        tokenStorage: _FakeTokenStorage(),
      );

  final AuthSession _session;

  @override
  AuthSession? get session => _session;
}

class _FakeAuthRepository implements AuthRepository {
  @override
  Future<AuthSession> login(LoginRequest request) {
    throw UnimplementedError();
  }

  @override
  Future<AuthSession> refresh(String refreshToken) {
    throw UnimplementedError();
  }
}

class _FakeTokenStorage implements TokenStorage {
  String? access;
  String? refresh;

  @override
  Future<void> clear() async {
    access = null;
    refresh = null;
  }

  @override
  Future<String?> readAccessToken() async => access;

  @override
  Future<String?> readRefreshToken() async => refresh;

  @override
  Future<void> writeAccessToken(String? token) async {
    access = token;
  }

  @override
  Future<void> writeRefreshToken(String? token) async {
    refresh = token;
  }
}
