<?php

namespace App\Filament\Resources;

use AbdulmajeedJamaan\FilamentTranslatableTabs\TranslatableTabs;
use App\Filament\Resources\ProjectResource\Pages;
use App\Filament\Resources\ProjectResource\RelationManagers;
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\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\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),
                ]),
                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("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"),
                        Select::make('badges')
                            ->multiple()
                            ->relationship('badges', 'title')
                            ->getOptionLabelFromRecordUsing(function ($record) {
                                $imageHtml = $record->img_url
                                    ? '<img src="' . Storage::url($record->img_url) . '" class="w-6 h-6 rounded-full mr-2 inline-block" />'
                                    : '<div class="w-6 h-6 bg-gray-200 rounded-full mr-2 inline-block"></div>';

                                return new \Illuminate\Support\HtmlString($imageHtml . $record->title);
                            })
                            ->allowHtml()
                            ->preload()
                            ->label('取得標章')
                            ->maxItems(8)
                            ->required(),
                    ]),
                    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"),
                        ])->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([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->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'),
        ];
    }
}
