<?php

namespace App\Filament\Resources;

use App\Filament\Exports\StickerMappingMasterExporter;
use App\Filament\Imports\StickerMappingMasterImporter;
use App\Filament\Resources\StickerMappingMasterResource\Pages;
use App\Filament\Resources\StickerMappingMasterResource\RelationManagers;
use App\Models\Item;
use App\Models\ItemCharacteristic;
use App\Models\Machine;
use App\Models\StickerMappingMaster;
use App\Models\StickerStructureDetail;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
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\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;

class StickerMappingMasterResource extends Resource
{
    protected static ?string $model = StickerMappingMaster::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\TextInput::make('plant_id')
    //                 ->required()
    //                 ->numeric(),
    //             Forms\Components\TextInput::make('item_id')
    //                 ->required()
    //                 ->numeric(),
    //             Forms\Components\Textarea::make('sticker1')
    //                 ->columnSpanFull(),
    //             Forms\Components\Textarea::make('sticker2')
    //                 ->columnSpanFull(),
    //             Forms\Components\Textarea::make('sticker3')
    //                 ->columnSpanFull(),
    //             Forms\Components\Textarea::make('sticker4')
    //                 ->columnSpanFull(),
    //             Forms\Components\Textarea::make('sticker5')
    //                 ->columnSpanFull(),
    //             Forms\Components\Textarea::make('created_by')
    //                 ->columnSpanFull(),
    //             Forms\Components\Textarea::make('updated_by')
    //                 ->columnSpanFull(),
    //         ]);
    // }


    public static function form(Form $form): Form
{
    return $form
        ->schema([
            /* -------- Basic Mapping -------- */
            Section::make('Basic Mapping')
                ->schema([
                    Select::make('plant_id')
                        ->label('Plant')
                        ->reactive()
                        ->relationship('plant', 'name')
                        ->required(),

                    Select::make('item_characteristic_id')
                        ->label('Item Code')
                        ->reactive()
                        //->relationship('item', 'code')
                        ->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()
                    ->required(),
                ])
                ->columns(2),

            /* -------- Sticker 1 -------- */
            Section::make('Sticker 1')
                ->schema([
                    Select::make('sticker_structure1_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker1_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker1Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker1_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 2 -------- */
            Section::make('Sticker 2')
                ->schema([
                    Select::make('sticker_structure2_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker2_machine_id')
                        ->label('Work Center')
                       // ->relationship('sticker2Machine', 'name')
                       ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker2_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 3 -------- */
            Section::make('Sticker 3')
                ->schema([
                    Select::make('sticker_structure3_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker3_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker3Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker3_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 4 -------- */
            Section::make('Sticker 4')
                ->schema([
                    Select::make('sticker_structure4_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker4_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker4Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker4_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 5 -------- */
            Section::make('Sticker 5')
                ->schema([
                    Select::make('sticker_structure5_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker5_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker5Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker5_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 6 -------- */
            Section::make('Sticker 6')
                ->schema([
                    Select::make('sticker_structure6_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker6_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker6Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker6_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 7 -------- */
            Section::make('Sticker 7')
                ->schema([
                    Select::make('sticker_structure7_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker7_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker7Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker7_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),

            /* -------- Sticker 8 -------- */
            Section::make('Sticker 8')
                ->schema([
                    Select::make('sticker_structure8_id')
                        ->label('Sticker ID')
                        ->options(function (callable $get) {
                            return StickerStructureDetail::pluck('sticker_id', 'id');
                        })
                        ->searchable(),
                    Select::make('sticker8_machine_id')
                        ->label('Work Center')
                        //->relationship('sticker8Machine', 'name')
                        ->options(function (callable $get) {
                            $plantId = $get('plant_id');
                            if (empty($plantId)) {
                                return [];
                            }
                            return Machine::where('plant_id', $plantId)->pluck('work_center', 'id');
                        })
                        ->searchable(),
                    TextInput::make('sticker8_print_ip')
                        ->label('Printer IP')
                        ->ipv4(),
                ])
                ->columns(2),
        ]);
}
    public static function table(Table $table): Table
    {
        return $table
            ->columns([
            Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
            Tables\Columns\TextColumn::make('plant.name')
                ->label('Plant')
                ->alignCenter()
                ->sortable(),
            Tables\Columns\TextColumn::make('itemCharacteristic.item.code')
                ->label('Item')
                ->alignCenter()
                ->sortable(),
            Tables\Columns\TextColumn::make('sticker1Structure.sticker_id')
                ->label('Sticker 1')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker1Machine.work_center')
                ->label('WC 1')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker1_print_ip')
                ->label('Printer IP 1')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker2Structure.sticker_id')
                ->label('Sticker 2')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker2Machine.work_center')
                ->label('WC 2')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker2_print_ip')
                ->label('Printer IP 2')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker3Structure.sticker_id')
                ->label('Sticker 3')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker3Machine.work_center')
                ->label('WC 3')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker3_print_ip')
                ->label('Printer IP 3')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker4Structure.sticker_id')
                ->label('Sticker 4')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker4Machine.work_center')
                ->label('WC 4')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker4_print_ip')
                ->label('Printer IP 4')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker5Structure.sticker_id')
                ->label('Sticker 5')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker5Machine.work_center')
                ->label('WC 5')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker5_print_ip')
                ->label('Printer IP 5')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker6Structure.sticker_id')
                ->label('Sticker 6')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker6Machine.work_center')
                ->label('WC 6')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker6_print_ip')
                ->label('Printer IP 6')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker7Structure.sticker_id')
                ->label('Sticker 7')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker7Machine.work_center')
                ->label('WC 7')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker7_print_ip')
                ->label('Printer IP 7')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker8Structure.sticker_id')
                ->label('Sticker 8')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker8Machine.work_center')
                ->label('WC 8')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('sticker8_print_ip')
                ->label('Printer IP 8')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('created_at')
                ->label('Created At')
                ->alignCenter()
                ->dateTime()
                ->sortable()
                ->toggleable(isToggledHiddenByDefault: true),
            Tables\Columns\TextColumn::make('updated_at')
                ->label('Updated At')
                ->alignCenter()
                ->dateTime()
                ->sortable()
                ->toggleable(isToggledHiddenByDefault: true),
            Tables\Columns\TextColumn::make('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()
                ->importer(StickerMappingMasterImporter::class)
                ->label('Import Sticker Mapping Master')
                ->color('warning')
                ->visible(function () {
                    return Filament::auth()->user()->can('view import sticker mapping master');
                }),
            ExportAction::make()
                ->exporter(StickerMappingMasterExporter::class)
                ->label('Export Sticker Mapping Master')
                ->color('warning')
                ->visible(function () {
                    return Filament::auth()->user()->can('view export sticker mapping master');
                }),
        ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListStickerMappingMasters::route('/'),
            'create' => Pages\CreateStickerMappingMaster::route('/create'),
            'view' => Pages\ViewStickerMappingMaster::route('/{record}'),
            'edit' => Pages\EditStickerMappingMaster::route('/{record}/edit'),
        ];
    }

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