<?php

namespace App\Filament\Resources;

use App\Filament\Exports\MotorTestingMasterExporter;
use App\Filament\Imports\MotorTestingMasterImporter;
use App\Filament\Resources\MotorTestingMasterResource\Pages;
use App\Models\Configuration;
use App\Models\Item;
use App\Models\MotorTestingMaster;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rule;

class MotorTestingMasterResource extends Resource
{
    protected static ?string $model = MotorTestingMaster::class;

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

    protected static ?string $navigationGroup = 'Testing Panel';

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant Name')
                    ->relationship('plant', 'name')
                    ->required()
                    ->searchable()
                    ->reactive()
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;

                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                    })
                    ->default(function () {
                        return optional(MotorTestingMaster::latest()->first())->plant_id;
                    })
                    ->disabled(fn (Get $get) => ! empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            $set('mTmError', 'Please select a plant first.');

                            return;
                        } else {
                            $set('mTmError', null);
                        }

                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('mTmError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('mTmError') ? $get('mTmError') : null)
                    ->hintColor('danger'),
                Forms\Components\TimePicker::make('routine_test_time')
                    ->label('Routine Test Time')
                    ->default('00:40:00')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->reactive(),
                Forms\Components\Select::make('item_id')
                    ->label('Item Code')
                    // ->relationship('item', 'name')
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            return [];
                        }

                        if (! $get('id')) {
                            // whereHas
                            return Item::where('plant_id', $plantId)->whereDoesntHave('motorTestingMasters')->pluck('code', 'id');
                        } else {
                            $itemId = MotorTestingMaster::where('id', $get('id'))->first()?->item_id;

                            return Item::where('plant_id', $plantId)
                                ->where(function ($query) use ($itemId) {
                                    $query->whereDoesntHave('motorTestingMasters')
                                        ->orWhere('id', $itemId);
                                })
                                ->pluck('code', 'id');
                        }
                        // return Item::where('plant_id', $plantId)->pluck('code', 'id')->toArray();
                    })
                    ->required()
                    ->searchable()
                    ->reactive()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->rule(function (callable $get) {
                        return Rule::unique('motor_testing_masters', 'item_id')
                            ->where('plant_id', $get('plant_id'))
                            ->ignore($get('id')); // Ignore current record during updates
                    }),
                Forms\Components\TextInput::make('subassembly_code')
                    ->label('Subassembly Code')
                    // ->required()
                    ->placeholder('Scan the subassembly code')
                    ->reactive()
                    ->alphaNum()
                    ->minLength(6)
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $code = $get('subassembly_code');
                        if (! $code) {
                            $set('iCodeError', 'Scan the valid Subassembly Code.');

                            return;
                        } else {
                            if (strlen($code) < 6) {
                                $set('iCodeError', 'Subassembly code must be at least 6 digits.');

                                return;
                            } elseif (! preg_match('/^[a-zA-Z0-9]{6,}$/', $code)) {
                                $set('code', null);
                                $set('iCodeError', 'Subassembly code must contain only alpha-numeric characters.');

                                return;
                            }
                            $set('iCodeError', null);
                        }

                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('iCodeError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('iCodeError') ? $get('iCodeError') : null)
                    ->hintColor('danger'),

                Forms\Components\Select::make('isi_model')
                    ->label('ISI Model')
                    ->options([
                        1 => 'Yes',
                        0 => 'No',
                    ])
                    ->selectablePlaceholder(false)
                    ->default(1)
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->reactive(),
                Forms\Components\Select::make('phase')
                    ->label('Phase')
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');

                        if ($plantId) {
                            return Configuration::where('plant_id', $plantId)
                                ->where('c_name', 'MOTOR_PHASE')
                                ->orderBy('created_at')
                                ->pluck('c_value', 'c_value')
                                ->toArray();
                        } else {
                            return Configuration::where('c_name', 'MOTOR_PHASE')
                                ->orderBy('created_at')
                                ->pluck('c_value', 'c_value')
                                ->toArray();
                        }
                    })
                    ->selectablePlaceholder(false)
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        if ($state == 'Single' && $get('connection') == 'Star-Delta') {
                            $set('phase', 'Three');
                        }

                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->default('Single')
                    ->required()
                    ->reactive(),
                Forms\Components\TextInput::make('hp')
                    ->label('HP')
                    ->placeholder('Scan the HP')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('kw')
                    ->label('KW')
                    ->placeholder('Scan the KW')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('volt')
                    ->label('Volt')
                    ->placeholder('Scan the volt')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('current')
                    ->label('Current')
                    ->placeholder('Scan the current')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('rpm')
                    ->label('RPM')
                    ->placeholder('Scan the RPM')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('torque')
                    ->label('Torque')
                    ->placeholder('Scan the torque')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('frequency')
                    ->label('Frequency')
                    ->placeholder('Scan the frequency')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Select::make('connection')
                    ->label('Connection')
                    ->selectablePlaceholder(false)
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if ($plantId) {
                            return Configuration::where('plant_id', $plantId)
                                ->where('c_name', 'MOTOR_CONNECTION')
                                ->orderBy('created_at')
                                ->pluck('c_value', 'c_value')
                                ->toArray();
                        } else {
                            return Configuration::where('c_name', 'MOTOR_CONNECTION')
                                ->orderBy('created_at')
                                ->pluck('c_value', 'c_value')
                                ->toArray();
                        }
                    })
                    ->afterStateUpdated(function ($state, callable $set) {
                        if ($state == 'Star-Delta') {
                            $set('phase', 'Three');
                        }

                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->required()
                    ->default('Star')
                    ->reactive(),
                Forms\Components\TextInput::make('ins_res_limit')
                    ->label('Insulation Resistance Limit')
                    ->placeholder('Scan the insulation resistance limit')
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->required(),
                Forms\Components\Select::make('ins_res_type')
                    ->label('Insulation Resistance Type')
                    ->placeholder('Scan the insulation resistance type')
                    ->default('O')
                    ->selectablePlaceholder(false)
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if ($plantId) {
                            return Configuration::where('plant_id', $plantId)
                                ->where('c_name', 'INSULATION_RESISTANCE_TYPE')
                                ->orderBy('created_at')
                                ->pluck('c_value', 'c_value')
                                ->toArray();
                        } else {
                            return Configuration::where('c_name', 'INSULATION_RESISTANCE_TYPE')
                                ->orderBy('created_at')
                                ->pluck('c_value', 'c_value')
                                ->toArray();
                        }
                    })
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('res_ry_ll')
                    ->label('Resistance RY LL')
                    ->placeholder('Scan the resistance RY LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('res_ry_ul')
                    ->label('Resistance RY UL')
                    ->placeholder('Scan the resistance RY UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('res_yb_ll')
                    ->label('Resistance YB LL')
                    ->placeholder('Scan the resistance YB LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('res_yb_ul')
                    ->label('Resistance YB UL')
                    ->placeholder('Scan the resistance YB UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('res_br_ll')
                    ->label('Resistance BR LL')
                    ->placeholder('Scan the resistance BR LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('res_br_ul')
                    ->label('Resistance BR UL')
                    ->placeholder('Scan the resistance BR UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('lock_volt_limit')
                    ->label('Lock Volt Limit')
                    ->placeholder('Scan the lock volt limit')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('leak_cur_limit')
                    ->label('Leakage Current Limit')
                    ->placeholder('Scan the leakage current limit')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('lock_cur_ll')
                    ->label('Lock Current LL')
                    ->placeholder('Scan the lock current LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('lock_cur_ul')
                    ->label('Lock Current UL')
                    ->placeholder('Scan the lock current UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('noload_cur_ll')
                    ->label('No Load Current LL')
                    ->placeholder('Scan the no load current LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('noload_cur_ul')
                    ->label('No Load Current UL')
                    ->placeholder('Scan the no load current UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('noload_pow_ll')
                    ->label('No Load Power LL')
                    ->placeholder('Scan the no load power LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('noload_pow_ul')
                    ->label('No Load Power UL')
                    ->placeholder('Scan the no load power UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('noload_spd_ll')
                    ->label('No Load Speed LL')
                    ->placeholder('Scan the no load speed LL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\TextInput::make('noload_spd_ul')
                    ->label('No Load Speed UL')
                    ->placeholder('Scan the no load speed UL')
                    ->required()
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Hidden::make('created_by')
                    ->default(fn () => Filament::auth()->user()?->name)
                    ->required(),
                Forms\Components\Hidden::make('updated_by')
                    ->default(fn () => Filament::auth()->user()?->name)
                    ->required(),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    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 Name')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.category')
                    ->label('Category')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item Code')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('subassembly_code')
                    ->label('Subassembly Code')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.description')
                    ->label('Model')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\IconColumn::make('isi_model')
                    ->label('ISI Model')
                    ->searchable()
                    ->alignCenter()
                    ->boolean(),
                Tables\Columns\TextColumn::make('phase')
                    ->label('Phase')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('kw')
                    ->label('KW')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('hp')
                    ->label('HP')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('volt')
                    ->label('Volt')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('current')
                    ->label('Current')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('rpm')
                    ->label('Rpm')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('torque')
                    ->label('Torque')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('frequency')
                    ->label('Frequency')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('connection')
                    ->label('Connection')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('ins_res_limit')
                    ->label('Insulation Resistance Limit')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('ins_res_type')
                    ->label('Insulation Resistance Type')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('routine_test_time')
                    ->label('Routine Test Time')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('res_ry_ll')
                    ->label('Resistance RY LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('res_ry_ul')
                    ->label('Resistance RY UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('res_yb_ll')
                    ->label('Resistance YB LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('res_yb_ul')
                    ->label('Resistance YB UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('res_br_ll')
                    ->label('Resistance BR LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('res_br_ul')
                    ->label('Resistance BR UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('lock_volt_limit')
                    ->label('Lock Volt Limit')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('leak_cur_limit')
                    ->label('Leakage Current Limit')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('lock_cur_ll')
                    ->label('Lock Current LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('lock_cur_ul')
                    ->label('Lock Current UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('noload_cur_ll')
                    ->label('No Load Current LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('noload_cur_ul')
                    ->label('No Load Current UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('noload_pow_ll')
                    ->label('No Load Power LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('noload_pow_ul')
                    ->label('No Load Power UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('noload_spd_ll')
                    ->label('No Load Speed LL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('noload_spd_ul')
                    ->label('No Load Speed UL')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Search by Plant Name')
                            ->nullable()
                            ->searchable()
                            ->reactive()
                            // ->options(function () {
                            //     return Plant::pluck('name', 'id');
                            // })
                            ->options(function (callable $get) {
                                $userHas = Filament::auth()->user()->plant_id;

                                if ($userHas && strlen($userHas) > 0) {
                                    return Plant::where('id', $userHas)->pluck('name', 'id')->toArray();
                                } else {
                                    return Plant::whereHas('motorTestingMasters', function ($query) {
                                        $query->whereNotNull('id');
                                    })->orderBy('code')->pluck('name', 'id');
                                }

                                // return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('Item', null);
                                $set('isi_type', null);
                                $set('created_by', null);
                                $set('updated_by', null);
                            }),
                        Select::make('Item')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->options(function (callable $get) {
                                $pId = $get('Plant');

                                if (! $pId) {
                                    return [];
                                } else {
                                    return Item::whereHas('motorTestingMasters', function ($query) use ($pId) {
                                        if ($pId) {
                                            $query->where('plant_id', $pId);
                                        }
                                    })->pluck('code', 'id');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        Select::make('subassembly_code')
                            ->label('Search by Subassembly Code')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return [];
                                } else {
                                    return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('subassembly_code')->select('subassembly_code')->distinct()->pluck('subassembly_code', 'subassembly_code');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        TextInput::make('description')
                            ->label('Model')
                            ->placeholder('Enter Model'),
                        Radio::make('isi_type')
                            ->label('ISI Model ?')
                            ->boolean()
                            ->options([
                                'All' => 'All',
                                'Y' => 'Y',
                                'N' => 'N',
                            ])
                            ->default(null)
                            ->inlineLabel(false)
                            ->inline(),
                        Select::make('phase_type')
                            ->label('Select Phase')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');

                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'MOTOR_PHASE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'MOTOR_PHASE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                }
                            })
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {

                                if ($state == 'Single' && $get('connection_type') == 'Star-Delta') {
                                    $set('phase_type', 'Three');
                                }
                            })
                            ->reactive(),
                        Select::make('connection_type')
                            ->label('Select Connection')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'MOTOR_CONNECTION')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'MOTOR_CONNECTION')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                }
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                if ($state == 'Star-Delta') {
                                    $set('phase_type', 'Three');
                                }
                            })
                            ->reactive(),
                        Select::make('created_by')
                            ->label('Created By')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return MotorTestingMaster::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                                } else {
                                    return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        DateTimePicker::make(name: 'created_from')
                            ->label('Created From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('created_to')
                            ->label('Created To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                        Select::make('updated_by')
                            ->label('Updated By')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return MotorTestingMaster::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                } else {
                                    return MotorTestingMaster::where('plant_id', $plantId)->whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        DateTimePicker::make(name: 'updated_from')
                            ->label('Updated From')
                            ->placeholder(placeholder: 'Select From DateTime')
                            ->reactive()
                            ->native(false),
                        DateTimePicker::make('updated_to')
                            ->label('Updated To')
                            ->placeholder(placeholder: 'Select To DateTime')
                            ->reactive()
                            ->native(false),
                    ])
                    ->query(function ($query, array $data) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['Item']) && empty($data['subassembly_code']) && empty($data['description']) && empty($data['isi_type']) && empty($data['phase_type']) && empty($data['connection_type']) && empty($data['created_by']) && empty($data['created_from']) && empty($data['created_to']) && empty($data['updated_by']) && empty($data['updated_from']) && empty($data['updated_to'])) {// || $data['isi_type'] == 'All')
                            return $query->whereRaw('1 = 0');
                        }

                        if (! empty($data['Plant'])) {
                            $query->where('plant_id', $data['Plant']);
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

                            if ($userHas && strlen($userHas) > 0) {
                                return $query->whereRaw('1 = 0');
                            }
                        }

                        if (! empty($data['Item'])) {
                            $itemIds = Item::where('id', $data['Item'])
                                ->pluck('id')
                                ->toArray();

                            if (! empty($itemIds)) {
                                $query->whereIn('item_id', $itemIds);
                            }
                        }

                        if (! empty($data['subassembly_code'])) {
                            $query->where('subassembly_code', $data['subassembly_code']);
                        }

                        if (! empty($data['description'])) {
                            $pId = $data['Plant'] ?? null;
                            $descIds = Item::where('description', 'like', '%'.$data['description'].'%')->whereHas('motorTestingMasters', function ($query) use ($pId) {
                                if ($pId) {
                                    $query->where('plant_id', $pId);
                                }
                            })->pluck('id')->toArray();

                            if (! empty($descIds)) {
                                $query->whereIn('item_id', $descIds);
                            }
                        }

                        if ($data['isi_type'] == 'Y') {
                            $query->where('isi_model', true);
                        } elseif ($data['isi_type'] == 'N') {
                            $query->where('isi_model', false);
                        }

                        if (! empty($data['phase_type'])) {
                            $query->where('phase', $data['phase_type']);
                        }

                        if (! empty($data['connection_type'])) {
                            $query->where('connection', $data['connection_type']);
                        }

                        if (! empty($data['created_by'])) {
                            $query->where('created_by', $data['created_by']);
                        }

                        if (! empty($data['created_from'])) {
                            $query->where('created_at', '>=', $data['created_from']);
                        }

                        if (! empty($data['created_to'])) {
                            $query->where('created_at', '<=', $data['created_to']);
                        }

                        if (! empty($data['updated_by'])) {
                            $query->where('updated_by', $data['updated_by']);
                        }

                        if (! empty($data['updated_from'])) {
                            $query->where('updated_at', '>=', $data['updated_from']);
                        }

                        if (! empty($data['updated_to'])) {
                            $query->where('updated_at', '<=', $data['updated_to']);
                        }
                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['Plant'])) {
                            $indicators[] = 'Plant Name: '.Plant::where('id', $data['Plant'])->value('name');
                        } else {
                            $userHas = Filament::auth()->user()->plant_id;

                            if ($userHas && strlen($userHas) > 0) {
                                return 'Plant: Choose plant to filter records.';
                            }
                        }

                        if (! empty($data['Item'])) {
                            $itemCode = Item::find($data['Item'])->code ?? 'Unknown';
                            $indicators[] = 'Item Codes: '.$itemCode;
                        }

                        if (! empty($data['subassembly_code'])) {
                            $indicators[] = 'Subassembly Code: '.$data['subassembly_code'];
                        }

                        if (! empty($data['description'])) {
                            $indicators[] = 'Model: '.$data['description'];
                        }

                        if ($data['isi_type'] == 'Y') {
                            $indicators[] = 'ISI Model: Yes';
                        } elseif ($data['isi_type'] == 'N') {
                            $indicators[] = 'ISI Model: No';
                        }

                        if (! empty($data['phase_type'])) {
                            $indicators[] = 'Phase: '.$data['phase_type'];
                        }

                        if (! empty($data['connection_type'])) {
                            $indicators[] = 'Connection: '.$data['connection_type'];
                        }

                        if (! empty($data['created_by'])) {
                            $indicators[] = 'Created By: '.$data['created_by'];
                        }

                        if (! empty($data['created_from'])) {
                            $indicators[] = 'Created From: '.$data['created_from'];
                        }

                        if (! empty($data['created_to'])) {
                            $indicators[] = 'Created To: '.$data['created_to'];
                        }

                        if (! empty($data['updated_by'])) {
                            $indicators[] = 'Updated By: '.$data['updated_by'];
                        }

                        if (! empty($data['updated_from'])) {
                            $indicators[] = 'Updated From: '.$data['updated_from'];
                        }

                        if (! empty($data['updated_to'])) {
                            $indicators[] = 'Updated To: '.$data['updated_to'];
                        }

                        return $indicators;
                    }),
            ])
            ->filtersFormMaxHeight('280px')
            ->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 Motor Testing Masters')
                    ->color('warning')
                    ->importer(MotorTestingMasterImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import motor testing master');
                    }),
                ExportAction::make()
                    ->label('Export Motor Testing Masters')
                    ->color('warning')
                    ->exporter(MotorTestingMasterExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export motor testing master');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListMotorTestingMasters::route('/'),
            'create' => Pages\CreateMotorTestingMaster::route('/create'),
            'view' => Pages\ViewMotorTestingMaster::route('/{record}'),
            'edit' => Pages\EditMotorTestingMaster::route('/{record}/edit'),
        ];
    }

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