<?php

namespace App\Filament\Resources;

use App\Filament\Exports\StickerStructureDetailExporter;
use App\Filament\Imports\StickerStructureDetailImporter;
use App\Filament\Resources\StickerStructureDetailResource\Pages;
use App\Filament\Resources\StickerStructureDetailResource\RelationManagers;
use App\Models\ItemCharacteristic;
use App\Models\StickerStructureDetail;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Actions\Action;
use Illuminate\Support\HtmlString;
use Filament\Forms\Components\Html;
use Filament\Forms\Get;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;

class StickerStructureDetailResource extends Resource
{
    protected static ?string $model = StickerStructureDetail::class;

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

    protected static ?string $navigationGroup = 'Customized Sticker Printing';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->relationship('plant', 'name')
                    ->reactive(),
                Forms\Components\Select::make('item_characteristic_id')
                    ->label('Item')
                    ->reactive()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');

                        if (! $plantId) {
                            return [];
                        }

                        return ItemCharacteristic::query()
                            ->whereHas('item', function ($query) use ($plantId) {
                                $query->where('plant_id', $plantId);
                            })
                            ->with('item')
                            ->get()
                            ->mapWithKeys(fn ($ic) => [
                                $ic->id => $ic->item->code,
                            ]);
                    })
                    ->searchable(),
                Forms\Components\TextInput::make('sticker_id')
                    ->label('Sticker ID')
                    ->reactive()
                    ->required()
                    ->afterStateUpdated(function ($state, callable $set) {
                    //\Log::info('Sticker ID typed:', ['sticker_id' => $state]);
                    $set('sticker_id_live', $state);
                }),
                Forms\Components\TextInput::make('sticker_width')
                    ->label('Sticker Width')
                    ->required(),
                Forms\Components\TextInput::make('sticker_height')
                    ->label('Sticker Height')
                    ->required(),
                Forms\Components\TextInput::make('sticker_lmargin')
                    ->label('Sticker Left Margin')
                    ->required(),
                Forms\Components\TextInput::make('sticker_rmargin')
                    ->label('Sticker Right Margin')
                    ->required(),
                Forms\Components\TextInput::make('sticker_tmargin')
                    ->label('Sticker Top Margin')
                    ->required(),
                Forms\Components\TextInput::make('sticker_bmargin')
                    ->label('Sticker Bottom Margin')
                    ->required(),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('sticker_id_live')
                ->default(fn ($get) => $get('sticker_id'))
                ->reactive()
                ->afterStateUpdated(function ($state, callable $set) {
                    $set('sticker_id_live', $state);
                }),
                Forms\Components\ViewField::make('generate_template')
                    ->view('fields.generate-template')
                    ->reactive()
                    //->key(fn ($get) => 'generate-template' . ($get('sticker_id_live') ?? 'empty'))
                    ->key(fn (Get $get) =>
                        'generate-template-' .
                        ($get('sticker_id_live') ?? 'empty') . '-' .
                        ($get('plant_id') ?? 'empty') . '-' .
                        ($get('item_characteristic_id') ?? 'empty')
                    )
                    // ->viewData(fn (Get $get) => [
                    //     'sticker_id' => $get('sticker_id_live') ?? 'empty',
                    // ]),
                    ->viewData(fn (Get $get) => [
                        'sticker_id' => $get('sticker_id_live') ?? 'empty',
                        'plant_id' => $get('plant_id') ?? 'empty',
                        'item_characteristic_id' => $get('item_characteristic_id') ?? 'empty',
                    ])

            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sticker_id')
                    ->label('Sticker ID'),
                Tables\Columns\TextColumn::make('sticker_width')
                    ->label('Sticker Width'),
                Tables\Columns\TextColumn::make('sticker_height')
                    ->label('Sticker Height'),
                Tables\Columns\TextColumn::make('sticker_lmargin')
                    ->label('Sticker Left Margin'),
                Tables\Columns\TextColumn::make('sticker_rmargin')
                    ->label('Sticker Right Margin'),
                Tables\Columns\TextColumn::make('sticker_tmargin')
                    ->label('Sticker Top Margin'),
                Tables\Columns\TextColumn::make('sticker_bmargin')
                    ->label('Sticker Bottom Margin'),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Sticker Structure Details')
                    ->color('warning')
                    ->importer(StickerStructureDetailImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import sticker structure details');
                    }),
                ExportAction::make()
                    ->label('Export Sticker Structure Details')
                    ->color('warning')
                    ->exporter(StickerStructureDetailExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export sticker structure details');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListStickerStructureDetails::route('/'),
            'create' => Pages\CreateStickerStructureDetail::route('/create'),
            'view' => Pages\ViewStickerStructureDetail::route('/{record}'),
            'edit' => Pages\EditStickerStructureDetail::route('/{record}/edit'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
