<?php

namespace App\Filament\Resources;

use App\Filament\Resources\EsgResource\Pages;
use App\Models\Esg;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Group;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\RichEditor;
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\Components\Toggle;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
use Str;

class EsgResource extends Resource
{
    protected static ?string $model = Esg::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $modelLabel = "ESG 管理";
    protected static ?string $navigationGroup = 'ESG 上稿內容管理';
    protected static ?string $navigationLabel = "ESG 管理";

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                //
                Tabs::make("")->tabs([
                    Tab::make('基本資訊')->schema([
                        TextInput::make('keyword')->label("關聯字詞")->required()
                        ->validationMessages([
                            'required' => '請填寫關聯字詞',
                        ]),
                        Translate::make()->schema(fn (string $locale) => [
                            TextInput::make('title')
                            ->label("標題")
                            ->columnSpan(1)
                            ->required($locale == "zh_TW")
                            ->validationMessages([
                                'required' => '請填寫標題',
                            ])
                        ])->locales(["zh_TW", "en"])
                        ->columnSpanFull()->columns(3),
                    ]),
                    Tab::make('Banner 設定')->schema([
                        FileUpload::make('banner_pc')->label("Banner (PC)")
                        ->disk("public")
                        // ->helperText('建議寬高限制為:1280*720px，檔案大小限制為1M以下')->maxSize('1024')
                        ->directory("esg")->required()
                        ->validationMessages([
                            'required' => '請上傳圖片',
                        ]),
                        FileUpload::make('banner_mobile')->label("Banner (Mobile)")
                        ->disk("public")
                        // ->helperText('建議寬高限制為:600*896px，檔案大小限制為1M以下')->maxSize('1024')
                        ->directory("esg")->required()
                        ->validationMessages([
                            'required' => '請上傳圖片',
                        ]),
                        Translate::make()->schema(fn (string $locale) => [
                            TextInput::make('banner_alt')
                            ->label("Banner 圖片註釋")
                            ->required($locale == "zh_TW")
                            ->validationMessages([
                                'required' => '請填寫圖片註釋',
                            ]),
                            Textarea::make("description")->rows(5)->columnSpanFull()->label("短文"),
                        ])->locales(["zh_TW", "en"])
                        ->columnSpanFull(),
                    ]),
                    Tab::make("段落設計")->schema([
                        //1: 純文字 2:區塊文字 3:表格 4:影片 or 圖片 5:左右圖文
                        Repeater::make("paragraphs")->label("")->schema([
                            TextInput::make('item_key')
                                ->default(fn () => Str::random())
                                ->hidden()
                                ->afterStateHydrated(function (TextInput $component, $state) {
                                    if (empty($state)) {
                                        $component->state(Str::random());
                                    }
                                }),
                            Radio::make("type")->options([
                                1 => "純文字",
                                2 => "區塊文字",
                                3 => "表格",
                                4 => "圖片",
                                5 => "影片",
                            ])->label("")->default(1)->Live(),
                            Group::make()->schema([
                                Translate::make()->schema(fn (string $locale) => [
                                    RichEditor::make('content.text_content')
                                    ->fileAttachmentsDirectory('attachments')
                                    ->fileAttachmentsVisibility('private')
                                    ->disableToolbarButtons(['attachFiles'])
                                    ->required($locale == "zh_TW")
                                    ->validationMessages([
                                        'required' => '請填寫文字內容',
                                    ]),
                                ])
                                ->locales(["zh_TW", "en"])
                                ->id(fn ($get) => "para_text_" . $get('item_key')),
                            ])->visible(fn (Get $get):bool => $get("type") == 1),
                            Group::make()->schema([
                                Section::make('區塊文字設定')->schema([
                                    // 文字區塊重複器
                                    Repeater::make("content.text_blocks")->schema([
                                        TextInput::make('block_item_key')
                                            ->default(fn () => Str::random())
                                            ->hidden()
                                            ->afterStateHydrated(function (TextInput $component, $state) {
                                                if (empty($state)) {
                                                    $component->state(Str::random());
                                                }
                                            }),
                                        // 多語系內容
                                        Translate::make()->schema(fn (string $locale) => [
                                            RichEditor::make('block_content')
                                                ->disableToolbarButtons(['attachFiles'])
                                                ->required($locale == "zh_TW")
                                                ->validationMessages([
                                                    'required' => '請填寫文字內容',
                                                ]),
                                        ])
                                        ->locales(["zh_TW", "en"])
                                        ->id(fn ($get) => "text_block_" . $get('block_item_key')),

                                    ])
                                    ->label("")
                                    ->addActionLabel('增加區塊')
                                    ->orderColumn('order')
                                    ->reorderableWithButtons()
                                    ->cloneable()
                                    ->minItems(1)
                                    ->maxItems(20)
                                    ->defaultItems(1),
                                ]),
                            ])->visible(fn (Get $get):bool => $get('type') == 2),
                            Group::make()->schema([
                                Section::make('表格設定')->schema([
                                    Radio::make('content.is_card')
                                            ->label('手機板卡片顯示')
                                            ->options([
                                                '1' => '是',  // 改為數字鍵值
                                                '0' => '否'
                                            ])
                                            ->default('0')
                                            ->inline(),
                                    // 表格資料
                                    Placeholder::make('table_builder_info')->label("")->content('請先設定表格欄數，然後填入表格資料'),
                                    Grid::make(3)->schema([
                                        Radio::make('content.column_count')
                                            ->label('欄數')
                                            ->options([
                                                2 => '2欄',  // 改為數字鍵值
                                                3 => '3欄',
                                                4 => '4欄'
                                            ])
                                            ->default(2)
                                            ->inline()
                                            ->live()
                                            ->reactive(), // ✅ 添加 reactive()
                                    ]),
                                    Translate::make()->schema(fn (string $locale) => [
                                        Grid::make(2)  // 改用 Grid 來支援動態 columns
                                            ->schema([
                                                TextInput::make('content.head1')->label('標題第1欄')->required()
                                                ->validationMessages([
                                                    'required' => '請填寫',
                                                ]),
                                                Radio::make('content.head_align1')
                                                    ->label('對齊')
                                                    ->options([
                                                        1 => '置左',  // 改為數字鍵值
                                                        2 => '置中',
                                                        3 => '置右'
                                                    ])
                                                    ->default(1),
                                                TextInput::make('content.head2')->label('標題第2欄')->required()
                                                ->validationMessages([
                                                    'required' => '請填寫',
                                                ]),
                                                Radio::make('content.head_align2')
                                                    ->label('對齊')
                                                    ->options([
                                                        1 => '置左',  // 改為數字鍵值
                                                        2 => '置中',
                                                        3 => '置右'
                                                    ])
                                                    ->default(1),
                                                TextInput::make('content.head3')->label('標題第3欄')
                                                    ->visible(fn (Get $get) => intval($get('content.column_count')) >= 3)->columnSpan(1),
                                                    Radio::make('content.head_align3')
                                                        ->label('對齊')
                                                        ->options([
                                                            1 => '置左',  // 改為數字鍵值
                                                            2 => '置中',
                                                            3 => '置右'
                                                        ])
                                                        ->default(1)
                                                        ->visible(fn (Get $get) => intval($get('content.column_count')) >= 3)->columnSpan(1),
                                                TextInput::make('content.head4')->label('標題第4欄')
                                                    ->visible(fn (Get $get) => intval($get('content.column_count')) >= 4)->columnSpan(1),
                                                    Radio::make('content.head_align4')
                                                        ->label('對齊')
                                                        ->options([
                                                            1 => '置左',  // 改為數字鍵值
                                                            2 => '置中',
                                                            3 => '置右'
                                                        ])
                                                        ->default(1)
                                                        ->visible(fn (Get $get) => intval($get('content.column_count')) >= 4)->columnSpan(1),
                                            ])
                                            ->reactive()  // 加入響應式
                                    ])->locales(["zh_TW", "en"]),
                                    Repeater::make('content.simple_table_rows')
                                        ->label('表格資料')
                                        ->schema([
                                            TextInput::make('simple_table_rows_key')
                                                ->default(fn () => Str::random())
                                                ->hidden()
                                                ->afterStateHydrated(function (TextInput $component, $state) {
                                                    if (empty($state)) {
                                                        $component->state(Str::random());
                                                    }
                                                }),
                                            Translate::make()->schema(fn (string $locale) => [
                                                Grid::make(1)  // 改用 Grid 來支援動態 columns
                                                    ->schema([
                                                        Radio::make('align1')
                                                            ->label('對齊')
                                                            ->options([
                                                                1 => '置左',  // 改為數字鍵值
                                                                2 => '置中',
                                                                3 => '置右'
                                                            ])
                                                        ->default(1),
                                                        RichEditor::make('col1')
                                                            ->label('第1欄')
                                                            ->disableToolbarButtons(['attachFiles'])
                                                            ->required($locale == "zh_TW")
                                                            ->validationMessages([
                                                                'required' => '請填寫',
                                                            ]),
                                                        // TextInput::make('col2')->label('第2欄')->required(),
                                                        Radio::make('align2')
                                                            ->label('對齊')
                                                            ->options([
                                                                1 => '置左',  // 改為數字鍵值
                                                                2 => '置中',
                                                                3 => '置右'
                                                            ])
                                                            ->default(1),
                                                        RichEditor::make('col2')
                                                            ->label('第2欄')
                                                            ->disableToolbarButtons(['attachFiles'])
                                                            ->required($locale == "zh_TW")
                                                            ->validationMessages([
                                                                'required' => '請填寫',
                                                            ]),
                                                        Radio::make('align3')
                                                            ->label('對齊')
                                                            ->options([
                                                                1 => '置左',  // 改為數字鍵值
                                                                2 => '置中',
                                                                3 => '置右'
                                                            ])
                                                            ->default(1)
                                                            ->visible(fn (Get $get) => intval($get('../../../content.column_count')) >= 3),
                                                        RichEditor::make('col3')
                                                            ->label('第3欄')
                                                            ->disableToolbarButtons(['attachFiles'])
                                                            ->visible(fn (Get $get) => intval($get('../../../content.column_count')) >= 3)
                                                            ->required($locale == "zh_TW" && fn (Get $get)=> intval($get("../../../content.column_count")) >= 3)
                                                            ->validationMessages([
                                                                'required' => '請填寫',
                                                            ]),
                                                            Radio::make('align4')
                                                                ->label('對齊')
                                                                ->options([
                                                                    1 => '置左',  // 改為數字鍵值
                                                                    2 => '置中',
                                                                    3 => '置右'
                                                                ])
                                                                ->default(1)
                                                                ->visible(fn (Get $get) => intval($get('../../../content.column_count')) >= 4),
                                                            RichEditor::make('col4')
                                                                ->label('第4欄')
                                                                ->disableToolbarButtons(['attachFiles'])
                                                                ->visible(fn (Get $get) => intval($get('../../../content.column_count')) >= 4)
                                                                ->required($locale == "zh_TW" && fn (Get $get)=> intval($get("../../../content.column_count")) >= 4)
                                                                ->validationMessages([
                                                                    'required' => '請填寫',
                                                                ]),
                                                    ])
                                                    ->reactive()  // 加入響應式
                                            ])->locales(["zh_TW", "en"]),
                                        ])
                                        ->id(fn ($get) => "simple_table_" . $get('simple_table_key'))
                                        ->addActionLabel('新增列')
                                        ->reorderableWithButtons()
                                        ->minItems(1)
                                ]),
                            ])->visible(fn (Get $get):bool => $get('type') == 3),
                            Group::make()->schema([
                                Section::make('')->schema([
                                    Repeater::make("content.multiple_images")->schema([
                                        TextInput::make('para_img_item_key')
                                            ->default(fn () => Str::random())
                                            ->hidden()
                                            ->afterStateHydrated(function (TextInput $component, $state) {
                                                if (empty($state)) {
                                                    $component->state(Str::random());
                                                }
                                            }),
                                        Translate::make()->schema(fn (string $locale) => [
                                            TextInput::make('image_alt')->label("圖片註文")
                                        ])->locales(["zh_TW", "en"])
                                        ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
                                        FileUpload::make('image_url')->label("")->disk("public")
                                        // ->helperText('建議寬高限制為:1080*675px，檔案大小限制為1M以下')->maxSize('1024')
                                        ->directory("esg/paragraphPhoto")
                                        ->maxFiles(10)
                                        ->required()
                                        ->validationMessages([
                                            'required' => '請上傳圖片',
                                        ]),
                                    ])
                                    ->addActionLabel('新增')
                                    ->label("")
                                    ->orderColumn('order')
                                ])
                            ])->visible(fn (Get $get):bool => $get("type") == 4),
                            Group::make()->schema([
                                Section::make("")->schema([
                                    FileUpload::make('content.video_img')->label("影片底圖")
                                    ->disk("public")
                                    ->directory("esg/paragraphVideo"),
                                    TextInput::make('content.link')->label("網址")->required()
                                    ->validationMessages([
                                        'required' => '請附上連結',
                                    ]),
                                    Translate::make()->schema(fn (string $locale) => [
                                        TextInput::make('content.video_alt')->label("影片註文"),
                                    ])->locales(["zh_TW", "en"])
                                ]),
                            ])->visible(fn (Get $get):bool => $get("type") == 5),
                        ])
                        ->relationship("paragraphs")
                        ->addActionLabel('新增段落')
                        ->collapsible()
                        ->reorderableWithButtons()
                        ->orderColumn('order')
                        ->cloneable()
                    ])->columnSpanFull(),
                ])
                ->columnSpanFull()
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                //
                TextColumn::make("title")->label("標題"),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ]);
    }

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

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