<?php

namespace Tests\Browser;

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

class CrudOperationsTest extends DuskTestCase
{
    /** @test */
    public function it_tests_subject_crud_operations()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🧪 TESTING SUBJECT CRUD OPERATIONS\n";
            echo "=" . str_repeat("=", 60) . "\n";

            // Use existing admin user
            $admin = User::where('role', 'admin')->first();

            $browser->loginAs($admin);

            // Test CREATE operation
            echo "\n📝 TESTING SUBJECT CREATE...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $browser->visit('/subjects/create')
                        ->pause(2000);

                echo "✅ Create page loaded\n";
                echo "📄 Title: " . $browser->driver->getTitle() . "\n";

                // Check for JavaScript errors before form submission
                $logs = $browser->driver->manage()->getLog('browser');
                $errorCount = count(array_filter($logs, fn($log) => $log['level'] === 'SEVERE'));
                echo "🔍 Console errors before form: {$errorCount}\n";

                // Fill and submit form
                $browser->type('name', 'Test Subject CRUD')
                        ->type('code', 'TESTCRUD001')
                        ->type('description', 'Test Description for CRUD')
                        ->check('is_active')
                        ->press('Create Subject')
                        ->pause(3000);

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

                // Check for console errors after form submission
                $logs = $browser->driver->manage()->getLog('browser');
                $errors = array_filter($logs, fn($log) => $log['level'] === 'SEVERE');

                if (!empty($errors)) {
                    echo "❌ Console errors after form submission:\n";
                    foreach ($errors as $error) {
                        echo "   - {$error['message']}\n";
                    }
                } else {
                    echo "✅ No console errors after form submission\n";
                }

                // Check for success indicators
                $this->checkSuccessIndicators($browser, 'Subject created');

            } catch (\Exception $e) {
                echo "❌ Error in CREATE test: {$e->getMessage()}\n";
            }

            // Test EDIT operation
            echo "\n✏️ TESTING SUBJECT EDIT...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $subject = Subject::where('name', 'Test Subject CRUD')->first();
                if (!$subject) {
                    $subject = Subject::first();
                }

                if ($subject) {
                    $browser->visit("/subjects/{$subject->id}/edit")
                            ->pause(2000);

                    echo "✅ Edit page loaded for subject ID: {$subject->id}\n";

                    // Update form
                    $browser->clear('name')
                            ->type('name', 'Updated Test Subject CRUD')
                            ->press('Update Subject')
                            ->pause(3000);

                    echo "✅ Edit form submitted\n";

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

                    if (!empty($errors)) {
                        echo "❌ Console errors after edit:\n";
                        foreach ($errors as $error) {
                            echo "   - {$error['message']}\n";
                        }
                    } else {
                        echo "✅ No console errors after edit\n";
                    }

                    // Check for success indicators
                    $this->checkSuccessIndicators($browser, 'Subject updated');
                } else {
                    echo "❌ No subject found for edit test\n";
                }

            } catch (\Exception $e) {
                echo "❌ Error in EDIT test: {$e->getMessage()}\n";
            }

            // Test DELETE operation
            echo "\n🗑️ TESTING SUBJECT DELETE...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $browser->visit('/subjects')
                        ->pause(2000);

                echo "✅ Subjects index loaded\n";

                $this->testDeleteOperation($browser, 'subject');

            } catch (\Exception $e) {
                echo "❌ Error in DELETE test: {$e->getMessage()}\n";
            }

            echo "\n✅ Subject CRUD tests completed\n";
        });
    }

    /** @test */
    public function it_tests_classroom_crud_operations()
    {
        $this->browse(function (Browser $browser) {
            echo "\n🏫 TESTING CLASSROOM CRUD OPERATIONS\n";
            echo "=" . str_repeat("=", 60) . "\n";

            $admin = User::where('role', 'admin')->first();
            $browser->loginAs($admin);

            // Test CREATE
            echo "\n📝 TESTING CLASSROOM CREATE...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $browser->visit('/classrooms/create')
                        ->pause(2000);

                echo "✅ Classroom create page loaded\n";

                // Get academic year for form
                $academicYear = AcademicYear::first();
                if ($academicYear) {
                    $browser->type('name', 'Test Classroom CRUD')
                            ->select('academic_year_id', $academicYear->id)
                            ->type('capacity', '30')
                            ->type('description', 'Test classroom description')
                            ->press('Create Classroom')
                            ->pause(3000);

                    echo "✅ Classroom form submitted\n";
                    $this->checkConsoleErrors($browser, 'classroom create');
                    $this->checkSuccessIndicators($browser, 'Classroom created');
                } else {
                    echo "❌ No academic year found for classroom creation\n";
                }

            } catch (\Exception $e) {
                echo "❌ Error in classroom CREATE: {$e->getMessage()}\n";
            }

            // Test DELETE
            echo "\n🗑️ TESTING CLASSROOM DELETE...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $browser->visit('/classrooms')
                        ->pause(2000);

                $this->testDeleteOperation($browser, 'classroom');

            } catch (\Exception $e) {
                echo "❌ Error in classroom DELETE: {$e->getMessage()}\n";
            }

            echo "\n✅ Classroom CRUD tests completed\n";
        });
    }

    /** @test */
    public function it_tests_academic_year_crud_operations()
    {
        $this->browse(function (Browser $browser) {
            echo "\n📅 TESTING ACADEMIC YEAR CRUD OPERATIONS\n";
            echo "=" . str_repeat("=", 60) . "\n";

            $admin = User::where('role', 'admin')->first();
            $browser->loginAs($admin);

            // Test CREATE
            echo "\n📝 TESTING ACADEMIC YEAR CREATE...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $browser->visit('/academic-years/create')
                        ->pause(2000);

                echo "✅ Academic year create page loaded\n";

                $browser->type('name', '2025-2026 Test')
                        ->type('start_date', '2025-01-01')
                        ->type('end_date', '2025-12-31')
                        ->press('Create Academic Year')
                        ->pause(3000);

                echo "✅ Academic year form submitted\n";
                $this->checkConsoleErrors($browser, 'academic year create');
                $this->checkSuccessIndicators($browser, 'Academic year created');

            } catch (\Exception $e) {
                echo "❌ Error in academic year CREATE: {$e->getMessage()}\n";
            }

            // Test DELETE
            echo "\n🗑️ TESTING ACADEMIC YEAR DELETE...\n";
            echo "-" . str_repeat("-", 40) . "\n";

            try {
                $browser->visit('/academic-years')
                        ->pause(2000);

                $this->testDeleteOperation($browser, 'academic year');

            } catch (\Exception $e) {
                echo "❌ Error in academic year DELETE: {$e->getMessage()}\n";
            }

            echo "\n✅ Academic year CRUD tests completed\n";
        });
    }

    private function checkSuccessIndicators(Browser $browser, string $operation): void
    {
        echo "\n🔍 CHECKING SUCCESS INDICATORS FOR: {$operation}\n";

        // Check for toast elements
        $toastSelectors = [
            '.toast',
            '[class*="toast"]',
            '.fixed.top-4.right-4 > div',
            '[role="alert"]',
            '.bg-green-50',
            '.notification'
        ];

        $toastFound = false;
        foreach ($toastSelectors as $selector) {
            if ($browser->element($selector)) {
                echo "✅ Toast element found: {$selector}\n";
                $toastFound = true;
                break;
            }
        }

        if (!$toastFound) {
            echo "❌ No toast elements found\n";
        }

        // Check for flash messages
        if ($browser->element('.bg-green-50, .alert-success')) {
            echo "✅ Flash message found\n";
        } else {
            echo "❌ No flash message found\n";
        }

        // Check page source for success text
        $pageSource = $browser->driver->getPageSource();
        if (strpos($pageSource, 'success') !== false) {
            echo "✅ Success text found in page source\n";
        } else {
            echo "❌ No success text in page source\n";
        }
    }

    private function checkConsoleErrors(Browser $browser, string $operation): void
    {
        $logs = $browser->driver->manage()->getLog('browser');
        $errors = array_filter($logs, fn($log) => $log['level'] === 'SEVERE');

        if (!empty($errors)) {
            echo "❌ Console errors during {$operation}:\n";
            foreach ($errors as $error) {
                echo "   - {$error['message']}\n";
            }
        } else {
            echo "✅ No console errors during {$operation}\n";
        }
    }

    private function testDeleteOperation(Browser $browser, string $entityType): void
    {
        echo "🔍 Looking for table dropdown menus...\n";

        // First, look for table rows
        $tableRows = $browser->elements('table tbody tr');
        echo "📊 Found " . count($tableRows) . " table rows\n";

        if (empty($tableRows)) {
            echo "❌ No table rows found for {$entityType}\n";
            return;
        }

        // Look for dropdown triggers in the table
        $dropdownSelectors = [
            'table tbody tr:first-child button[data-testid*="dropdown"]',
            'table tbody tr:first-child .dropdown-trigger',
            'table tbody tr:first-child button[aria-haspopup="true"]',
            'table tbody tr:first-child button:contains("⋮")',
            'table tbody tr:first-child button:contains("...")',
            'table tbody tr:first-child [role="button"]',
            'table tbody tr:first-child td:last-child button'
        ];

        $dropdownFound = false;
        foreach ($dropdownSelectors as $selector) {
            try {
                if ($browser->element($selector)) {
                    echo "✅ Dropdown trigger found: {$selector}\n";

                    // Click to open dropdown
                    $browser->click($selector)
                            ->pause(1000);

                    echo "✅ Dropdown opened\n";

                    // Now look for delete option in the opened dropdown
                    $deleteSelectors = [
                        'button:contains("Delete")',
                        '[role="menuitem"]:contains("Delete")',
                        '.dropdown-menu button:contains("Delete")',
                        '.dropdown-content button:contains("Delete")',
                        '[data-testid*="delete"]',
                        'button[onclick*="delete"]'
                    ];

                    $deleteFound = false;
                    foreach ($deleteSelectors as $deleteSelector) {
                        try {
                            if ($browser->element($deleteSelector)) {
                                echo "✅ Delete option found: {$deleteSelector}\n";

                                $browser->click($deleteSelector)
                                        ->pause(1000);

                                // Handle confirmation dialog
                                try {
                                    $browser->acceptDialog();
                                    echo "✅ Confirmation dialog accepted\n";
                                } catch (\Exception $e) {
                                    echo "ℹ️ No confirmation dialog\n";
                                }

                                $browser->pause(3000);
                                $deleteFound = true;
                                break;
                            }
                        } catch (\Exception $e) {
                            continue;
                        }
                    }

                    if ($deleteFound) {
                        $dropdownFound = true;
                        break;
                    } else {
                        echo "❌ No delete option found in dropdown\n";
                        // Try to close dropdown by clicking elsewhere
                        $browser->click('body')->pause(500);
                    }
                }
            } catch (\Exception $e) {
                continue;
            }
        }

        if ($dropdownFound) {
            echo "✅ Delete operation attempted for {$entityType}\n";
            $this->checkConsoleErrors($browser, "{$entityType} delete");
            $this->checkSuccessIndicators($browser, "{$entityType} deleted");
        } else {
            echo "❌ No dropdown menu or delete option found for {$entityType}\n";

            // Debug: Let's see what's actually in the table
            echo "🔍 Debugging table structure...\n";
            try {
                $lastColumnContent = $browser->text('table tbody tr:first-child td:last-child');
                echo "📋 Last column content: {$lastColumnContent}\n";
            } catch (\Exception $e) {
                echo "❌ Could not read last column content\n";
            }
        }
    }
}
