<?php

namespace App\Filament\Resources\Media\Schemas;

use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
use Spatie\MediaLibrary\MediaCollections\Models\Media as SpatieMedia;

class MediaForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->required()
                    ->maxLength(255),
                TextInput::make('collection_name')
                    ->default('default')
                    ->required()
                    ->maxLength(255),
                Hidden::make('disk')
                    ->default('public'),
                FileUpload::make('file')
                    ->label('File')
                    ->imageEditor()
                    ->imageEditorAspectRatios([
                        '16:9',
                        '4:3',
                        '1:1',
                    ])
                    ->columnSpanFull()
                    ->disk('public')
                    ->directory('media')
                    ->visibility('public')
                    ->acceptedFileTypes(['image/*', 'application/pdf'])
                    ->maxSize(10240)
                    ->required(fn ($context) => $context === 'create')
                    ->afterStateHydrated(function (FileUpload $component, $state, $record): void {
                        if (! $record) {
                            return;
                        }

                        $media = $record;

                        if (! $media instanceof SpatieMedia) {
                            return;
                        }

                        // Construct the correct path: {media_id}/{filename}
                        $path = $media->id.'/'.$media->file_name;

                        $component->state($path);
                    }),
            ]);
    }
}
