<?php

namespace Tests\Browser;

use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use App\Models\User;
use Modules\Academic\Models\AcademicYear;
use Modules\Academic\Models\Subject;
use Modules\Academic\Models\Classroom;
use Modules\Academic\Models\ExamType;
use Modules\Students\Models\Student;
use Modules\Results\Models\Result;
use Modules\Enrollment\Models\Enrollment;

class ResultsModuleTest extends DuskTestCase
{
    protected $admin;
    protected $academicYear;
    protected $subject;
    protected $classroom;
    protected $examType;
    protected $student;

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

        // Use existing data from seeders
        $this->admin = User::where('role', 'admin')->first();
        if (!$this->admin) {
            $this->admin = User::factory()->create([
                'role' => 'admin',
                'email' => 'admin@resultstest.com'
            ]);
        }

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

        $this->subject = Subject::where('is_active', true)->first();
        if (!$this->subject) {
            $this->subject = Subject::factory()->create([
                'name' => 'Test Subject Results',
                'code' => 'TESTRES001',
                'is_active' => true
            ]);
        }

        $this->classroom = Classroom::where('academic_year_id', $this->academicYear->id)->first();
        if (!$this->classroom) {
            $this->classroom = Classroom::factory()->create([
                'name' => 'Test Classroom Results',
                'academic_year_id' => $this->academicYear->id,
                'capacity' => 30
            ]);
        }

        $this->examType = ExamType::where('academic_year_id', $this->academicYear->id)->where('is_active', true)->first();
        if (!$this->examType) {
            $this->examType = ExamType::factory()->create([
                'name' => 'Test Exam Results',
                'academic_year_id' => $this->academicYear->id,
                'is_active' => true
            ]);
        }

        $this->student = Student::first();
        if (!$this->student) {
            $this->student = Student::factory()->create([
                'first_name' => 'Test',
                'last_name' => 'Student Results'
            ]);
        }

        // Ensure enrollment exists
        $enrollment = Enrollment::where('student_id', $this->student->id)
                               ->where('classroom_id', $this->classroom->id)
                               ->first();
        if (!$enrollment) {
            Enrollment::create([
                'student_id' => $this->student->id,
                'classroom_id' => $this->classroom->id,
                'academic_year_id' => $this->academicYear->id,
                'enrolled_at' => now(),
                'is_active' => true,
            ]);
        }
    }

    /** @test */
    public function admin_can_access_results_page()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🧪 TESTING RESULTS PAGE ACCESS\n";
            echo "=" . str_repeat("=", 50) . "\n";

            $browser->loginAs($this->admin)
                    ->visit('/results')
                    ->waitFor('h1', 10)
                    ->assertSee('Results')
                    ->assertSee('Manage student examination results');

            echo "✅ Results page loaded successfully\n";

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

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

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

            $browser->loginAs($this->admin)
                    ->visit('/results/create')
                    ->waitFor('h1', 10)
                    ->assertSee('Create Result')
                    ->assertSee('Add a new student examination result');

            echo "✅ Create Result page loaded successfully\n";

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

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

    /** @test */
    public function admin_can_navigate_via_sidebar()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🧪 TESTING SIDEBAR NAVIGATION TO RESULTS\n";
            echo "=" . str_repeat("=", 50) . "\n";

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

            // Try to find and click the Results link in sidebar
            try {
                $browser->clickLink('Results')
                        ->waitForLocation('/results', 10)
                        ->assertPathIs('/results')
                        ->assertSee('Results');

                echo "✅ Successfully navigated to Results via sidebar\n";
            } catch (\Exception $e) {
                echo "❌ Could not navigate via sidebar: " . $e->getMessage() . "\n";

                // Try direct navigation as fallback
                $browser->visit('/results')
                        ->waitFor('h1', 10)
                        ->assertSee('Results');

                echo "✅ Direct navigation to Results works\n";
            }
        });
    }

    /** @test */
    public function results_page_has_required_elements()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🧪 TESTING RESULTS PAGE ELEMENTS\n";
            echo "=" . str_repeat("=", 50) . "\n";

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

            // Check for key elements
            $elements = [
                'Add Result' => 'Add Result button',
                'Export' => 'Export button',
                'Results' => 'Page title'
            ];

            foreach ($elements as $text => $description) {
                try {
                    $browser->assertSee($text);
                    echo "✅ Found: {$description}\n";
                } catch (\Exception $e) {
                    echo "❌ Missing: {$description}\n";
                }
            }
        });
    }
}
