<?php

namespace App\Filament\Resources\Guides\Schemas;

use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Schema;
use Illuminate\Support\Str;

class GuideForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('title')
                    ->required()
                    ->live(onBlur: true)
                    ->afterStateUpdated(fn ($state, callable $set, ?string $old, $get) => $get('slug') ? null : $set('slug', Str::slug($state ?? ''))),
                TextInput::make('slug')
                    ->required()
                    ->unique(ignoreRecord: true),
                TextInput::make('category')
                    ->placeholder('e.g. Debt, Investing, Saving'),
                TextInput::make('sort')
                    ->numeric()
                    ->default(0),
                Textarea::make('description')
                    ->rows(2)
                    ->helperText('Shown on the cover and the library card.')
                    ->columnSpanFull(),
                FileUpload::make('cover_path')
                    ->label('Cover image')
                    ->image()
                    ->disk('public')
                    ->directory('guides')
                    ->imageEditor()
                    ->helperText('Landscape or portrait photo, it becomes the book cover.')
                    ->columnSpanFull(),
                Repeater::make('pages')
                    ->label('Pages (each entry is one flipbook page / PDF chapter)')
                    ->schema([
                        TextInput::make('title')
                            ->label('Page title')
                            ->required(),
                        Textarea::make('body')
                            ->label('Page body (blank line = new paragraph)')
                            ->rows(7)
                            ->required(),
                    ])
                    ->minItems(1)
                    ->reorderable()
                    ->collapsible()
                    ->itemLabel(fn (array $state): ?string => $state['title'] ?? null)
                    ->columnSpanFull(),
                Toggle::make('is_published')
                    ->default(true),
            ]);
    }
}
