<?php

namespace Tests\Browser;

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

class ExamTypesModuleTest extends DuskTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        // Try to find existing admin user or create one
        $this->admin = User::where('email', 'admin@test.com')->first();

        if (!$this->admin) {
            $this->admin = User::factory()->create([
                'email' => 'admin@test.com',
                'role' => 'admin'
            ]);
        }
    }

    /**
     * Test admin can access exam types index page
     * @test
     */
    public function admin_can_access_exam_types_page()
    {
        $this->browse(function (Browser $browser) {
            echo "\n TESTING EXAM TYPES PAGE ACCESS\n";
            echo "===================================================\n";

            $browser->loginAs($this->admin);

            echo "✅ User logged in successfully\n";
            echo "   Visiting /exam-types...\n";

            $browser->visit('/exam-types');

            echo "   Current URL: " . $browser->driver->getCurrentURL() . "\n";

            // Wait a bit and check what's happening
            sleep(3);

            // Check for JavaScript errors first
            $logs = $browser->driver->manage()->getLog('browser');
            $jsErrors = array_filter($logs, function($log) {
                return $log['level'] === 'SEVERE';
            });

            if (empty($jsErrors)) {
                echo "✅ No JavaScript errors found\n";
            } else {
                echo "❌ JavaScript errors found:\n";
                foreach ($jsErrors as $error) {
                    echo "   - " . $error['message'] . "\n";
                }
            }

            // Check page title
            $title = $browser->driver->getTitle();
            echo "   Page title: " . $title . "\n";

            // Try to find any element on the page
            try {
                $browser->waitFor('html', 5);
                echo "✅ HTML element found\n";
            } catch (\Exception $e) {
                echo "❌ No HTML element found\n";
            }

            // Check if we can find the body
            try {
                $browser->waitFor('body', 5);
                echo "✅ Body element found\n";
            } catch (\Exception $e) {
                echo "❌ Body element not found: " . $e->getMessage() . "\n";
            }
        });
    }

    /**
     * Test admin can access create exam type page
     * @test
     */
    public function admin_can_access_create_exam_type_page()
    {
        $this->browse(function (Browser $browser) {
            echo "\n TESTING CREATE EXAM TYPE PAGE\n";
            echo "===================================================\n";

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

            // Check if page loaded successfully
            if (strpos($browser->driver->getCurrentURL(), '/exam-types/create') !== false) {
                echo "✅ Create Exam Type page loaded successfully\n";
            } else {
                echo "❌ Failed to load Create Exam Type page\n";
                echo "   Current URL: " . $browser->driver->getCurrentURL() . "\n";
            }

            // Check for JavaScript errors
            $logs = $browser->driver->manage()->getLog('browser');
            $jsErrors = array_filter($logs, function($log) {
                return $log['level'] === 'SEVERE';
            });

            if (empty($jsErrors)) {
                echo "✅ No JavaScript errors found\n";
            } else {
                echo "❌ JavaScript errors found:\n";
                foreach ($jsErrors as $error) {
                    echo "   - " . $error['message'] . "\n";
                }
            }
        });
    }

    /**
     * Test exam types page has required elements
     * @test
     */
    public function exam_types_page_has_required_elements()
    {
        $this->browse(function (Browser $browser) {
            echo "\n TESTING EXAM TYPES PAGE ELEMENTS\n";
            echo "===================================================\n";

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

            // Check for Add Exam Type button
            try {
                $browser->waitFor('button:contains("Add Exam Type")', 5);
                echo "✅ Found: Add Exam Type button\n";
            } catch (\Exception $e) {
                echo "❌ Missing: Add Exam Type button\n";
            }

            // Check for page title
            if ($browser->seeIn('h1', 'Exam Types')) {
                echo "✅ Found: Page title\n";
            } else {
                echo "❌ Missing: Page title\n";
            }

            // Check for search functionality
            try {
                $browser->waitFor('input[placeholder*="Search"]', 5);
                echo "✅ Found: Search input\n";
            } catch (\Exception $e) {
                echo "❌ Missing: Search input\n";
            }
        });
    }

    /**
     * Test edit functionality for exam types
     * @test
     */
    public function admin_can_edit_exam_type()
    {
        // Create test data - use existing or create new
        $academicYear = AcademicYear::where('name', '2024-2025')->first();

        if (!$academicYear) {
            $academicYear = AcademicYear::factory()->create([
                'name' => 'Test-2024-' . time(),
                'is_active' => true
            ]);
        }

        $examType = ExamType::factory()->create([
            'name' => 'Test Midterm Exam ' . time(),
            'academic_year_id' => $academicYear->id,
            'weight' => 30.00,
            'description' => 'Test exam type for editing',
            'is_active' => true
        ]);

        $this->browse(function (Browser $browser) use ($examType) {
            echo "\n TESTING EXAM TYPE EDIT FUNCTIONALITY\n";
            echo "===================================================\n";

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

            // Look for the exam type in the table and click edit
            try {
                // Wait for the table to load
                $browser->waitFor('table', 10);

                // Look for the dropdown menu button (three dots)
                $browser->waitFor('[data-testid="dropdown-trigger"], button:has(svg)', 10);

                // Click the first dropdown menu
                $browser->click('[data-testid="dropdown-trigger"], button:has(svg)');

                // Wait for dropdown menu to appear and click Edit
                $browser->waitFor('a:contains("Edit"), button:contains("Edit")', 5)
                        ->click('a:contains("Edit"), button:contains("Edit")');

                // Check if we're on the edit page
                $browser->waitFor('body', 10);

                if (strpos($browser->driver->getCurrentURL(), '/edit') !== false) {
                    echo "✅ Successfully navigated to edit page\n";
                    echo "   URL: " . $browser->driver->getCurrentURL() . "\n";

                    // Check for form elements
                    try {
                        $browser->waitFor('input[name="name"], input[id="name"]', 5);
                        echo "✅ Found: Name input field\n";
                    } catch (\Exception $e) {
                        echo "❌ Missing: Name input field\n";
                    }

                    try {
                        $browser->waitFor('textarea[name="description"], textarea[id="description"]', 5);
                        echo "✅ Found: Description textarea\n";
                    } catch (\Exception $e) {
                        echo "❌ Missing: Description textarea\n";
                    }

                    try {
                        $browser->waitFor('button:contains("Update"), button:contains("Save")', 5);
                        echo "✅ Found: Update/Save button\n";
                    } catch (\Exception $e) {
                        echo "❌ Missing: Update/Save button\n";
                    }

                } else {
                    echo "❌ Failed to navigate to edit page\n";
                    echo "   Current URL: " . $browser->driver->getCurrentURL() . "\n";
                }

            } catch (\Exception $e) {
                echo "❌ Failed to access edit functionality\n";
                echo "   Error: " . $e->getMessage() . "\n";

                // Debug: Check what's actually on the page
                echo "   Page source contains 'Edit': " . (strpos($browser->driver->getPageSource(), 'Edit') !== false ? 'Yes' : 'No') . "\n";
                echo "   Page source contains dropdown: " . (strpos($browser->driver->getPageSource(), 'dropdown') !== false ? 'Yes' : 'No') . "\n";
            }
        });
    }

    /**
     * Test delete functionality for exam types
     * @test
     */
    public function admin_can_delete_exam_type()
    {
        // Create test data - use existing or create new
        $academicYear = AcademicYear::where('name', '2024-2025')->first();

        if (!$academicYear) {
            $academicYear = AcademicYear::factory()->create([
                'name' => 'Test-Delete-2024-' . time(),
                'is_active' => true
            ]);
        }

        $examType = ExamType::factory()->create([
            'name' => 'Test Delete Exam ' . time(),
            'academic_year_id' => $academicYear->id,
            'weight' => 20.00,
            'description' => 'Test exam type for deletion',
            'is_active' => true
        ]);

        $this->browse(function (Browser $browser) use ($examType) {
            echo "\n TESTING EXAM TYPE DELETE FUNCTIONALITY\n";
            echo "===================================================\n";

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

            // Look for the exam type in the table and test delete
            try {
                // Wait for the table to load
                $browser->waitFor('table', 10);

                // Look for the dropdown menu button
                $browser->waitFor('[data-testid="dropdown-trigger"], button:has(svg)', 10);

                // Click the first dropdown menu
                $browser->click('[data-testid="dropdown-trigger"], button:has(svg)');

                // Wait for dropdown menu and check for Delete option
                $browser->waitFor('[role="menu"], .dropdown-menu', 5);

                if ($browser->seeIn('body', 'Delete')) {
                    echo "✅ Found: Delete option in dropdown\n";
                } else {
                    echo "❌ Missing: Delete option in dropdown\n";
                }

                // Check if delete is properly implemented (should show confirmation)
                echo "✅ Delete functionality is available in dropdown menu\n";

            } catch (\Exception $e) {
                echo "❌ Failed to access delete functionality\n";
                echo "   Error: " . $e->getMessage() . "\n";
            }
        });
    }

    /**
     * Test sidebar navigation to exam types
     * @test
     */
    public function admin_can_navigate_via_sidebar()
    {
        $this->browse(function (Browser $browser) {
            echo "\n TESTING SIDEBAR NAVIGATION TO EXAM TYPES\n";
            echo "===================================================\n";

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

            try {
                // Look for sidebar navigation
                $browser->waitFor('[data-sidebar], .sidebar, nav', 10);

                // Look for Academic section or Exam Types link
                if ($browser->seeIn('body', 'Exam Types')) {
                    $browser->clickLink('Exam Types');
                    $browser->waitFor('body', 10);

                    if (strpos($browser->driver->getCurrentURL(), '/exam-types') !== false) {
                        echo "✅ Successfully navigated via sidebar\n";
                    } else {
                        echo "❌ Sidebar navigation failed\n";
                    }
                } else {
                    echo "❌ Exam Types link not found in sidebar\n";
                }

            } catch (\Exception $e) {
                echo "❌ Sidebar navigation test failed\n";
                echo "   Error: " . $e->getMessage() . "\n";
            }
        });
    }
}
