<?php

namespace App\Filament\Resources;

use App\Filament\Exports\StickerMasterExporter;
//use App\Filament\Imports\ShiftImporter;
use App\Filament\Imports\StickerMasterImporter;
use App\Filament\Resources\StickerMasterResource\Pages;
use App\Models\Plant;
//use App\Filament\Resources\StickerMasterResource\RelationManagers;
use App\Models\StickerMaster;
//use Closure;
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\Get;
use Filament\Forms\Set;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
// use Illuminate\Validation\Rule;

class StickerMasterResource extends Resource
{
    protected static ?string $model = StickerMaster::class;

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

    protected static ?string $navigationGroup = 'Master Entries';

    protected static ?int $navigationSort = 8;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->relationship('plant', 'name')
                    ->reactive()
                    ->nullable()
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;
                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                    })
                    ->default(function () {
                        return optional(StickerMaster::latest()->first())->plant_id;
                    })
                    ->disabled(fn (Get $get) => !empty($get('id'))) //disable in edit if user try to change
                    ->afterStateUpdated(fn (callable $set) =>
                        $set('item_id', null) &  //when plant changed remove all the data which is in text input box
                        $set('item_description', null) &
                        $set('item_error', null) &
                        $set('panel_box_code', null) &
                        $set('load_rate', null) &
                        $set('bundle_quantity', null) &
                        $set('material_type', null) &
                        $set('part_validation1', null) &
                        $set('part_validation2', null) &
                        $set('part_validation3', null) &
                        $set('part_validation4', null) &
                        $set('part_validation5', null) &
                        $set('laser_part_validation1', null) &
                        $set('laser_part_validation2', null) &
                        $set('serial_number_motor', false) &
                        $set('serial_number_pump', false)  &
                        $set('serial_number_pumpset', false) &
                        $set('pack_slip_motor', false) &
                        $set('pack_slip_pump', false) &
                        $set('pack_slip_pumpset', false) &
                        $set('name_plate_motor', false) &
                        $set('name_plate_pump', false) &
                        $set('name_plate_pumpset', false) &
                        $set('tube_sticker_motor', false) &
                        $set('tube_sticker_pump', false) &
                        $set('tube_sticker_pumpset', false) &
                        $set('warranty_card', false)
                    )
                    ->required(),

                Forms\Components\Select::make('item_id')
                    ->label('Item Code')
                    ->options(function (callable $get) {
                        if (!$get('plant_id')) {
                            return [];
                        }

                        return \App\Models\Item::where('plant_id', $get('plant_id'))
                            ->pluck('code', 'id')
                            ->toArray();
                    })
                    // ->rule(function (callable $get) {
                    //     return Rule::unique('items', 'code')
                    //         ->where('plant_id', $get('plant_id'))
                    //         ->ignore($get('id')); // Ignore current record during updates
                    // })
                    ->required()
                    ->nullable()
                    ->searchable()
                    ->reactive()
                    // ->disabled(fn (Get $get) => !empty($get('id')))
                    ->live(debounce: 500) // Enable live updates
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        $itemId = $get('item_id');

                        //If plant_id is changed or empty, reset everything
                        if (blank($plantId)) {
                            $set('item_id', null);
                            $set('item_error', null);
                            $set('item_description', null);
                            return;
                        }

                        if (blank($itemId)) {
                            $set('item_error', null);
                            $set('item_description', null);
                            return;
                        }

                        $availableItems = \App\Models\Item::where('plant_id', $plantId)->exists();
                        if (!$availableItems) {
                            $set('item_error', null);
                            return;
                        }

                        // Ensure `item_id` is not cleared
                        if (!$plantId || !$itemId) {
                            $set('item_description', null);
                            return;
                        }

                        // Check if item exists for the selected plant
                        $item = \App\Models\Item::where('plant_id', $plantId)
                            ->where('id', $itemId)
                            ->first();

                        if ($item) {
                            $set('item_description', $item->description);
                        } else {
                            $set('item_description', null);
                        }

                        $duplicateSticker = StickerMaster::where('plant_id', $plantId)
                            ->where('item_id', $itemId)
                            ->exists();
                        if(!$get('id'))
                        {
                            $set('item_error', $duplicateSticker ? 'Item Code already exists for the selected plant.' : null);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('item_error') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('item_error') ? $get('item_error') : null)
                    ->hintColor('danger'),

                Forms\Components\TextInput::make('item_description')
                    ->label('Description')
                    ->required()
                    ->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
                        if ($get('id')) {
                            $itemId = StickerMaster::where('id', $get('id'))->first()?->item_id;
                            if ($itemId) {
                                $item = \App\Models\Item::where('id', $itemId)->first()?->description;
                                if ($item) {
                                    $set('item_description', $item);
                                } else {
                                    $set('item_description', null);
                                }
                            } else {
                                $set('item_description', null);
                            }
                        }
                    })
                    ->reactive()
                    ->readOnly(true),

                Forms\Components\TextInput::make('part_validation1')
                    ->label('Part Validation 1')
                    ->nullable(),

                Forms\Components\TextInput::make('part_validation2')
                    ->label('Part Validation 2')
                    ->nullable(),

                Forms\Components\TextInput::make('part_validation3')
                    ->label('Part Validation 3')
                    ->nullable(),

                Forms\Components\TextInput::make('part_validation4')
                    ->label('Part Validation 4')
                    ->nullable(),

                Forms\Components\TextInput::make('part_validation5')
                    ->label('Part Validation 5 (Capacitor QR)')
                    ->nullable(),

                Forms\Components\TextInput::make('laser_part_validation1')
                    ->label('Laser Part Validation 1')
                    ->nullable(),

                Forms\Components\TextInput::make('laser_part_validation2')
                    ->label('Laser Part Validation 2')
                    ->nullable(),

                Forms\Components\TextInput::make('panel_box_code')
                    ->label('Panel Box Code')
                    ->readOnly(fn (callable $get) => $get('material_type'))
                    ->nullable(),

                Forms\Components\TextInput::make('load_rate')
                    ->label('Load Rate')
                    ->default(0)
                    ->required()
                    ->disabled(function ($get) {
                        return $get('material_type');
                        })
                    ->integer(),

                Forms\Components\Select::make('material_type')
                    ->label('Material Type')
                    ->options([
                        '1' => 'Individual',
                        '2' => 'Bundle',
                        '3' => 'Quantity',
                    ])
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {

                        if ($state)
                        {
                            $set('panel_box_code', null);
                            $set('load_rate', 0);
                        }

                        if ($state !== "2")
                        {
                            $set('bundle_quantity', null);
                        }
                        else
                        {
                            $set('bundle_quantity', 2);
                        }
                        //$plantId = $get('plant_id');
                    })
                    ->nullable(),

                Forms\Components\TextInput::make('bundle_quantity')
                    ->label('Bundle Quantity')
                    ->integer()
                    ->readOnly(fn (callable $get) => $get('material_type') !== "2")
                    ->nullable()
                    ->minValue(2)
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if($get('material_type') !== "2")
                        {
                            $set('bundle_quantity', null);
                        }
                        else if ($get('bundle_quantity') < 2)
                        {
                            $set('bundle_quantity', 2);
                        }
                    }),

                Forms\Components\Checkbox::make('serial_number_motor')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('serial_number_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('serial_number_pumpset'))
                        {
                            $set('serial_number_motor', false);
                        }
                        })
                    ->dehydrateStateUsing(fn ($state): mixed => $state ? $state : null),

                Forms\Components\Checkbox::make('serial_number_pump')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('serial_number_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('serial_number_pumpset'))
                        {
                            $set('serial_number_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('serial_number_pumpset')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('serial_number_motor') || $get('serial_number_pump');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('serial_number_pumpset'))
                        {
                            $set('serial_number_motor', false);
                            $set('serial_number_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('pack_slip_motor')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('pack_slip_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('pack_slip_pumpset'))
                        {
                            $set('pack_slip_motor', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('pack_slip_pump')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('pack_slip_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('pack_slip_pumpset'))
                        {
                            $set('pack_slip_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('pack_slip_pumpset')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('pack_slip_motor') || $get('pack_slip_pump');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('pack_slip_pumpset'))
                        {
                            $set('pack_slip_motor', false);
                            $set('pack_slip_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('name_plate_motor')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('name_plate_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('name_plate_pumpset'))
                        {
                            $set('name_plate_motor', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('name_plate_pump')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('name_plate_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('name_plate_pumpset'))
                        {
                            $set('name_plate_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('name_plate_pumpset')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('name_plate_motor') || $get('name_plate_pump');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('name_plate_pumpset'))
                        {
                            $set('name_plate_motor', false);
                            $set('name_plate_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('tube_sticker_motor')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('tube_sticker_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('tube_sticker_pumpset'))
                        {
                            $set('tube_sticker_motor', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('tube_sticker_pump')
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('tube_sticker_pumpset');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('tube_sticker_pumpset'))
                        {
                            $set('tube_sticker_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\Checkbox::make('tube_sticker_pumpset')
                    ->nullable()
                    ->reactive()
                    ->disabled(function ($get) {
                        return $get('tube_sticker_motor') || $get('tube_sticker_pump');
                    })
                    ->afterStateUpdated(function ($state, callable $set,callable $get) {
                        if ($get('tube_sticker_pumpset'))
                        {
                            $set('tube_sticker_motor', false);
                            $set('tube_sticker_pump', false);
                        }
                    })
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null), //to pass null value

                Forms\Components\Checkbox::make('warranty_card')
                    ->nullable()
                    ->dehydrateStateUsing(fn ($state) => $state ? $state : null),

                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table

        ->columns([
            // Tables\Columns\TextColumn::make('id')
            //     ->label('ID')
            //     ->numeric()
            //     ->sortable(),
            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()
                ->searchable(),
            Tables\Columns\TextColumn::make('item.code')
                ->label('Item Code')
                ->alignCenter()
                ->sortable()
                ->searchable(),
            Tables\Columns\CheckboxColumn::make('serial_number_motor')
                ->label('Serial Number Motor')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('serial_number_pump')
                ->label('Serial Number Pump')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('serial_number_pumpset')
                ->label('Serial Number Pumpset')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('pack_slip_motor')
                ->label('Pack Slip Motor')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('pack_slip_pump')
                ->label('Pack Slip Pump')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('pack_slip_pumpset')
                ->label('Pack Slip Pumpset')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('name_plate_motor')
                ->label('Name Plate Motor')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('name_plate_pump')
                ->label('Name Plate Pump')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('name_plate_pumpset')
                ->label('Name Plate Pumpset')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('tube_sticker_motor')
                ->label('Tube Sticker Motor')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('tube_sticker_pump')
                ->label('Tube Sticker Pump')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('tube_sticker_pumpset')
                ->label('Tube Sticker Pumpset')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\CheckboxColumn::make('warranty_card')
                ->label('Warranty Card')
                ->disabled(true)
                ->alignCenter()
                ->sortable(),
            Tables\Columns\TextColumn::make('part_validation1')
                ->label('Part Validation 1')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('part_validation2')
                ->label('Part Validation 2')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('part_validation3')
                ->label('Part Validation 3')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('part_validation4')
                ->label('Part Validation 4')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('part_validation5')
                ->label('Part Validation 5')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('laser_part_validation1')
                ->label('Laser Part Validation 1')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('laser_part_validation2')
                ->label('Laser Part Validation 2')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('panel_box_code')
                ->label('Panel Box Code')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('load_rate')
                ->label('Load Rate')
                ->alignCenter()
                ->sortable(),
            Tables\Columns\TextColumn::make('bundle_quantity')
                ->label('Bundle Quantity')
                ->alignCenter(),
            Tables\Columns\TextColumn::make('material_type')
                ->label('Material Type')
                ->alignCenter()
                ->formatStateUsing(function ($state) {
                    if (is_null($state) || $state === '') {
                        return '';
                    }
                    return match ($state) {
                        1 => 'Individual',
                        2 => 'Bundle',
                        3 => 'Quantity',
                        default => '',
                    };
                }),
            Tables\Columns\TextColumn::make('created_at')
                ->label('Created At')
                ->dateTime()
                ->alignCenter()
                ->sortable(),
            Tables\Columns\TextColumn::make('updated_at')
                ->label('Updated At')
                ->dateTime()
                ->alignCenter()
                ->sortable()
                ->toggleable(isToggledHiddenByDefault: true),
            Tables\Columns\TextColumn::make('deleted_at')
                ->label('Deleted At')
                ->dateTime()
                ->alignCenter()
                ->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(StickerMasterImporter::class)
                ->visible(function() {
                    return Filament::auth()->user()->can('view import sticker master');
                }),
            ExportAction::make()
                ->exporter(StickerMasterExporter::class)
                ->visible(function() {
                    return Filament::auth()->user()->can('view export sticker master');
                }),
        ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListStickerMasters::route('/'),
            'create' => Pages\CreateStickerMaster::route('/create'),
            'view' => Pages\ViewStickerMaster::route('/{record}'),
            'edit' => Pages\EditStickerMaster::route('/{record}/edit'),
        ];
    }

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