<?php

namespace App\Filament\Resources;

use App\Filament\Exports\PumpTestingMasterExporter;
use App\Filament\Resources\PumpTestingMasterResource\Pages;
use App\Models\Configuration;
use App\Models\Item;
use App\Models\Plant;
use App\Models\PumpTestingMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Section;
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\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Validation\Rule;

class PumpTestingMasterResource extends Resource
{
    protected static ?string $model = PumpTestingMaster::class;

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

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

    protected static ?int $navigationSort = 1;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->label('Plant Name')
                            ->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::orderBy('code')->pluck('name', 'id')->toArray();
                            })
                            ->columnSpan(1) // (['default' => 1, 'sm' => 2])
                            ->required()
                            ->searchable()
                            ->reactive()
                            ->default(function () {
                                $userHas = Filament::auth()->user()->plant_id;

                                return ($userHas && strlen($userHas) > 0) ? $userHas : optional(PumpTestingMaster::latest()->first())->plant_id ?? null;
                            })
                            ->disabled(fn (Get $get) => ! empty($get('id')))
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    $set('pTmError', 'Please select a plant first.');

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

                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->extraAttributes(fn ($get) => [
                                'class' => $get('pTmError') ? 'border-red-500' : '',
                            ])
                            ->hint(fn ($get) => $get('pTmError') ? $get('pTmError') : null)
                            ->hintColor('danger'),
                        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('pumpTestingMasters')->pluck('code', 'id');
                                } else {
                                    $itemId = PumpTestingMaster::where('id', $get('id'))->first()?->item_id;

                                    return Item::where('plant_id', $plantId)
                                        ->where(function ($query) use ($itemId) {
                                            $query->whereDoesntHave('pumpTestingMasters')
                                                ->orWhere('id', $itemId);
                                        })
                                        ->pluck('code', 'id');
                                }
                                // return Item::where('plant_id', $plantId)->pluck('code', 'id')->toArray();
                            })
                            ->columnSpan(1)
                            ->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('pump_testing_masters', 'item_id')
                                    ->where('plant_id', $get('plant_id'))
                                    ->ignore($get('id')); // Ignore current record during updates
                            }),
                        Forms\Components\TextInput::make('head')
                            ->label('Head')
                            ->placeholder('Scan the head')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\Select::make('head_type')
                            ->label('Head Type')
                            ->selectablePlaceholder(false)
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'PUMP_HEAD_TYPE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'PUMP_HEAD_TYPE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                }
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->default('m')
                            ->reactive(),
                        Forms\Components\TextInput::make('discharge')
                            ->label('Discharge')
                            ->placeholder('Scan the discharge')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\Select::make('discharge_type')
                            ->label('Discharge Type')
                            ->selectablePlaceholder(false)
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'PUMP_DISCHARGE_TYPE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'PUMP_DISCHARGE_TYPE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                }
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->default('lps')
                            ->reactive(),
                        Forms\Components\TextInput::make('motor_efficiency')
                            ->label('Motor Efficiency')
                            ->placeholder('Scan the motor efficiency')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->reactive()
                            ->required(),
                        Forms\Components\TextInput::make('pump_efficiency')
                            ->label('Pump Efficiency')
                            ->placeholder('Scan the pump efficiency')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->reactive()
                            ->required(),
                        Forms\Components\TextInput::make('speed')
                            ->label('Speed')
                            ->placeholder('Scan the Speed')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('frequency')
                            ->label('Frequency')
                            ->placeholder('Scan the frequency')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('i_max')
                            ->label('I-Max')
                            ->placeholder('Scan the I-Max')
                            ->columnSpan(1)
                            ->required()
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->reactive(),
                        Forms\Components\TextInput::make('p_input')
                            ->label('P-Input')
                            ->placeholder('Scan the P-Input')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('delivery_size')
                            ->label('Delivery Size')
                            ->placeholder('Scan the delivery size')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('no_of_stages')
                            ->label('No of Stages')
                            ->placeholder('Scan the no of stages')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('size')
                            ->label('Size')
                            ->placeholder('Scan the size')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('maximum_head')
                            ->label('Maximum Head')
                            ->placeholder('Scan the maximum head')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('motor_type')
                            ->label('Motor Type')
                            ->placeholder('Scan the motor type')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('motor_code')
                            ->label('Motor Code')
                            ->placeholder('Scan the motor code')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('kw_hp')
                            ->label('KW / HP')
                            ->placeholder('Scan the KW / HP')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\Select::make('connection_type')
                            ->label('Connection Type')
                            ->selectablePlaceholder(false)
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'PUMP_CONNECTION')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'PUMP_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);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->default('STAR')
                            ->reactive(),
                        Forms\Components\TextInput::make('voltage')
                            ->label('Voltage')
                            ->placeholder('Scan the voltage')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\Select::make('phase')
                            ->label('Phase')
                            ->selectablePlaceholder(false)
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');

                                if ($plantId) {
                                    return Configuration::where('plant_id', $plantId)
                                        ->where('c_name', 'PUMP_PHASE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'PUMP_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', 'Three');
                                }

                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->default('Single')
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('oh_minimum')
                            ->label('OH Minimum')
                            ->placeholder('Scan the OH minimum')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('oh_maximum')
                            ->label('OH Maximum')
                            ->placeholder('Scan the OH maximum')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('current_minimum')
                            ->label('Current Minimum')
                            ->placeholder('Scan the current minimum')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('current_maximum')
                            ->label('Current Maximum')
                            ->placeholder('Scan the current maximum')
                            ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('class_of_insulation')
                            ->label('Class of Insulation')
                            ->placeholder('Scan the class of insulation')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\TextInput::make('testing_code')
                            ->label('Testing Code')
                            ->placeholder('Scan the testing code')
                            ->afterStateUpdated(function ($state, callable $set) {
                                $set('updated_by', Filament::auth()->user()?->name);
                            })
                            ->columnSpan(1)
                            ->required()
                            ->reactive(),
                        Forms\Components\Hidden::make('created_by')
                            ->default(fn () => Filament::auth()->user()?->name)
                            ->columnSpan(1)
                            ->required(),
                        Forms\Components\Hidden::make('updated_by')
                            ->default(fn () => Filament::auth()->user()?->name)
                            ->columnSpan(1)
                            ->required(),
                        Forms\Components\TextInput::make('id')
                            ->hidden()
                            ->columnSpan(1)
                            ->readOnly(),
                    ])
                    ->columns(['default' => 1, 'sm' => 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 Name')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Pump Code')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.category')
                    ->label('Pump Category')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('item.description')
                    ->label('Pump Type')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.uom')
                    ->label('Unit Of Measure')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('head')
                    ->label('Head')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('head_type')
                    ->label('Head Type')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('discharge')
                    ->label('Discharge')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('discharge_type')
                    ->label('Discharge Type')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('motor_efficiency')
                    ->label('Motor Efficiency')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('pump_efficiency')
                    ->label('Pump Efficiency')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('speed')
                    ->label('Speed')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('frequency')
                    ->label('Frequency')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('i_max')
                    ->label('I-Max')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('p_input')
                    ->label('P-Input')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('delivery_size')
                    ->label('Delivery Size')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('no_of_stages')
                    ->label('No of Stages')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('size')
                    ->label('Size')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('maximum_head')
                    ->label('Maximum Head')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('motor_type')
                    ->label('Motor Type')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('motor_code')
                    ->label('Motor Code')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('kw_hp')
                    ->label('KW / HP')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('connection_type')
                    ->label('Connection Type')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('voltage')
                    ->label('Voltage')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('phase')
                    ->label('Phase')
                    ->default('-')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('oh_minimum')
                    ->label('OH Minimum')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('oh_maximum')
                    ->label('OH Maximum')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('current_minimum')
                    ->label('Current Minimum')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('current_maximum')
                    ->label('Current Maximum')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('class_of_insulation')
                    ->label('Class of Insulation')
                    ->default('-')
                    ->searchable()
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('testing_code')
                    ->label('Testing Code')
                    ->default('-')
                    ->searchable()
                    ->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')
                    ->label('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('pumpTestingMasters', 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 Pump Code')
                            ->nullable()
                            ->options(function (callable $get) {
                                $pId = $get('Plant');

                                if (! $pId) {
                                    return [];
                                } else {
                                    return Item::whereHas('pumpTestingMasters', function ($query) use ($pId) {
                                        if ($pId) {
                                            $query->where('plant_id', $pId);
                                        }
                                    })->pluck('code', 'id');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        TextInput::make('description')
                            ->label('Pump Type')
                            ->placeholder('Enter the Pump Type'),
                        Select::make('motor_code')
                            ->label('Search by Motor Code')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plantId = $get('Plant');
                                if (! $plantId) {
                                    return [];
                                } else {
                                    return PumpTestingMaster::where('plant_id', $plantId)->whereNotNull('motor_code')->select('motor_code')->distinct()->pluck('motor_code', 'motor_code');
                                }
                            })
                            ->searchable()
                            ->reactive(),
                        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', 'PUMP_PHASE')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'PUMP_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', 'PUMP_CONNECTION')
                                        ->orderBy('created_at')
                                        ->pluck('c_value', 'c_value')
                                        ->toArray();
                                } else {
                                    return Configuration::where('c_name', 'PUMP_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 PumpTestingMaster::whereNotNull('created_by')->select('created_by')->distinct()->pluck('created_by', 'created_by');
                                } else {
                                    return PumpTestingMaster::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 PumpTestingMaster::whereNotNull('updated_by')->select('updated_by')->distinct()->pluck('updated_by', 'updated_by');
                                } else {
                                    return PumpTestingMaster::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['description']) && empty($data['motor_code']) && 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['description'])) {
                            $pId = $data['Plant'] ?? null;
                            $descIds = Item::where('description', 'like', '%'.$data['description'].'%')->whereHas('pumpTestingMasters', function ($query) use ($pId) {
                                if ($pId) {
                                    $query->where('plant_id', $pId);
                                }
                            })->pluck('id')->toArray();

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

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

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

                        if (! empty($data['connection_type'])) {
                            $query->where('connection_type', $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[] = 'Pump Code: '.$itemCode;
                        }

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

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

                        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(),
            ])
            ->headerActions([
                ExportAction::make()
                    ->label('Export Pump Testing Masters')
                    ->color('warning')
                    ->exporter(PumpTestingMasterExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export pump testing master');
                    }),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPumpTestingMasters::route('/'),
            'create' => Pages\CreatePumpTestingMaster::route('/create'),
            'view' => Pages\ViewPumpTestingMaster::route('/{record}'),
            'edit' => Pages\EditPumpTestingMaster::route('/{record}/edit'),
        ];
    }

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