<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use App\Models\User;
use Modules\Academic\Models\ExamType;
use Modules\Academic\Models\AcademicYear;

class ExamTypeDropdownTest extends DuskTestCase
{

    /**
     * Test dropdown functionality specifically
     * @test
     */
    public function test_exam_type_dropdown_functionality()
    {
        $this->browse(function (Browser $browser) {
            // Use existing admin user
            $adminUser = User::where('role', 'admin')->first();
            if (!$adminUser) {
                $adminUser = User::create([
                    'email' => 'admin@dropdown.test',
                    'role' => 'admin',
                    'name' => 'Admin User',
                    'password' => bcrypt('password'),
                ]);
            }

            // Use existing academic year
            $academicYear = AcademicYear::first();
            if (!$academicYear) {
                $academicYear = AcademicYear::create([
                    'name' => '2024-2025 Test Year',
                    'start_date' => '2024-09-01',
                    'end_date' => '2025-06-30',
                    'is_current' => true,
                    'status' => 'active',
                ]);
            }

            // Use existing exam type or create one
            $examType = ExamType::first();
            if (!$examType) {
                $examType = ExamType::create([
                    'name' => 'Test Midterm Exam',
                    'description' => 'Test midterm examination',
                    'academic_year_id' => $academicYear->id,
                    'status' => 'active',
                ]);
            }

            echo "\n=== TESTING EXAM TYPE DROPDOWN FUNCTIONALITY ===\n";
            echo "Admin User: {$adminUser->email}\n";
            echo "Exam Type: {$examType->name}\n";
            echo "Academic Year: {$academicYear->name}\n";
            echo "================================================\n";

            $browser->loginAs($adminUser)
                    ->visit('/exam-types')
                    ->waitFor('body', 15)
                    ->pause(2000); // Wait for page to fully load

            // Check if we can see the exam types page
            echo "Current URL: " . $browser->driver->getCurrentURL() . "\n";
            echo "Page Title: " . $browser->driver->getTitle() . "\n";

            // Check for any JavaScript errors
            $logs = $browser->driver->manage()->getLog('browser');
            if (!empty($logs)) {
                echo "=== BROWSER CONSOLE LOGS ===\n";
                foreach ($logs as $log) {
                    echo "[{$log['level']}] {$log['message']}\n";
                }
                echo "============================\n";
            }

            // Look for the exam type in the table
            if ($browser->seeIn('body', $examType->name)) {
                echo "✓ Found exam type '{$examType->name}' in the table\n";

                // Try to find and click the dropdown button
                try {
                    // Look for dropdown trigger (could be button, link, or icon)
                    $dropdownSelectors = [
                        'button[data-dropdown-toggle]',
                        '.dropdown-toggle',
                        '[data-bs-toggle="dropdown"]',
                        '.actions-dropdown',
                        'button:contains("⋮")',
                        'button:contains("...")',
                        '.table tbody tr:first-child td:last-child button',
                        '.table tbody tr:first-child td:last-child .dropdown-toggle',
                    ];

                    $dropdownFound = false;
                    foreach ($dropdownSelectors as $selector) {
                        try {
                            if ($browser->element($selector)) {
                                echo "✓ Found dropdown with selector: {$selector}\n";
                                $browser->click($selector)->pause(1000);
                                $dropdownFound = true;
                                break;
                            }
                        } catch (\Exception $e) {
                            // Continue to next selector
                        }
                    }

                    if (!$dropdownFound) {
                        echo "✗ Could not find dropdown button\n";
                        echo "Available elements in last column:\n";
                        $elements = $browser->driver->findElements(\Facebook\WebDriver\WebDriverBy::cssSelector('.table tbody tr:first-child td:last-child *'));
                        foreach ($elements as $element) {
                            echo "  - Tag: {$element->getTagName()}, Text: '{$element->getText()}', Class: '{$element->getAttribute('class')}'\n";
                        }
                    } else {
                        // Try to click edit option
                        $editSelectors = [
                            'a:contains("Edit")',
                            'button:contains("Edit")',
                            '[href*="edit"]',
                            '.edit-btn',
                            '.dropdown-item:contains("Edit")',
                        ];

                        $editFound = false;
                        foreach ($editSelectors as $selector) {
                            try {
                                if ($browser->element($selector)) {
                                    echo "✓ Found edit option with selector: {$selector}\n";

                                    // Get the href before clicking
                                    $editElement = $browser->driver->findElement(\Facebook\WebDriver\WebDriverBy::cssSelector($selector));
                                    $href = $editElement->getAttribute('href');
                                    echo "Edit URL: {$href}\n";

                                    // Click and capture any errors
                                    $browser->click($selector)->pause(2000);

                                    // Check current URL after click
                                    echo "URL after edit click: " . $browser->driver->getCurrentURL() . "\n";

                                    // Check for new console errors
                                    $newLogs = $browser->driver->manage()->getLog('browser');
                                    if (!empty($newLogs)) {
                                        echo "=== NEW CONSOLE ERRORS AFTER EDIT CLICK ===\n";
                                        foreach ($newLogs as $log) {
                                            if ($log['level'] === 'SEVERE') {
                                                echo "[ERROR] {$log['message']}\n";
                                            }
                                        }
                                        echo "==========================================\n";
                                    }

                                    $editFound = true;
                                    break;
                                }
                            } catch (\Exception $e) {
                                echo "Error with selector {$selector}: " . $e->getMessage() . "\n";
                            }
                        }

                        if (!$editFound) {
                            echo "✗ Could not find edit option in dropdown\n";
                        }
                    }

                } catch (\Exception $e) {
                    echo "✗ Error testing dropdown: " . $e->getMessage() . "\n";
                }

            } else {
                echo "✗ Could not find exam type '{$examType->name}' in the table\n";
                echo "Page content preview:\n";
                echo substr($browser->driver->getPageSource(), 0, 1000) . "...\n";
            }
        });
    }
}
