import 'package:feature_wordpress/feature_wordpress.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

// ── Helpers ───────────────────────────────────────────────────────────────────

Widget _wrap(Widget child) => MaterialApp(home: Scaffold(body: child));

/// Opens the dialog and returns the result.
Future<CreateProductDialogResult?> _openDialog(
  WidgetTester tester, {
  List<ProductCategory> categories = const [],
}) async {
  CreateProductDialogResult? result;

  await tester.pumpWidget(
    MaterialApp(
      home: Builder(
        builder: (context) => TextButton(
          onPressed: () async {
            result = await showCreateProductDialog(context, categories: categories);
          },
          child: const Text('Open'),
        ),
      ),
    ),
  );

  await tester.tap(find.text('Open'));
  await tester.pumpAndSettle();

  return result;
}

// ── Tests ─────────────────────────────────────────────────────────────────────

void main() {
  group('CreateProductDialog', () {
    testWidgets('renders title and required fields', (tester) async {
      await _openDialog(tester);

      expect(find.text('New Product'), findsOneWidget);
      expect(find.text('Product Name *'), findsOneWidget);
      expect(find.text('Price *'), findsOneWidget);
      expect(find.text('SKU'), findsOneWidget);
      expect(find.text('Description'), findsOneWidget);
    });

    testWidgets('shows Cancel and Create Product buttons', (tester) async {
      await _openDialog(tester);

      expect(find.text('Cancel'), findsOneWidget);
      expect(find.text('Create Product'), findsOneWidget);
    });

    testWidgets('Cancel closes dialog and returns null', (tester) async {
      CreateProductDialogResult? result;

      await tester.pumpWidget(
        MaterialApp(
          home: Builder(
            builder: (context) => TextButton(
              onPressed: () async {
                result = await showCreateProductDialog(context, categories: []);
              },
              child: const Text('Open'),
            ),
          ),
        ),
      );

      await tester.tap(find.text('Open'));
      await tester.pumpAndSettle();

      await tester.tap(find.text('Cancel'));
      await tester.pumpAndSettle();

      expect(result, isNull);
      expect(find.text('New Product'), findsNothing);
    });

    testWidgets('shows name error when submitted with empty name', (tester) async {
      await _openDialog(tester);

      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();

      expect(find.text('Product name is required.'), findsOneWidget);
      // Dialog stays open.
      expect(find.text('New Product'), findsOneWidget);
    });

    testWidgets('shows price error when submitted with invalid price', (tester) async {
      await _openDialog(tester);

      await tester.enterText(find.widgetWithText(TextField, 'Product Name *'), 'My Product');
      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();

      expect(find.text('Enter a valid price (e.g. 12.99).'), findsOneWidget);
      expect(find.text('New Product'), findsOneWidget);
    });

    testWidgets('submits with valid name and price and returns result', (tester) async {
      CreateProductDialogResult? result;

      await tester.pumpWidget(
        MaterialApp(
          home: Builder(
            builder: (context) => TextButton(
              onPressed: () async {
                result = await showCreateProductDialog(context, categories: []);
              },
              child: const Text('Open'),
            ),
          ),
        ),
      );

      await tester.tap(find.text('Open'));
      await tester.pumpAndSettle();

      await tester.enterText(find.widgetWithText(TextField, 'Product Name *'), 'Floral Bowl Cozy');
      await tester.enterText(find.widgetWithText(TextField, 'Price *'), '12.99');
      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();

      expect(result, isNotNull);
      expect(result!.name, 'Floral Bowl Cozy');
      expect(result!.price, 12.99);
      expect(result!.status, PublishStatus.draft);
      expect(result!.categoryId, isNull);
    });

    testWidgets('submits with SKU and description', (tester) async {
      CreateProductDialogResult? result;

      await tester.pumpWidget(
        MaterialApp(
          home: Builder(
            builder: (context) => TextButton(
              onPressed: () async {
                result = await showCreateProductDialog(context, categories: []);
              },
              child: const Text('Open'),
            ),
          ),
        ),
      );

      await tester.tap(find.text('Open'));
      await tester.pumpAndSettle();

      await tester.enterText(find.widgetWithText(TextField, 'Product Name *'), 'Cozy');
      await tester.enterText(find.widgetWithText(TextField, 'Price *'), '9.99');
      await tester.enterText(find.widgetWithText(TextField, 'SKU'), 'BC-001');
      await tester.enterText(find.widgetWithText(TextField, 'Description'), 'A nice cozy');
      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();

      expect(result!.sku, 'BC-001');
      expect(result!.description, 'A nice cozy');
    });

    testWidgets('does not show category dropdown when no categories provided', (tester) async {
      await _openDialog(tester, categories: []);

      expect(find.text('Category'), findsNothing);
    });

    testWidgets('shows category dropdown when categories are provided', (tester) async {
      const cats = [
        ProductCategory(id: 1, name: 'Bowl Cozies', slug: 'bowl-cozies', parentId: 0, count: 3),
        ProductCategory(id: 2, name: 'Coasters', slug: 'coasters', parentId: 0, count: 1),
      ];

      await _openDialog(tester, categories: cats);

      expect(find.text('Category'), findsOneWidget);
    });

    testWidgets('initial status defaults to draft', (tester) async {
      CreateProductDialogResult? result;

      await tester.pumpWidget(
        MaterialApp(
          home: Builder(
            builder: (context) => TextButton(
              onPressed: () async {
                result = await showCreateProductDialog(context, categories: []);
              },
              child: const Text('Open'),
            ),
          ),
        ),
      );

      await tester.tap(find.text('Open'));
      await tester.pumpAndSettle();

      await tester.enterText(find.widgetWithText(TextField, 'Product Name *'), 'Test');
      await tester.enterText(find.widgetWithText(TextField, 'Price *'), '5.00');
      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();

      expect(result!.status, PublishStatus.draft);
    });

    testWidgets('name error clears when user starts typing', (tester) async {
      await _openDialog(tester);

      // Trigger error.
      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();
      expect(find.text('Product name is required.'), findsOneWidget);

      // Start typing.
      await tester.enterText(find.widgetWithText(TextField, 'Product Name *'), 'A');
      await tester.pumpAndSettle();
      expect(find.text('Product name is required.'), findsNothing);
    });

    testWidgets('price error clears when user starts typing', (tester) async {
      await _openDialog(tester);

      await tester.enterText(find.widgetWithText(TextField, 'Product Name *'), 'Test');
      await tester.tap(find.text('Create Product'));
      await tester.pumpAndSettle();
      expect(find.text('Enter a valid price (e.g. 12.99).'), findsOneWidget);

      await tester.enterText(find.widgetWithText(TextField, 'Price *'), '1');
      await tester.pumpAndSettle();
      expect(find.text('Enter a valid price (e.g. 12.99).'), findsNothing);
    });
  });

  group('CreateProductDialog — standalone widget', () {
    testWidgets('renders inside a MaterialApp without error', (tester) async {
      await tester.pumpWidget(
        _wrap(
          Builder(
            builder: (context) => TextButton(
              onPressed: () => showDialog<CreateProductDialogResult>(
                context: context,
                builder: (_) => const CreateProductDialog(availableCategories: []),
              ),
              child: const Text('Open'),
            ),
          ),
        ),
      );

      await tester.tap(find.text('Open'));
      await tester.pumpAndSettle();

      expect(find.byType(CreateProductDialog), findsOneWidget);
    });
  });
}
