<?php

namespace App\Filament\Resources;

use App\Filament\Resources\AlbumResource\Pages;
use App\Models\Album;
use App\Models\AlbumCategory;
use App\Service\DeepLService;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Group;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use SolutionForest\FilamentTranslateField\Forms\Component\Translate;

class AlbumResource extends Resource
{
    protected static ?string $model = Album::class;

    protected static ?string $modelLabel = '影音管理';

    protected static ?string $navigationIcon = 'heroicon-o-photo';

    protected static ?string $navigationGroup = '最新消息';

    protected static ?string $navigationLabel = '影音管理';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('新增 影音')->schema([
                    Group::make()->schema([
                        Select::make('album_category_id')
                            ->options(AlbumCategory::orderBy('order')->get()->pluck('name', 'id'))
                            ->label('影音分類')
                            ->required()
                            ->columnSpan(1)
                            ->native(false)
                            ->live(),
                    ])->columnSpanFull()->columns(2),
                    Group::make()->schema([
                        DatePicker::make('post_date')
                            ->label('發布日期')
                            ->closeOnDateSelection(),
                    ])->columnSpanFull()->columns(2),
                    FileUpload::make('news_banner')->label('列表大圖')
                        ->image()
                        ->optimize('webp')
                        ->maxImageWidth(1920)
                        ->directory('album/img')
                        ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
                    FileUpload::make('news_img_pc')->label('列表圖(desktop)')
                        ->image()
                        ->optimize('webp')
                        ->maxImageWidth(1920)
                        ->directory('album/img')
                        ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
                    FileUpload::make('news_img_mobile')->label('列表圖(mobile)')
                        ->image()
                        ->optimize('webp')
                        ->maxImageWidth(1920)
                        ->directory('album/img')
                        ->acceptedFileTypes(['image/jpeg', 'image/jpg', 'image/png', 'image/webp'])->required()->imageEditor(),
                    Translate::make()->schema(fn (string $locale) => [
                        TextInput::make('title')
                            ->label('標題')
                            ->columnSpan(1),
                    ])
                        ->locales(['zh_TW', 'en'])
                        ->actions([
                            app(DeepLService::class)->createTranslationAction('Main', ['title']),
                        ])
                        ->id('main')->columnSpanFull()->columns(3),

                    Section::make('')->schema([
                        Radio::make('upload_type')->label('')->options([
                            1 => '網址',
                            2 => '檔案',
                        ])->columnSpanFull()->default(1)->live(),
                        Group::make()->schema([
                            TextInput::make('link_video')->label('網址')->nullable(),
                        ])->visible(fn (Get $get): bool => $get('upload_type') == 1)->columnSpanFull(),
                        Group::make()->schema([
                            FileUpload::make('link_upload')->label('')->directory('album/video')
                                ->acceptedFileTypes(['video/mp4', 'video/mpeg', 'video/quicktime', 'video/x-msvideo', 'video/x-ms-wmv'])
                                ->helperText('建議影片寬高限制為:1920*1080px，出血寬度720px，大小限制為:100M以下')
                                ->maxSize(102400)->nullable(),
                        ])->visible(fn (Get $get): bool => $get('upload_type') == 2)->columnSpanFull(),
                    ])->columnSpanFull(),
                    Toggle::make('on_top')->inline()->label('置頂輪播')->columnSpanFull(),
                    //                    Toggle::make('homepage_top')->inline()->label('在首頁輪播')->columnSpanFull(),
                ])->columns(3),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                //
                TextColumn::make('albumCategory.name')->label('分類')->alignCenter(),
                TextColumn::make('title')->label('標題')->alignCenter(),
                TextColumn::make('post_date')->label('發布日期')->date()->alignCenter(),
                ImageColumn::make('news_img_pc')->label('列表圖(desktop)')->alignCenter(),
                TextColumn::make('list_audit_state')->label('狀態')->badge()
                    ->color(fn (string $state): string => match ($state) {
                        '暫存' => 'warning',
                        '已發佈' => 'success',
                    }),
                TextColumn::make('created_at')->label('建立時間')->dateTime()->alignCenter(),
                TextColumn::make('updated_at')->label('更新時間')->dateTime()->alignCenter(),
            ])
            ->filters([
                SelectFilter::make('post_date')->label('年份')
                    ->options(Album::select(DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull('post_date')->distinct()->pluck('year', 'year')->toArray())
                    ->query(
                        fn (array $data, Builder $query): Builder => $query->when(
                            $data['value'],
                            fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value'].'%')
                        )
                    ),
                SelectFilter::make('album_category_id')->label('分類')
                    ->relationship('albumCategory', 'name')
                    ->getOptionLabelFromRecordUsing(fn ($record, $livewire) => $record->getTranslation('name', 'zh_TW')),
                SelectFilter::make('visible')->label('狀態')
                    ->options([
                        0 => '暫存',
                        1 => '已發佈',
                    ])
                    ->query(
                        fn (array $data, Builder $query): Builder => $query->when(
                            $data['value'],
                            fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
                        )
                    ),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
                \Filament\Tables\Actions\Action::make('audit')
                    ->label(fn ($record) => match ($record->visible) {
                        0 => '發佈',
                        1 => '下架',
                    })
                    ->color(fn ($record) => match ($record->visible) {
                        0 => 'warning',
                        1 => 'gray',
                    })
                    ->icon(fn ($record) => match ($record->visible) {
                        0 => 'heroicon-m-chevron-double-up',
                        1 => 'heroicon-m-chevron-double-down',
                    })
                    ->action(function ($record) {
                        $record->visible = ! $record->visible;
                        $record->save();
                    })
                    ->outlined()
                    ->requiresConfirmation(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->reorderable('order')
            ->defaultSort('order');
    }

    public static function getRelations(): array
    {
        return [
            //
        ];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListAlbums::route('/'),
            'create' => Pages\CreateAlbum::route('/create'),
            'edit' => Pages\EditAlbum::route('/{record}/edit'),
            'view' => Pages\ViewAlbum::route('/{record}/view'),
        ];
    }
}
