<?php

namespace App\Filament\Resources\Devices\Schemas;

use App\Enums\DeviceType;
use App\Enums\Platform;
use App\Models\Device;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;

class DeviceForm
{
        public static function configure(Schema $schema): Schema
        {
            return $schema
                ->components([
                    TextInput::make('serial_number')
                        ->required()
                        ->maxLength(8)
                        ->unique(ignoreRecord: true)
                        ->afterStateHydrated(function ($state, $set) {
                            if (!$state) {
                                $set('serial_number', self::generateUniqueDeviceCode());
                            }
                        })
                        ->suffixAction(function ($get, $set) {
                            if (!$get('id')) {
                                return Action::make('refresh')
                                    ->icon('tabler-refresh')
                                    ->action(function () use ($set) {
                                        $set('serial_number', self::generateUniqueDeviceCode());
                                    });
                            }
                            return null;
                        })->readOnly(),
                    Select::make('type')->options(DeviceType::options())->required(),
                    Select::make('platform')->options(Platform::options())->required(),
                    Toggle::make('is_active')->inline(false)
                ]);
        }

    public static function generateUniqueDeviceCode(): string
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (Device::query()->where('serial_number', $code)->exists());

        return $code;
    }
}
