<?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\Classroom;
use Modules\Academic\Models\AcademicYear;
use Modules\Users\Models\User;
use Spatie\Permission\Models\Role;

class ToastFunctionalityTest extends DuskTestCase
{
    use RefreshDatabase;

    protected $admin;

    protected function setUp(): void
    {
        parent::setUp();
        
        // Create admin role and user
        $adminRole = Role::create(['name' => 'admin']);
        $this->admin = User::factory()->create([
            'email' => 'admin@test.com',
            'password' => bcrypt('password')
        ]);
        $this->admin->assignRole($adminRole);
    }

    /** @test */
    public function it_can_navigate_to_all_pages_without_javascript_errors()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->admin)
                    ->visit('/dashboard');

            $pages = [
                '/subjects' => 'Subjects',
                '/classrooms' => 'Classrooms',
                '/academic-years' => 'Academic Years',
                '/exam-types' => 'Exam Types',
                '/students' => 'Students',
                '/teachers' => 'Teachers',
            ];

            foreach ($pages as $url => $title) {
                $browser->visit($url)
                        ->waitFor('h1', 10)
                        ->assertSee($title);

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

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

    /** @test */
    public function it_shows_toast_on_subject_creation()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->admin)
                    ->visit('/subjects/create')
                    ->waitFor('form', 5)
                    ->type('name', 'Test Subject')
                    ->type('code', 'TEST001')
                    ->type('description', 'Test Description')
                    ->check('is_active')
                    ->press('Create Subject')
                    ->waitForLocation('/subjects', 10);

            // Check for success toast
            $browser->waitFor('.toast, [class*="toast"], [class*="notification"]', 5);
            
            // Check for JavaScript errors
            $logs = $browser->driver->manage()->getLog('browser');
            $errors = array_filter($logs, function($log) {
                return $log['level'] === 'SEVERE';
            });

            if (!empty($errors)) {
                echo "❌ JavaScript errors during subject creation:\n";
                foreach ($errors as $error) {
                    echo "   - {$error['message']}\n";
                }
            } else {
                echo "✅ Subject creation completed without JavaScript errors\n";
            }
        });
    }

    /** @test */
    public function it_shows_toast_on_subject_deletion()
    {
        $subject = Subject::factory()->create([
            'name' => 'Test Subject for Deletion',
            'code' => 'DEL001'
        ]);

        $this->browse(function (Browser $browser) use ($subject) {
            $browser->loginAs($this->admin)
                    ->visit('/subjects')
                    ->waitFor('table', 5);

            // Find and click delete button
            $browser->click('[data-testid="subject-' . $subject->id . '-delete"], .dropdown-menu button:contains("Delete")')
                    ->waitFor('.confirm, [role="dialog"]', 3);

            // Confirm deletion
            $browser->press('Confirm')
                    ->waitFor('.toast, [class*="toast"], [class*="notification"]', 5);

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

            if (!empty($errors)) {
                echo "❌ JavaScript errors during subject deletion:\n";
                foreach ($errors as $error) {
                    echo "   - {$error['message']}\n";
                }
            } else {
                echo "✅ Subject deletion completed without JavaScript errors\n";
            }
        });
    }

    /** @test */
    public function it_shows_toast_on_classroom_creation()
    {
        $academicYear = AcademicYear::factory()->create();

        $this->browse(function (Browser $browser) use ($academicYear) {
            $browser->loginAs($this->admin)
                    ->visit('/classrooms/create')
                    ->waitFor('form', 5)
                    ->type('name', 'Test Classroom')
                    ->select('academic_year_id', $academicYear->id)
                    ->type('capacity', '30')
                    ->type('description', 'Test Description')
                    ->press('Create Classroom')
                    ->waitForLocation('/classrooms', 10);

            // Check for success toast
            $browser->waitFor('.toast, [class*="toast"], [class*="notification"]', 5);

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

            if (!empty($errors)) {
                echo "❌ JavaScript errors during classroom creation:\n";
                foreach ($errors as $error) {
                    echo "   - {$error['message']}\n";
                }
            } else {
                echo "✅ Classroom creation completed without JavaScript errors\n";
            }
        });
    }

    /** @test */
    public function it_shows_validation_error_toast()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->admin)
                    ->visit('/subjects/create')
                    ->waitFor('form', 5)
                    // Submit form without required fields
                    ->press('Create Subject')
                    ->waitFor('.toast, [class*="toast"], [class*="error"]', 5);

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

            if (!empty($errors)) {
                echo "❌ JavaScript errors during validation error handling:\n";
                foreach ($errors as $error) {
                    echo "   - {$error['message']}\n";
                }
            } else {
                echo "✅ Validation error handling completed without JavaScript errors\n";
            }
        });
    }

    /** @test */
    public function it_can_test_all_delete_buttons()
    {
        // Create test data
        $subject = Subject::factory()->create();
        $academicYear = AcademicYear::factory()->create();
        $classroom = Classroom::factory()->create(['academic_year_id' => $academicYear->id]);

        $this->browse(function (Browser $browser) use ($subject, $classroom) {
            $browser->loginAs($this->admin);

            $testCases = [
                ['/subjects', 'subject', $subject->id],
                ['/classrooms', 'classroom', $classroom->id],
            ];

            foreach ($testCases as [$url, $type, $id]) {
                $browser->visit($url)
                        ->waitFor('table', 5);

                // Look for delete button and test it
                try {
                    $browser->click("button[onclick*='delete{$type}({$id})'], .dropdown-menu button:contains('Delete')")
                            ->pause(1000); // Wait for any confirmation dialog

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

                    if (!empty($errors)) {
                        echo "❌ JavaScript errors on {$url} delete button:\n";
                        foreach ($errors as $error) {
                            echo "   - {$error['message']}\n";
                        }
                    } else {
                        echo "✅ Delete button on {$url} works without JavaScript errors\n";
                    }
                } catch (\Exception $e) {
                    echo "⚠️  Could not find delete button on {$url}: {$e->getMessage()}\n";
                }
            }
        });
    }

    /** @test */
    public function it_checks_toast_container_exists()
    {
        $this->browse(function (Browser $browser) {
            $browser->loginAs($this->admin)
                    ->visit('/subjects')
                    ->waitFor('body', 5);

            // Check if toast container exists in DOM
            $hasToastContainer = $browser->element('.toast-container, [class*="toast"], .fixed.top-4.right-4');
            
            if ($hasToastContainer) {
                echo "✅ Toast container found in DOM\n";
            } else {
                echo "❌ Toast container not found in DOM\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 "❌ JavaScript errors on page load:\n";
                foreach ($errors as $error) {
                    echo "   - {$error['message']}\n";
                }
            } else {
                echo "✅ Page loads without JavaScript errors\n";
            }
        });
    }
}
