<?php

namespace App\Filament\Resources\Devices\Pages;

use App\Enums\SystemRole;
use App\Filament\Resources\Devices\DeviceResource;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Notifications\Notification;
use Filament\Panel\Concerns\HasNotifications;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;
use Illuminate\Support\Facades\Auth;

class DeviceResourceSetup extends Page
{
    use InteractsWithRecord, InteractsWithForms, HasNotifications;

    protected static string $resource = DeviceResource::class;

    protected string $view = 'filament.resources.devices.pages.device-resource-setup';

    protected static ?string $title = "Setup Device";

    public ?array $data = [];

    public function mount(int | string $record): void
    {
        $this->record = $this->resolveRecord($record);

        if (!auth()->user()->hasRole(SystemRole::SUPER_ADMIN)) {
            if ($this->record->user_id !== Auth::id()) {
                abort(403, 'You are not authorized to edit this device.');
            }
        }

        $this->form->fill([
            'business_name' => $this->record->business_name,
            'review_url' => $this->record->review_url,
            'is_active' => $this->record->is_active,
        ]);
    }

    protected function getHeaderActions(): array
    {
        return [];
    }

    public function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                Grid::make(1)->schema([
                    TextInput::make('business_name')
                        ->label('Business Name')
                        ->placeholder('Enter business name')
                        ->required(),

                    TextInput::make('review_url')
                        ->label('Review URL')
                        ->placeholder('Reviews URL')
                        ->required(),

                    Toggle::make('is_active')
                        ->label('Active')
                        ->inline(false),
                ]),
            ])
            ->statePath('data');
    }

    public function submit(): void
    {
        $this->validate(); // optional, Filament handles it

        $this->record->update([
            'business_name' => $this->data['business_name'] ?? null,
            'review_url' => $this->data['review_url'] ?? null,
            'is_active' => $this->data['is_active'] ?? false,
        ]);

        Notification::make()
            ->title('Device updated successfully')
            ->success() // Sets the color/icon to success type
            ->send();
    }
}
