<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Modules\Academic\Models\Subject;
use Modules\Academic\Models\AcademicYear;
use Modules\Academic\Models\Classroom;
use App\Models\User;

class ConsoleErrorDebugTest extends DuskTestCase
{
    use RefreshDatabase;

    protected $admin;

    protected function setUp(): void
    {
        parent::setUp();

        // Create admin user (skip permissions for now)
        $this->admin = User::factory()->admin()->create([
            'email' => 'admin@test.com',
            'password' => bcrypt('password')
        ]);
    }

    /** @test */
    public function it_captures_console_errors_on_subjects_page()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🔍 DEBUGGING SUBJECTS PAGE...\n";
            echo "=" . str_repeat("=", 50) . "\n";

            $browser->loginAs($this->admin)
                    ->visit('/subjects')
                    ->waitFor('body', 10);

            // Capture console logs
            $logs = $browser->driver->manage()->getLog('browser');

            echo "📋 CONSOLE LOGS:\n";
            echo "-" . str_repeat("-", 30) . "\n";

            if (empty($logs)) {
                echo "✅ No console logs found\n";
            } else {
                foreach ($logs as $log) {
                    $level = $log['level'];
                    $message = $log['message'];
                    $timestamp = date('H:i:s', $log['timestamp'] / 1000);

                    $icon = match($level) {
                        'SEVERE' => '❌',
                        'WARNING' => '⚠️',
                        'INFO' => 'ℹ️',
                        default => '📝'
                    };

                    echo "{$icon} [{$level}] {$timestamp}: {$message}\n";
                }
            }

            // Check if page loaded successfully
            echo "\n📄 PAGE STATUS:\n";
            echo "-" . str_repeat("-", 30) . "\n";

            try {
                $browser->assertSee('Subjects');
                echo "✅ Page title found\n";
            } catch (\Exception $e) {
                echo "❌ Page title not found: {$e->getMessage()}\n";
            }

            // Check if ToastContainer is in DOM
            echo "\n🍞 TOAST CONTAINER CHECK:\n";
            echo "-" . str_repeat("-", 30) . "\n";

            $toastContainerExists = $browser->element('.fixed.top-4.right-4') !== null;
            if ($toastContainerExists) {
                echo "✅ Toast container found in DOM\n";
            } else {
                echo "❌ Toast container not found in DOM\n";
            }

            // Check for Vue app
            echo "\n⚡ VUE APP CHECK:\n";
            echo "-" . str_repeat("-", 30) . "\n";

            $vueExists = $browser->script('return typeof window.Vue !== "undefined"')[0];
            if ($vueExists) {
                echo "✅ Vue is available globally\n";
            } else {
                echo "❌ Vue not available globally\n";
            }

            // Check for Inertia
            $inertiaExists = $browser->script('return typeof window.Inertia !== "undefined"')[0];
            if ($inertiaExists) {
                echo "✅ Inertia is available globally\n";
            } else {
                echo "❌ Inertia not available globally\n";
            }
        });
    }

    /** @test */
    public function it_tests_toast_functionality_with_console_monitoring()
    {
        // Create a test subject first
        $subject = Subject::factory()->create([
            'name' => 'Test Subject for Toast',
            'code' => 'TOAST001'
        ]);

        $this->browse(function (Browser $browser) use ($subject) {
            echo "\n🍞 TESTING TOAST FUNCTIONALITY...\n";
            echo "=" . str_repeat("=", 50) . "\n";

            $browser->loginAs($this->admin)
                    ->visit('/subjects')
                    ->waitFor('table', 10);

            // Clear previous logs
            $browser->driver->manage()->getLog('browser');

            echo "🗑️ TESTING DELETE FUNCTIONALITY...\n";
            echo "-" . str_repeat("-", 30) . "\n";

            try {
                // Look for delete button - try multiple selectors
                $deleteButtonFound = false;

                // Try to find dropdown menu first
                if ($browser->element('[data-testid="dropdown-trigger"]')) {
                    $browser->click('[data-testid="dropdown-trigger"]')
                            ->pause(500);
                    echo "✅ Dropdown menu opened\n";

                    if ($browser->element('button:contains("Delete")')) {
                        $browser->click('button:contains("Delete")')
                                ->pause(1000);
                        $deleteButtonFound = true;
                        echo "✅ Delete button clicked\n";
                    }
                }

                if (!$deleteButtonFound) {
                    // Try direct delete button
                    $deleteButtons = $browser->elements('button[onclick*="delete"]');
                    if (!empty($deleteButtons)) {
                        $browser->click('button[onclick*="delete"]:first')
                                ->pause(1000);
                        $deleteButtonFound = true;
                        echo "✅ Direct delete button clicked\n";
                    }
                }

                if ($deleteButtonFound) {
                    // Handle confirmation dialog if it appears
                    try {
                        $browser->acceptDialog();
                        echo "✅ Confirmation dialog accepted\n";
                    } catch (\Exception $e) {
                        echo "ℹ️ No confirmation dialog found\n";
                    }

                    // Wait for potential toast
                    $browser->pause(2000);

                    // Check for toast elements
                    $toastFound = false;
                    $toastSelectors = [
                        '.toast',
                        '[class*="toast"]',
                        '.fixed.top-4.right-4 > div',
                        '[role="alert"]',
                        '.bg-green-50',
                        '.bg-red-50'
                    ];

                    foreach ($toastSelectors as $selector) {
                        if ($browser->element($selector)) {
                            echo "✅ Toast element found with selector: {$selector}\n";
                            $toastFound = true;
                            break;
                        }
                    }

                    if (!$toastFound) {
                        echo "❌ No toast elements found\n";
                    }
                } else {
                    echo "❌ No delete button found\n";
                }

            } catch (\Exception $e) {
                echo "❌ Error during delete test: {$e->getMessage()}\n";
            }

            // Capture console logs after delete attempt
            $logs = $browser->driver->manage()->getLog('browser');

            echo "\n📋 CONSOLE LOGS AFTER DELETE:\n";
            echo "-" . str_repeat("-", 30) . "\n";

            if (empty($logs)) {
                echo "✅ No new console logs\n";
            } else {
                foreach ($logs as $log) {
                    $level = $log['level'];
                    $message = $log['message'];

                    $icon = match($level) {
                        'SEVERE' => '❌',
                        'WARNING' => '⚠️',
                        'INFO' => 'ℹ️',
                        default => '📝'
                    };

                    echo "{$icon} [{$level}]: {$message}\n";
                }
            }
        });
    }

    /** @test */
    public function it_tests_create_form_with_console_monitoring()
    {
        $this->browse(function (Browser $browser) {
            echo "\n📝 TESTING CREATE FORM...\n";
            echo "=" . str_repeat("=", 50) . "\n";

            $browser->loginAs($this->admin)
                    ->visit('/subjects/create')
                    ->waitFor('form', 10);

            // Clear previous logs
            $browser->driver->manage()->getLog('browser');

            echo "📋 FILLING FORM...\n";
            echo "-" . str_repeat("-", 30) . "\n";

            try {
                $browser->type('name', 'Test Subject Console')
                        ->type('code', 'CONSOLE001')
                        ->type('description', 'Test Description')
                        ->check('is_active')
                        ->press('Create Subject')
                        ->waitForLocation('/subjects', 15);

                echo "✅ Form submitted successfully\n";
                echo "✅ Redirected to subjects index\n";

                // Wait for potential toast
                $browser->pause(2000);

                // Check for success message or toast
                $successFound = false;

                // Check for flash message
                if ($browser->element('.bg-green-50')) {
                    echo "✅ Success flash message found\n";
                    $successFound = true;
                }

                // Check for toast
                if ($browser->element('.toast, [class*="toast"]')) {
                    echo "✅ Success toast found\n";
                    $successFound = true;
                }

                if (!$successFound) {
                    echo "❌ No success indication found\n";
                }

            } catch (\Exception $e) {
                echo "❌ Error during form submission: {$e->getMessage()}\n";
            }

            // Capture console logs after form submission
            $logs = $browser->driver->manage()->getLog('browser');

            echo "\n📋 CONSOLE LOGS AFTER FORM SUBMISSION:\n";
            echo "-" . str_repeat("-", 30) . "\n";

            if (empty($logs)) {
                echo "✅ No console errors during form submission\n";
            } else {
                foreach ($logs as $log) {
                    $level = $log['level'];
                    $message = $log['message'];

                    $icon = match($level) {
                        'SEVERE' => '❌',
                        'WARNING' => '⚠️',
                        'INFO' => 'ℹ️',
                        default => '📝'
                    };

                    echo "{$icon} [{$level}]: {$message}\n";
                }
            }
        });
    }
}
