<?php

namespace App\Filament\Resources;

use AbdulmajeedJamaan\FilamentTranslatableTabs\TranslatableTabs;
use App\Filament\Resources\ProjectResource\Pages;
use App\Filament\Resources\ProjectResource\RelationManagers;
use App\Models\Badge;
use App\Models\Project;
use App\Models\Region;
use Filament\Forms;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Group;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Tabs;
use Filament\Forms\Components\Tabs\Tab;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
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\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
use App\Service\DeepLService;

class ProjectResource extends Resource
{
    protected static ?string $model = Project::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationGroup = '專案項目管理';
    protected static ?string $navigationLabel = "專案項目管理";
    protected static ?string $modelLabel = "專案項目管理";
    protected static ?int $navigationSort = 5;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make("")->schema([
                    Translate::make()->schema(fn (string $locale) => [
                        TextInput::make("name")->label("項目名稱"),
                        TextInput::make("sub_name")->label("項目子名稱"),
                    ])
                    ->locales(["zh_TW", "en"])
                    ->actions([
                        app(DeepLService::class)->createTranslationAction("Main", ["name", "sub_name"])
                    ])->columnSpanFull()->id("main"),
                    Select::make('tags')
                        ->multiple()
                        ->relationship('tags', 'name')
                        ->preload()
                        ->label('標籤'),
                    FileUpload::make("img_url")->label("圖片")->directory("project")->multiple()->maxFiles(5),
                    TextInput::make('order')->label("排序")->default("0")
                ]),
                Tabs::make()->schema([
                    Tab::make("專案概要")->schema([
                        Select::make("region_id")->label("地區")->options(function (){
                            return Region::where("visible",true)->pluck("name", "id");
                        }),
                        Translate::make()->schema(fn (string $locale) => [
                            Textarea::make("summaries")->label("簡述"),
                            TextInput::make("district")->label("區域"),
                            TextInput::make("address")->label("地址"),
                            Textarea::make("floor_plan")->label("樓層規劃"),
                            Textarea::make("building_structure")->label("建築結構"),
                            Textarea::make("design_unit")->label("設計單位")
                        ])
                        ->locales(["zh_TW", "en"])
                        ->actions([
                            app(DeepLService::class)->createTranslationAction("summaries", ["summaries","address",
                            "floor_plan","building_structure","design_unit"])
                        ])->columnSpanFull()->id("summaries"),
                        Radio::make("badge_type")->label("")->options([1 => "永續目標", 2 => "取得標章"])->default(1)->inline(),
                        Repeater::make("badgesTarget")->label("永續目標")->schema([
                            Hidden::make("award_type")->default(1),
                            Select::make('badge_id')
                                ->options(function () {
                                    return Badge::all()->mapWithKeys(function ($badge) {
                                        return [
                                            $badge->id => '<div class="flex items-center gap-2">
                                                <img src="' . Storage::url($badge->img_url) . '" class="w-6 h-6 rounded-full">
                                                <span>' . $badge->title . '</span>
                                            </div>'
                                        ];
                                    });
                                })
                                ->allowHtml()
                                ->preload()
                                ->searchable()
                                ->label('')
                                ->required(),
                        ])->reorderable(false),
                        Repeater::make("badgesAward")->label("取得標章")->schema([
                            Hidden::make("award_type")->default(2),
                            Select::make('badge_id')
                                ->options(function () {
                                    return Badge::all()->mapWithKeys(function ($badge) {
                                        return [
                                            $badge->id => '<div class="flex items-center gap-2">
                                                <img src="' . Storage::url($badge->img_url) . '" class="w-6 h-6 rounded-full">
                                                <span>' . $badge->title . '</span>
                                            </div>'
                                        ];
                                    });
                                })
                                ->allowHtml()
                                ->preload()
                                ->searchable()
                                ->label('')
                                ->required(),
                            DatePicker::make('award_date')
                                ->label('選擇年月')
                                ->format('Y-m')
                                ->displayFormat('Y年m月')
                                ->native(false)
                                ->closeOnDateSelection()
                        ])->reorderable(false),
                    ]),
                    Tab::make("開發歷程")->schema([
                        Repeater::make("histories")->label("")->schema([
                            TextInput::make('histories_item_key')
                            ->default(fn () => Str::random())
                            ->hidden()
                            ->afterStateHydrated(function (TextInput $component, $state) {
                                if (empty($state)) {
                                    $component->state(Str::random());
                                }
                            }),
                            DatePicker::make("operate_date")->label("歷程日期")->columnSpan(1),
                            Translate::make()->schema(fn (string $locale) => [
                                TextInput::make("title")->label("標題")->columnSpanFull()
                            ])
                            ->locales(["zh_TW", "en"])
                            ->actions([
                                app(DeepLService::class)->createTranslationAction("histories", ["title"])
                            ])->columnSpanFull()
                            ->id(fn ($get) => "histories_" . $get('histories_item_key')),
                        ])
                        ->relationship("histories", function ($query,Get $get, $livewire) {
                            return $query->orderby("operate_date","desc");
                        })
                        ->collapsible()
                        ->cloneable()
                    ]),
                    Tab::make("空間資訊")->schema([
                        Group::make()->schema([
                            Translate::make()->schema(fn (string $locale) => [
                                TextInput::make("contact_unit")->label("物管單位"),
                                TextInput::make("contact_phone")->label("物管電話"),
                                TextInput::make("inversment_phone")->label("招商電話"),
                            ])
                            ->locales(["zh_TW", "en"])
                            ->actions([
                                app(DeepLService::class)->createTranslationAction("contact", ["contact_unit", "contact_phone", "inversment_phone"])
                            ])->columnSpanFull()->columns(3)
                            ->id("contact"),
                            TextInput::make("offical_link")->label("官網連結"),
                        ])->columnSpanFull(),
                        Repeater::make("spaceInfos")->label("")->schema([
                            Translate::make()->schema(fn (string $locale) => [
                                TextInput::make("title")->label("標題")->columnSpanFull(),
                                Textarea::make("content")->label("內文")->columnSpanFull()
                            ])
                            ->locales(["zh_TW", "en"])
                            ->actions([
                                app(DeepLService::class)->createTranslationAction("spaceInfos", ["title", "content"])
                            ])->columnSpanFull()
                            ->id(fn ($get) => "spaceInfos_" . $get('item_key')),
                        ])
                        ->relationship("spaceInfos")
                        ->label("")
                        ->collapsible()
                        ->reorderableWithButtons()
                        ->orderColumn('order')
                        ->cloneable(),
                    ])
                ])->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                //
                TextColumn::make("name")->label("項目名稱")->alignCenter(),
                ImageColumn::make("first_list_img_url")->label("列表圖")->alignCenter(),
                TextColumn::make("region.name")->label("地址")->alignCenter()
                ->formatStateUsing(fn ($record) => $record->region->getTranslation("name", "zh_TW") . ' | ' . $record->getTranslation("address", "zh_TW")),
            ])
            ->filters([
                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): void {
                    $record->visible = !$record->visible;
                    $record->save();
                })
                ->outlined()
                ->requiresConfirmation(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProjects::route('/'),
            'create' => Pages\CreateProject::route('/create'),
            'edit' => Pages\EditProject::route('/{record}/edit'),
        ];
    }
}
