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

import '../../../../../helpers/tester_extensions.dart';
import 'package:superport_v2/core/common/models/paginated_result.dart';
import 'package:superport_v2/features/masters/customer/domain/entities/customer.dart';
import 'package:superport_v2/features/masters/customer/domain/repositories/customer_repository.dart';
import 'package:superport_v2/features/masters/customer/presentation/pages/customer_page.dart';

class _MockCustomerRepository extends Mock implements CustomerRepository {}

class _FakeCustomerInput extends Fake implements CustomerInput {}

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();

  setUpAll(() {
    registerFallbackValue(_FakeCustomerInput());
  });

  tearDown(() async {
    await GetIt.I.reset();
    dotenv.clean();
  });

  testWidgets('플래그 Off 시 스펙 화면 유지', (tester) async {
    dotenv.testLoad(fileInput: 'FEATURE_CUSTOMERS_ENABLED=false\n');

    await tester.pumpWidget(
      _buildApp(CustomerPage(routeUri: Uri(path: '/masters/customers'))),
    );
    await tester.pump();

    expect(find.text('회사(고객사) 관리'), findsOneWidget);
    expect(find.text('테이블 리스트'), findsOneWidget);
  });

  group('플래그 On', () {
    late _MockCustomerRepository repository;

    setUp(() {
      dotenv.testLoad(fileInput: 'FEATURE_CUSTOMERS_ENABLED=true\n');
      repository = _MockCustomerRepository();
      GetIt.I.registerLazySingleton<CustomerRepository>(() => repository);
    });

    testWidgets('목록 조회 후 테이블 렌더', (tester) async {
      when(
        () => repository.list(
          page: any(named: 'page'),
          pageSize: any(named: 'pageSize'),
          query: any(named: 'query'),
          isPartner: any(named: 'isPartner'),
          isGeneral: any(named: 'isGeneral'),
          isActive: any(named: 'isActive'),
        ),
      ).thenAnswer(
        (_) async => PaginatedResult<Customer>(
          items: [
            Customer(
              id: 1,
              customerCode: 'C-001',
              customerName: '슈퍼포트',
              isPartner: true,
              isGeneral: false,
              email: 'partner@superport.com',
            ),
          ],
          page: 1,
          pageSize: 20,
          total: 1,
        ),
      );

      await tester.pumpWidget(
        _buildApp(CustomerPage(routeUri: Uri(path: '/masters/customers'))),
      );
      await tester.pumpAndSettle();

      expect(find.text('C-001'), findsOneWidget);
      verify(
        () => repository.list(
          page: 1,
          pageSize: 20,
          query: null,
          isPartner: null,
          isGeneral: null,
          isActive: null,
        ),
      ).called(1);
    });

    testWidgets('폼 검증: 필수값 누락 시 경고', (tester) async {
      when(
        () => repository.list(
          page: any(named: 'page'),
          pageSize: any(named: 'pageSize'),
          query: any(named: 'query'),
          isPartner: any(named: 'isPartner'),
          isGeneral: any(named: 'isGeneral'),
          isActive: any(named: 'isActive'),
        ),
      ).thenAnswer(
        (_) async => PaginatedResult<Customer>(
          items: const [],
          page: 1,
          pageSize: 20,
          total: 0,
        ),
      );

      await tester.pumpWidget(
        _buildApp(CustomerPage(routeUri: Uri(path: '/masters/customers'))),
      );
      await tester.pumpAndSettle();

      await tester.tap(find.text('신규 등록'));
      await tester.pumpAndSettle();
      await tester.tapShadButton('등록', settle: false);
      await tester.pump();

      expect(find.text('고객사코드를 입력하세요.'), findsOneWidget);
      expect(find.text('고객사명을 입력하세요.'), findsOneWidget);
    });

    testWidgets('우편번호를 수동 입력하면 검색 안내를 노출한다', (tester) async {
      when(
        () => repository.list(
          page: any(named: 'page'),
          pageSize: any(named: 'pageSize'),
          query: any(named: 'query'),
          isPartner: any(named: 'isPartner'),
          isGeneral: any(named: 'isGeneral'),
          isActive: any(named: 'isActive'),
        ),
      ).thenAnswer(
        (_) async => PaginatedResult<Customer>(
          items: const [],
          page: 1,
          pageSize: 20,
          total: 0,
        ),
      );

      await tester.pumpWidget(
        _buildApp(CustomerPage(routeUri: Uri(path: '/masters/customers'))),
      );
      await tester.pumpAndSettle();

      await tester.tap(find.text('신규 등록'));
      await tester.pumpAndSettle();

      final fields = find.descendant(
        of: find.byType(Dialog),
        matching: find.byType(EditableText),
      );

      await tester.enterText(fields.at(0), 'C-200');
      await tester.enterText(fields.at(1), '검색 필요 고객');
      await tester.enterText(fields.at(4), '06000');

      await tester.tapShadButton('등록', settle: false);
      await tester.pump();

      expect(find.text('검색 버튼을 눌러 주소를 선택하세요.'), findsOneWidget);
    });

    testWidgets('신규 등록 성공 시 repository.create 호출', (tester) async {
      var listCallCount = 0;
      when(
        () => repository.list(
          page: any(named: 'page'),
          pageSize: any(named: 'pageSize'),
          query: any(named: 'query'),
          isPartner: any(named: 'isPartner'),
          isGeneral: any(named: 'isGeneral'),
          isActive: any(named: 'isActive'),
        ),
      ).thenAnswer((_) async {
        listCallCount += 1;
        if (listCallCount == 1) {
          return PaginatedResult<Customer>(
            items: const [],
            page: 1,
            pageSize: 20,
            total: 0,
          );
        }
        return PaginatedResult<Customer>(
          items: [
            Customer(
              id: 2,
              customerCode: 'C-100',
              customerName: '신규 고객',
              isPartner: true,
              isGeneral: true,
            ),
          ],
          page: 1,
          pageSize: 20,
          total: 1,
        );
      });

      CustomerInput? capturedInput;
      when(() => repository.create(any())).thenAnswer((invocation) async {
        capturedInput = invocation.positionalArguments.first as CustomerInput;
        return Customer(
          id: 2,
          customerCode: capturedInput!.customerCode,
          customerName: capturedInput!.customerName,
          contactName: capturedInput!.contactName,
          isPartner: capturedInput!.isPartner,
          isGeneral: capturedInput!.isGeneral,
        );
      });

      await tester.pumpWidget(
        _buildApp(CustomerPage(routeUri: Uri(path: '/masters/customers'))),
      );
      await tester.pumpAndSettle();

      await tester.tap(find.text('신규 등록'));
      await tester.pumpAndSettle();

      final dialog = find.byType(Dialog);
      final editableTexts = find.descendant(
        of: dialog,
        matching: find.byType(EditableText),
      );

      await tester.enterText(editableTexts.at(0), 'C-100');
      await tester.enterText(editableTexts.at(1), '신규 고객');
      await tester.enterText(editableTexts.at(2), '홍길동');
      await tester.enterText(editableTexts.at(3), 'new@superport.com');
      await tester.enterText(editableTexts.at(4), '02-0000-0000');

      // 유형 체크박스: 기본값 partner=false, general=true. partner on 추가
      await tester.tap(find.text('파트너'), warnIfMissed: false);
      await tester.pump();

      await tester.tapShadButton('등록');

      expect(capturedInput, isNotNull);
      expect(capturedInput?.customerCode, 'C-100');
      expect(capturedInput?.contactName, '홍길동');
      expect(find.byType(Dialog), findsNothing);
      expect(find.text('C-100'), findsOneWidget);
      verify(() => repository.create(any())).called(1);
    });

    testWidgets('좁은 폭에서도 오버플로 없이 렌더링', (tester) async {
      when(
        () => repository.list(
          page: any(named: 'page'),
          pageSize: any(named: 'pageSize'),
          query: any(named: 'query'),
          isPartner: any(named: 'isPartner'),
          isGeneral: any(named: 'isGeneral'),
          isActive: any(named: 'isActive'),
        ),
      ).thenAnswer(
        (_) async => PaginatedResult<Customer>(
          items: [
            Customer(
              id: 1,
              customerCode: 'C-SMALL',
              customerName: '좁은 화면 고객',
              isPartner: false,
              isGeneral: true,
            ),
          ],
          page: 1,
          pageSize: 20,
          total: 1,
        ),
      );

      await tester.pumpWidget(
        _buildApp(
          Center(
            child: SizedBox(
              width: 320,
              child: CustomerPage(routeUri: Uri(path: '/masters/customers')),
            ),
          ),
        ),
      );
      await tester.pumpAndSettle();

      expect(tester.takeException(), isNull);
    });
  });
}
