<?php

namespace Tests\Browser\Enrollment;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Modules\Enrollment\Models\Enrollment;
use Modules\Students\Models\Student;
use Modules\Academic\Models\Classroom;
use Modules\Academic\Models\AcademicYear;
use Modules\Academic\Models\Subject;
use App\Models\User;

class EnrollmentViewTest extends DuskTestCase
{
    use DatabaseMigrations;

    private User $adminUser;
    private AcademicYear $academicYear;
    private Classroom $classroom;
    private Student $student;
    private Enrollment $enrollment;

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

        // Create test data
        $this->adminUser = User::factory()->create(['role' => 'admin']);
        
        $this->academicYear = AcademicYear::factory()->create([
            'name' => '2024-2025',
            'is_active' => true,
        ]);

        $this->classroom = Classroom::factory()->create([
            'academic_year_id' => $this->academicYear->id,
            'name' => 'Grade 10A',
            'capacity' => 30,
        ]);

        $studentUser = User::factory()->create([
            'first_name' => 'John',
            'last_name' => 'Doe',
            'role' => 'student',
        ]);

        $this->student = Student::factory()->create([
            'user_id' => $studentUser->id,
            'student_id' => 'STU001',
        ]);

        $this->enrollment = Enrollment::factory()->create([
            'student_id' => $this->student->id,
            'classroom_id' => $this->classroom->id,
            'academic_year_id' => $this->academicYear->id,
            'is_active' => true,
        ]);
    }

    /** @test */
    public function admin_can_navigate_to_enrollment_index_page()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/dashboard')
                ->clickLink('Enrollment')
                ->assertPathIs('/enrollments')
                ->assertSee('Enrollments')
                ->assertSee('Manage student enrollments in classrooms')
                ->assertSee('New Enrollment')
                ->assertSee('Bulk Enroll');
        });
    }

    /** @test */
    public function enrollment_index_page_displays_enrollment_data()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->assertSee('John Doe')
                ->assertSee('STU001')
                ->assertSee('Grade 10A')
                ->assertSee('2024-2025')
                ->assertSee('Active');
        });
    }

    /** @test */
    public function admin_can_view_enrollment_details()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->click('[data-testid="enrollment-actions-' . $this->enrollment->id . '"]')
                ->click('[data-testid="view-enrollment"]')
                ->assertPathIs('/enrollments/' . $this->enrollment->id)
                ->assertSee('Enrollment Details')
                ->assertSee('John Doe')
                ->assertSee('STU001')
                ->assertSee('Grade 10A')
                ->assertSee('2024-2025')
                ->assertSee('Active');
        });
    }

    /** @test */
    public function admin_can_navigate_to_edit_enrollment_page()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments/' . $this->enrollment->id)
                ->clickLink('Edit Enrollment')
                ->assertPathIs('/enrollments/' . $this->enrollment->id . '/edit')
                ->assertSee('Edit Enrollment')
                ->assertSee('Update enrollment information for John Doe');
        });
    }

    /** @test */
    public function enrollment_edit_form_displays_current_data()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments/' . $this->enrollment->id . '/edit')
                ->assertSee('John Doe')
                ->assertSee('STU001')
                ->assertSelected('[data-testid="academic-year-select"]', $this->academicYear->id)
                ->assertSelected('[data-testid="classroom-select"]', $this->classroom->id)
                ->assertChecked('[data-testid="is-active-checkbox"]');
        });
    }

    /** @test */
    public function admin_can_navigate_to_create_enrollment_page()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->clickLink('New Enrollment')
                ->assertPathIs('/enrollments/create')
                ->assertSee('Create Enrollment')
                ->assertSee('Enroll a student in a classroom for an academic year');
        });
    }

    /** @test */
    public function admin_can_navigate_to_bulk_enroll_page()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->clickLink('Bulk Enroll')
                ->assertPathIs('/enrollments/bulk/enroll')
                ->assertSee('Bulk Enrollment')
                ->assertSee('Enroll multiple students in a classroom');
        });
    }

    /** @test */
    public function enrollment_index_page_search_functionality_works()
    {
        // Create another enrollment for testing search
        $anotherStudentUser = User::factory()->create([
            'first_name' => 'Jane',
            'last_name' => 'Smith',
            'role' => 'student',
        ]);

        $anotherStudent = Student::factory()->create([
            'user_id' => $anotherStudentUser->id,
            'student_id' => 'STU002',
        ]);

        Enrollment::factory()->create([
            'student_id' => $anotherStudent->id,
            'classroom_id' => $this->classroom->id,
            'academic_year_id' => $this->academicYear->id,
        ]);

        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->type('[data-testid="search-input"]', 'John')
                ->click('[data-testid="search-button"]')
                ->waitForText('John Doe')
                ->assertSee('John Doe')
                ->assertDontSee('Jane Smith');
        });
    }

    /** @test */
    public function enrollment_index_page_filter_functionality_works()
    {
        // Create another classroom and enrollment for testing filters
        $anotherClassroom = Classroom::factory()->create([
            'academic_year_id' => $this->academicYear->id,
            'name' => 'Grade 11A',
        ]);

        $anotherStudentUser = User::factory()->create([
            'first_name' => 'Jane',
            'last_name' => 'Smith',
            'role' => 'student',
        ]);

        $anotherStudent = Student::factory()->create([
            'user_id' => $anotherStudentUser->id,
            'student_id' => 'STU002',
        ]);

        Enrollment::factory()->create([
            'student_id' => $anotherStudent->id,
            'classroom_id' => $anotherClassroom->id,
            'academic_year_id' => $this->academicYear->id,
        ]);

        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->select('[data-testid="classroom-filter"]', $this->classroom->id)
                ->click('[data-testid="search-button"]')
                ->waitForText('Grade 10A')
                ->assertSee('John Doe')
                ->assertDontSee('Jane Smith');
        });
    }

    /** @test */
    public function enrollment_show_page_displays_comprehensive_information()
    {
        // Create subject for classroom
        $subject = Subject::factory()->create(['name' => 'Mathematics']);
        $this->classroom->subjects()->attach($subject->id);

        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments/' . $this->enrollment->id)
                ->assertSee('Enrollment Information')
                ->assertSee('Student Information')
                ->assertSee('John Doe')
                ->assertSee('STU001')
                ->assertSee('Grade 10A')
                ->assertSee('2024-2025')
                ->assertSee('Active')
                ->assertSee('Mathematics');
        });
    }

    /** @test */
    public function enrollment_show_page_navigation_buttons_work()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments/' . $this->enrollment->id)
                ->clickLink('Edit Enrollment')
                ->assertPathIs('/enrollments/' . $this->enrollment->id . '/edit')
                ->clickLink('Back to Enrollments')
                ->assertPathIs('/enrollments');
        });
    }

    /** @test */
    public function enrollment_edit_page_form_validation_works()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments/' . $this->enrollment->id . '/edit')
                ->clear('[data-testid="enrolled-at-input"]')
                ->click('[data-testid="submit-button"]')
                ->waitForText('The enrolled at field is required')
                ->assertSee('The enrolled at field is required');
        });
    }

    /** @test */
    public function enrollment_dropdown_actions_work_correctly()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->click('[data-testid="enrollment-dropdown-' . $this->enrollment->id . '"]')
                ->assertSee('View')
                ->assertSee('Edit')
                ->assertSee('Transfer')
                ->assertSee('Deactivate')
                ->click('[data-testid="view-enrollment"]')
                ->assertPathIs('/enrollments/' . $this->enrollment->id);
        });
    }

    /** @test */
    public function page_console_errors_are_monitored()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments');

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

            $this->assertEmpty($errors, 'Console errors found: ' . json_encode($errors));
        });
    }

    /** @test */
    public function enrollment_statistics_are_displayed_correctly()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->adminUser)
                ->visit('/enrollments')
                ->assertSee('Total')
                ->assertSee('Active')
                ->assertSee('Current Year')
                ->assertSee('1'); // Should show 1 enrollment
        });
    }
}
