<?php

namespace Tests\Feature;

use App\Filament\Resources\TerminalResource;
use App\Filament\Resources\TerminalResource\Pages\CreateTerminal;
use App\Filament\Resources\TerminalResource\Pages\EditTerminal;
use App\Filament\Resources\TerminalResource\Pages\ListTerminals;
use App\Models\Station;
use App\Models\Terminal;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class TerminalResourceTest extends TestCase
{
    use RefreshDatabase;

    protected User $user;

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

        // 创建测试用户并赋予管理员权限
        $this->user = User::factory()->create();

        // 设置为Filament管理员
        config(['filament.auth.guard' => 'web']);

        $this->actingAs($this->user);
    }

    /** @test */
    public function it_can_render_terminal_list_page(): void
    {
        Livewire::test(ListTerminals::class)
            ->assertSuccessful();
    }

    /** @test */
    public function it_can_list_terminals(): void
    {
        $terminals = Terminal::factory()->count(10)->create();

        Livewire::test(ListTerminals::class)
            ->assertCanSeeTableRecords($terminals);
    }

    /** @test */
    public function it_can_render_create_page(): void
    {
        Livewire::test(CreateTerminal::class)
            ->assertSuccessful();
    }

    /** @test */
    public function it_can_create_terminal(): void
    {
        $station = Station::factory()->create();

        $newData = [
            'name' => '测试终端',
            'code' => 'TEST-0001',
            'ip_address' => '192.168.1.100',
            'station_id' => $station->id,
            'diagram_urls' => [['title' => '测试组态', 'url' => 'https://example.com/diagram.html']],
        ];

        Livewire::test(CreateTerminal::class)
            ->fillForm($newData)
            ->call('create')
            ->assertHasNoFormErrors();

        $this->assertDatabaseHas('terminals', [
            'name' => '测试终端',
            'code' => 'TEST-0001',
            'ip_address' => '192.168.1.100',
        ]);
    }

    /** @test */
    public function it_validates_required_fields_on_create(): void
    {
        Livewire::test(CreateTerminal::class)
            ->fillForm([
                'name' => '',
                'code' => '',
            ])
            ->call('create')
            ->assertHasFormErrors([
                'name' => 'required',
                'code' => 'required',
            ]);
    }

    /** @test */
    public function it_validates_unique_code(): void
    {
        $existingTerminal = Terminal::factory()->create([
            'code' => 'EXISTING-001',
        ]);

        Livewire::test(CreateTerminal::class)
            ->fillForm([
                'name' => '新终端',
                'code' => 'EXISTING-001',
            ])
            ->call('create')
            ->assertHasFormErrors(['code' => 'unique']);
    }

    /** @test */
    public function it_validates_ip_address_format(): void
    {
        Livewire::test(CreateTerminal::class)
            ->fillForm([
                'name' => '测试终端',
                'code' => 'TEST-0001',
                'ip_address' => 'invalid-ip',
            ])
            ->call('create')
            ->assertHasFormErrors(['ip_address' => 'ip']);
    }

    /** @test */
    public function it_validates_code_format(): void
    {
        Livewire::test(CreateTerminal::class)
            ->fillForm([
                'name' => '测试终端',
                'code' => 'invalid code with spaces',
            ])
            ->call('create')
            ->assertHasFormErrors(['code' => 'regex']);
    }

    /** @test */
    public function it_can_render_edit_page(): void
    {
        $terminal = Terminal::factory()->create();

        Livewire::test(EditTerminal::class, ['record' => $terminal->getRouteKey()])
            ->assertSuccessful();
    }

    /** @test */
    public function it_can_retrieve_data_for_edit(): void
    {
        $terminal = Terminal::factory()->create();

        Livewire::test(EditTerminal::class, ['record' => $terminal->getRouteKey()])
            ->assertFormSet([
                'name' => $terminal->name,
                'code' => $terminal->code,
                'ip_address' => $terminal->ip_address,
                'station_id' => $terminal->station_id,
            ]);
    }

    /** @test */
    public function it_can_update_terminal(): void
    {
        $terminal = Terminal::factory()->create();

        $station = Station::factory()->create();

        $newData = [
            'name' => '更新后的终端',
            'code' => $terminal->code,
            'ip_address' => '192.168.1.200',
            'station_id' => $station->id,
        ];

        Livewire::test(EditTerminal::class, ['record' => $terminal->getRouteKey()])
            ->fillForm($newData)
            ->call('save')
            ->assertHasNoFormErrors();

        $this->assertDatabaseHas('terminals', [
            'id' => $terminal->id,
            'name' => '更新后的终端',
            'ip_address' => '192.168.1.200',
        ]);
    }

    /** @test */
    public function it_can_delete_terminal(): void
    {
        $terminal = Terminal::factory()->create();

        Livewire::test(EditTerminal::class, ['record' => $terminal->getRouteKey()])
            ->callAction('delete');

        $this->assertSoftDeleted('terminals', [
            'id' => $terminal->id,
        ]);
    }

    /** @test */
    public function it_can_filter_by_online_status(): void
    {
        $onlineTerminals = Terminal::factory()->count(3)->online()->create();
        $offlineTerminals = Terminal::factory()->count(2)->offline()->create();

        Livewire::test(ListTerminals::class)
            ->filterTable('is_online', true)
            ->assertCanSeeTableRecords($onlineTerminals)
            ->assertCanNotSeeTableRecords($offlineTerminals);
    }

    /** @test */
    public function it_can_search_terminals(): void
    {
        $terminal1 = Terminal::factory()->create(['name' => '生产线A-工位1']);
        $terminal2 = Terminal::factory()->create(['name' => '质检站-工位2']);

        Livewire::test(ListTerminals::class)
            ->searchTable('生产线A')
            ->assertCanSeeTableRecords([$terminal1])
            ->assertCanNotSeeTableRecords([$terminal2]);
    }

    /** @test */
    public function it_can_sort_terminals(): void
    {
        $terminals = Terminal::factory()->count(3)->create();

        Livewire::test(ListTerminals::class)
            ->sortTable('name')
            ->assertCanSeeTableRecords($terminals->sortBy('name'), inOrder: true);
    }

    /** @test */
    public function it_displays_online_status_badge(): void
    {
        $onlineTerminal = Terminal::factory()->online()->create();
        $offlineTerminal = Terminal::factory()->offline()->create();

        Livewire::test(ListTerminals::class)
            ->assertTableColumnStateSet('is_online', true, $onlineTerminal)
            ->assertTableColumnStateSet('is_online', false, $offlineTerminal);
    }

    /** @test */
    public function it_can_group_by_group(): void
    {
        $station1 = Station::factory()->create();
        $station2 = Station::factory()->create();
        Terminal::factory()->count(3)->create(['station_id' => $station1->id]);
        Terminal::factory()->count(2)->create(['station_id' => $station2->id]);

        // 测试分组功能是否可用
        $component = Livewire::test(ListTerminals::class);

        // 验证表格可以正常渲染
        $component->assertSuccessful();
    }

    /** @test */
    public function it_can_bulk_delete_terminals(): void
    {
        $terminals = Terminal::factory()->count(3)->create();

        Livewire::test(ListTerminals::class)
            ->callTableBulkAction('delete', $terminals)
            ->assertSuccessful();

        foreach ($terminals as $terminal) {
            $this->assertSoftDeleted('terminals', [
                'id' => $terminal->id,
            ]);
        }
    }
}
