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

import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/features/approvals/domain/entities/approval_template.dart';
import 'package:superport_v2/features/approvals/domain/repositories/approval_template_repository.dart';
import 'package:superport_v2/features/approvals/request/presentation/controllers/approval_request_controller.dart';
import 'package:superport_v2/features/approvals/request/presentation/widgets/approval_template_picker.dart';

class _MockApprovalTemplateRepository extends Mock
    implements ApprovalTemplateRepository {}

Widget _buildApp(Widget child) {
  return MaterialApp(
    home: ShadTheme(
      data: ShadThemeData(
        colorScheme: const ShadSlateColorScheme.light(),
        brightness: Brightness.light,
      ),
      child: Scaffold(body: child),
    ),
  );
}

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  late _MockApprovalTemplateRepository repository;

  setUp(() {
    repository = _MockApprovalTemplateRepository();
  });

  testWidgets('템플릿을 선택해 적용하면 단계가 컨트롤러에 반영된다', (tester) async {
    final view = tester.view;
    view.physicalSize = const Size(1280, 800);
    view.devicePixelRatio = 1.0;
    addTearDown(() {
      view.resetPhysicalSize();
      view.resetDevicePixelRatio();
    });

    final controller = ApprovalRequestController();
    final template = ApprovalTemplate(
      id: 1,
      code: 'AP-RENTAL',
      name: '입고 결재 템플릿',
      isActive: true,
      steps: const [],
      updatedAt: DateTime.utc(2025, 1, 1),
      createdBy: ApprovalTemplateAuthor(
        id: 7,
        employeeNo: 'EMP-7',
        name: '관리자',
      ),
    );
    final templateDetail = template.copyWith(
      steps: [
        ApprovalTemplateStep(
          id: 10,
          stepOrder: 1,
          approver: ApprovalTemplateApprover(
            id: 101,
            employeeNo: 'EMP-101',
            name: '1차 승인자',
          ),
          note: '재고 확인',
        ),
        ApprovalTemplateStep(
          id: 11,
          stepOrder: 2,
          approver: ApprovalTemplateApprover(
            id: 102,
            employeeNo: 'EMP-102',
            name: '최종 승인자',
          ),
          note: '승인 처리',
        ),
      ],
    );

    when(
      () => repository.list(
        page: any(named: 'page'),
        pageSize: any(named: 'pageSize'),
        isActive: any(named: 'isActive'),
      ),
    ).thenAnswer(
      (_) async => PaginatedResult<ApprovalTemplate>(
        items: [template],
        page: 1,
        pageSize: 30,
        total: 1,
      ),
    );
    when(
      () => repository.fetchDetail(
        template.id,
        includeSteps: any(named: 'includeSteps'),
      ),
    ).thenAnswer((_) async => templateDetail);

    final applied = <ApprovalTemplate>[];
    controller.setTemplateSnapshot(
      ApprovalTemplateSnapshot(
        templateId: template.id,
        updatedAt: template.updatedAt,
      ),
    );

    await tester.pumpWidget(
      _buildApp(
        ApprovalTemplatePicker(
          controller: controller,
          repository: repository,
          onTemplateApplied: applied.add,
        ),
      ),
    );
    await tester.pump();
    await tester.pumpAndSettle();

    final applyButton = find.widgetWithText(ShadButton, '템플릿 적용');
    expect(tester.widget<ShadButton>(applyButton).onPressed, isNotNull);

    await tester.tap(applyButton);
    await tester.pumpAndSettle();

    expect(controller.steps, hasLength(2));
    expect(controller.steps.first.approver.name, '1차 승인자');
    expect(controller.steps.last.approver.name, '최종 승인자');
    expect(applied.single.id, templateDetail.id);
  });
}
