<?php

declare(strict_types=1);

namespace App\Filament\Resources\SpaProducts;

use App\Filament\Resources\SpaProducts\Pages\CreateSpaProduct;
use App\Filament\Resources\SpaProducts\Pages\EditSpaProduct;
use App\Filament\Resources\SpaProducts\Pages\ListSpaProducts;
use App\Models\SpaProduct;
use App\Models\User;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\BaseFileUpload;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use UnitEnum;

class SpaProductResource extends Resource
{
    protected static ?string $model = SpaProduct::class;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $slug = 'spa-products';

    protected static ?string $navigationLabel = '產品與精油';

    protected static string|UnitEnum|null $navigationGroup = '怡SPA';

    protected static ?int $navigationSort = 20;

    protected static ?string $modelLabel = '產品與精油';

    protected static ?string $pluralModelLabel = '產品與精油';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-sparkles';

    public static function canViewAny(): bool
    {
        $user = Auth::user();

        return $user instanceof User
            && $user->hasAnyRole(['super_admin', 'admin']);
    }

    public static function canCreate(): bool
    {
        return static::canViewAny();
    }

    public static function canEdit(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function canDelete(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                Grid::make()
                    ->schema([
                        Section::make()
                            ->schema([
                                TextInput::make('name')
                                    ->label('名稱')
                                    ->required()
                                    ->maxLength(150),

                                FileUpload::make('main_image_path')
                                    ->label('主圖')
                                    ->disk('public')
                                    ->directory('spa-products/main')
                                    ->image()
                                    ->saveUploadedFileUsing(static fn (BaseFileUpload $component, TemporaryUploadedFile $file): ?string =>
                                        \App\Support\Uploads\ImageVariants::store($component, $file)
                                    )
                                    ->deleteUploadedFileUsing(static function (BaseFileUpload $component, string $file): void {
                                        \App\Support\Uploads\ImageVariants::delete($component, $file);
                                    })
                                    ->maxSize(4096),

                                FileUpload::make('gallery_image_paths')
                                    ->label('相簿')
                                    ->disk('public')
                                    ->directory('spa-products/gallery')
                                    ->image()
                                    ->multiple()
                                    ->saveUploadedFileUsing(static fn (BaseFileUpload $component, TemporaryUploadedFile $file): ?string =>
                                        \App\Support\Uploads\ImageVariants::store($component, $file)
                                    )
                                    ->deleteUploadedFileUsing(static function (BaseFileUpload $component, string $file): void {
                                        \App\Support\Uploads\ImageVariants::delete($component, $file);
                                    })
                                    ->maxSize(4096),

                                RichEditor::make('description')
                                    ->label('內容')
                                    ->columnSpanFull(),

                                TextInput::make('sort_order')
                                    ->label('排序')
                                    ->numeric()
                                    ->default(0)
                                    ->required(),

                                Toggle::make('is_active')
                                    ->label('啟用')
                                    ->default(true),
                            ])
                            ->columns([
                                'sm' => 2,
                                'lg' => 3,
                            ])
                            ->columnSpanFull(),
                    ])
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                ImageColumn::make('main_image_path')
                    ->label('圖片')
                    ->disk('public')
                    ->getStateUsing(fn (\App\Models\SpaProduct $record): ?string =>
                        \App\Support\Uploads\ImageVariants::preferredPath($record->main_image_path, variant: 'medium', diskName: 'public')
                    )
                    ->square(),

                TextColumn::make('name')
                    ->label('名稱')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('slug')
                    ->label('Slug')
                    ->searchable()
                    ->sortable(),

                ToggleColumn::make('is_active')
                    ->label('啟用')
                    ->sortable(),

                TextColumn::make('sort_order')
                    ->label('排序')
                    ->numeric()
                    ->sortable(),

                TextColumn::make('updated_at')
                    ->label('更新')
                    ->dateTime('Y-m-d H:i')
                    ->sortable(),
            ])
            ->reorderable('sort_order')
            ->actions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([
                DeleteBulkAction::make(),
            ])
            ->defaultSort('sort_order', 'asc');
    }

    public static function getPages(): array
    {
        return [
            'index' => ListSpaProducts::route('/'),
            'create' => CreateSpaProduct::route('/create'),
            'edit' => EditSpaProduct::route('/{record}/edit'),
        ];
    }
}
