<?php

namespace App\Filament\Resources;

use App\Filament\Exports\ProductCharacteristicsMasterExporter;
use App\Filament\Imports\ProductCharacteristicsMasterImporter;
use App\Filament\Resources\ProductCharacteristicsMasterResource\Pages;
use App\Filament\Resources\ProductCharacteristicsMasterResource\RelationManagers;
use App\Models\Line;
use App\Models\Machine;
use App\Models\Plant;
use App\Models\ProductCharacteristicsMaster;
use App\Models\WorkGroupMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
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\ImportAction;
use Filament\Tables\Actions\ExportAction;

class ProductCharacteristicsMasterResource extends Resource
{
    protected static ?string $model = ProductCharacteristicsMaster::class;

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

    protected static ?string $navigationGroup = 'Process Order';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->relationship('plant', 'name')
                    ->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();
                    })
                    ->reactive()
                    ->required(),
                Forms\Components\Select::make('item_id')
                    ->label('Item Code')
                    //->relationship('item', 'code')
                    ->searchable()
                    ->reactive()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (empty($plantId)) {
                            return [];
                        }
                        return \App\Models\Item::where('plant_id', $plantId)->pluck('code', 'id');
                    })
                    ->required(),
                Forms\Components\Select::make('line_id')
                    ->label('Line')
                    ->reactive()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (empty($plantId)) {
                            return [];
                        }
                        return Line::where('plant_id', $plantId)->pluck('name', 'id');
                    })
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $set('machine_id', null);

                        if (!$get('work_group_master_id')) {
                            $set('machine_id', null);
                        }
                    })
                    ->required(),
                   // ->relationship('line', 'name'),
                Forms\Components\Select::make('work_group_master_id')
                    ->label('Group Work Center')
                    ->required()
                    ->reactive()
                    ->options(function (callable $get) {
                        if (!$get('plant_id') || !$get('line_id')) {
                            return [];
                        }

                        $line = Line::find($get('line_id'));
                        $workGroupIds = [];
                        for ($i = 1; $i <= $line->no_of_operation; $i++) {
                            $column = "work_group{$i}_id";
                            if (!empty($line->$column)) {
                                $workGroupIds[] = $line->$column;
                            }
                        }

                        return WorkGroupMaster::where('plant_id', $get('plant_id'))->whereIn('id', $workGroupIds)->pluck('name', 'id')->toArray();
                    })
                    ->disabled(fn (Get $get) => !empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $lineId = $get('line_id');
                        if (!$lineId) {
                            $set('mGroupWorkError', 'Please select a line first.');
                            $set('machine_id', null);
                            return;
                        }
                        else
                        {
                            // $grpWrkCnr = Line::find($lineId)->group_work_center;
                            // if (!$grpWrkCnr || Str::length($grpWrkCnr) < 1)
                            // {
                            //     $set('mGroupWorkError', 'Please select a group work center line.');
                            //     $set('line_id', null);
                            //     return;
                            // }
                            $set('mGroupWorkError', null);
                            $set('machine_id', null);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('mGroupWorkError') ? 'border-red-500' : '',
                    ])
                   // ->dehydrateStateUsing(fn ($state) => null)
                    ->hint(fn ($get) => $get('mGroupWorkError') ? $get('mGroupWorkError') : null)
                    ->hintColor('danger'),
                Forms\Components\Select::make('machine_id')
                    ->label('Work Center')
                    //->relationship('machine', 'name'),
                    ->searchable()
                    ->reactive()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        $lineId = $get('line_id');
                        $workGroupId = $get('work_group_master_id');

                        if (empty($plantId) || empty($lineId) || empty($workGroupId)) {
                            return [];
                        }

                        return Machine::where('plant_id', $plantId)
                            ->where('line_id', $lineId)
                            ->where('work_group_master_id', $workGroupId)
                            ->pluck('work_center', 'id');
                    })
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        if (!$get('plant_id') || !$get('line_id') || !$get('work_group_master_id')) {
                            $set('machine_id', null);
                        }
                    })
                    ->required(),
                Forms\Components\Select::make('characteristics_type')
                    ->label('Characteristics Type')
                    ->options([
                        'Product' => 'Product',
                        'Process'  => 'Process',
                    ])
                    ->reactive()
                    ->required(),
                Forms\Components\TextInput::make('name')
                    ->label('Name'),
                Forms\Components\Select::make('inspection_type')
                    ->label('Inspection Type')
                    ->options([
                        'Visual' => 'Visual',
                        'Value'  => 'Value',
                    ])
                    ->reactive()
                    ->required(),
                // Forms\Components\Select::make('result')
                //     ->label('Visual Type')
                //     ->reactive()
                //     ->options(function (callable $get) {
                //         if ($get('inspection_type') == 'Visual') {
                //             return [
                //                 'Ok' => 'OK',
                //                 'NotOk' => 'Not Ok',
                //             ];
                //         }
                //         return []; //empty options if type ≠ Visual
                //     })
                //     ->afterStateUpdated(function ($state, $set) {
                //         $set('result', $state); // store in form state only
                //         session()->put('temp_result', $state);
                //     })
                //     ->hidden(fn (callable $get) => $get('inspection_type') != 'Visual'),
                Forms\Components\TextInput::make('upper')
                    ->label('Upper')
                    ->numeric()
                    ->default(0.0)
                    ->visible(fn (callable $get) => $get('inspection_type') == 'Value'),
                Forms\Components\TextInput::make('lower')
                    ->label('Lower')
                    ->numeric()
                    ->default(0.0)
                    ->visible(fn (callable $get) => $get('inspection_type') == 'Value'),
                Forms\Components\TextInput::make('middle')
                    ->label('Middle')
                    ->numeric()
                    ->visible(fn (callable $get) => $get('inspection_type') == 'Value')
                    ->rule(function (callable $get) {
                        return function (string $attribute, $value, \Closure $fail) use ($get) {
                            $lower = $get('lower');
                            $upper = $get('upper');
                            $middle = $value;

                            if (!is_null($lower) && !is_null($upper) && !is_null($middle)) {
                                if (!($lower <= $middle && $middle <= $upper)) {
                                    $fail("Middle must be between Lower and Upper (Lower ≤ Middle ≤ Upper).");
                                }
                            }
                        };
                    }),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By'),
            ]);
    }

    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('item.code')
                    ->label('Item Code')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('characteristics_type')
                    ->label('Characteristics Type')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('workGroupMaster.name')
                    ->label('Group Work Center')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine.work_center')
                    ->label('Work Center')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('inspection_type')
                    ->label('Inspection Type')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('upper')
                    ->label('Upper')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('lower')
                    ->label('Lower')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('middle')
                    ->label('Middle')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->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 Product Characteristics Masters')
                    ->color('warning')
                    ->importer(ProductCharacteristicsMasterImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import product characteristics master');
                    }),
                ExportAction::make()
                    ->label('Export Product Characteristics Masters')
                    ->color('warning')
                    ->exporter(ProductCharacteristicsMasterExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export product characteristics master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProductCharacteristicsMasters::route('/'),
            'create' => Pages\CreateProductCharacteristicsMaster::route('/create'),
            'view' => Pages\ViewProductCharacteristicsMaster::route('/{record}'),
            'edit' => Pages\EditProductCharacteristicsMaster::route('/{record}/edit'),
        ];
    }

    public static function getNavigationLabel(): string
    {
        return 'Characteristics';
    }

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