<?php

namespace App\Filament\Resources;

use App\Filament\Exports\EbReadingExporter;
use App\Filament\Imports\EbReadingImporter;
use App\Filament\Resources\EbReadingResource\Pages;
use App\Models\EbReading;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Form;
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;

class EbReadingResource extends Resource
{
    protected static ?string $model = EbReading::class;

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

    protected static ?string $navigationGroup = 'Power House';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->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();
                    })
                    ->required(),
                Forms\Components\TextInput::make('lcd_segment_check')
                    ->label('LCD Segment Check'),
                Forms\Components\TextInput::make('meter_serial_no')
                    ->label('Meter Serial No'),
                Forms\Components\DateTimePicker::make('eb_date_time')
                    ->required()
                    ->label('EB Date Time'),
                Forms\Components\TextInput::make('ph_seq_of_volt')
                    ->label('PH Sequence of Volt'),
                Forms\Components\TextInput::make('ph_assoc_conn_check')
                    ->label('PH Association Connection Check'),
                Forms\Components\TextInput::make('instantaneous_ph_volt')
                    ->label('Instantaneous PH Volt'),
                Forms\Components\TextInput::make('instantaneous_curr')
                    ->label('Instantaneous Current'),
                Forms\Components\TextInput::make('instantaneous_freq')
                    ->label('Instantaneous Frequency'),
                Forms\Components\TextInput::make('instantaneous_kw_with_sign')
                    ->label('Instantaneous KW with Sign'),
                Forms\Components\TextInput::make('instantaneous_kva')
                    ->label('Instantaneous KVA'),
                Forms\Components\TextInput::make('instantaneous_kv_ar')
                    ->label('Instantaneous KV AR'),
                Forms\Components\TextInput::make('instantaneous_pf_with_sign')
                    ->label('Instantaneous PF with Sign'),
                Forms\Components\TextInput::make('rd_with_elapsed_time_kva')
                    ->label('RD with Elapsed Time KVA'),
                Forms\Components\TextInput::make('cum_active_import_energy')
                    ->label('Cumulative Active Import Energy'),
                Forms\Components\TextInput::make('tod1_active_energy_6_9')
                    ->label('TOD1 Active Energy 6-9'),
                Forms\Components\TextInput::make('tod2_active_energy_18_21')
                    ->label('TOD2 Active Energy 18-21'),
                Forms\Components\TextInput::make('tod3_active_energy_21_22')
                    ->label('TOD3 Active Energy 21-22'),
                Forms\Components\TextInput::make('tod4_active_energy_5_6_9_18')
                    ->label('TOD4 Active Energy 5-6-9-18'),
                Forms\Components\TextInput::make('tod5_active_energy_22_5')
                    ->label('TOD5 Active Energy 22-5'),
                Forms\Components\TextInput::make('cum_reac_lag_energy')
                    ->label('Cumulative Reactive Lag Energy'),
                Forms\Components\TextInput::make('cum_reac_lead_energy')
                    ->label('Cumulative Reactive Lead Energy'),
                Forms\Components\TextInput::make('cum_appar_energy')
                    ->label('Cumulative Apparent Energy'),
                Forms\Components\TextInput::make('tod1_appar_energy_6_9')
                    ->label('TOD1 Apparent Energy 6-9'),
                Forms\Components\TextInput::make('tod2_appar_energy_18_21')
                    ->label('TOD2 Apparent Energy 18-21'),
                Forms\Components\TextInput::make('tod3_appar_energy_21_22')
                    ->label('TOD3 Apparent Energy 21-22'),
                Forms\Components\TextInput::make('tod4_appar_energy_5_6_9_18')
                    ->label('TOD4 Apparent Energy 5-6-9-18'),
                Forms\Components\TextInput::make('tod5_appar_energy_22_5')
                    ->label('TOD5 Apparent Energy 22-5'),
                Forms\Components\TextInput::make('avg_pow_factor')
                    ->label('Average Power Factor'),
                Forms\Components\TextInput::make('avg_freq_15min_last_ip')
                    ->label('Average Frequency 15min Last IP'),
                Forms\Components\TextInput::make('net_kv_arh_high')
                    ->label('Net KV ARH High'),
                Forms\Components\TextInput::make('net_kv_arh_low')
                    ->label('Net KV ARH Low'),
                Forms\Components\TextInput::make('cum_md_kva')
                    ->label('Cumulative MD KVA'),
                Forms\Components\TextInput::make('present_md_kva')
                    ->label('Present MD KVA'),
                Forms\Components\DateTimePicker::make('present_md_kva_date_time')
                    ->label('Present MD KVA Date Time')
                    ->required(),
                Forms\Components\TextInput::make('tod1_md_kva_6_9')
                    ->label('TOD1 MD KVA 6-9'),
                Forms\Components\TextInput::make('tod2_md_kva_18_21')
                    ->label('TOD2 MD KVA 18-21'),
                Forms\Components\TextInput::make('tod3_md_kva_21_22')
                    ->label('TOD3 MD KVA 21-22'),
                Forms\Components\TextInput::make('tod4_md_kva_5_6_9_18')
                    ->label('TOD4 MD KVA 5-6-9-18'),
                Forms\Components\TextInput::make('tod5_md_kva_22_5')
                    ->label('TOD5 MD KVA 22-5'),
                Forms\Components\TextInput::make('total_pow_off_hours')
                    ->label('Total Power Off Hours'),
                Forms\Components\TextInput::make('programming_count')
                    ->label('Programming Count'),
                Forms\Components\TextInput::make('last_occ_res_event_type')
                    ->label('Last Occurrence/Reset Event Type'),
                Forms\Components\DateTimePicker::make('last_occ_res_event_date_time')
                    ->label('Last Occurrence/Reset Event Date Time')
                    ->required(),
                Forms\Components\TextInput::make('tamper_count')
                    ->label('Tamper Count'),
                Forms\Components\TextInput::make('reset_count')
                    ->label('Reset Count'),
                Forms\Components\DateTimePicker::make('last_md_reset_date_time')
                    ->label('Last MD Reset Date Time')
                    ->required(),
                Forms\Components\Hidden::make('electrician_sign')
                    ->default(Filament::auth()->user()?->name),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->alignCenter()
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;

                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('lcd_segment_check')
                    ->alignCenter()
                    ->label('LCD Segment Check'),
                Tables\Columns\TextColumn::make('meter_serial_no')
                    ->alignCenter()
                    ->label('Meter Serial No'),
                Tables\Columns\TextColumn::make('eb_date_time')
                    ->alignCenter()
                    ->label('EB Date Time'),
                Tables\Columns\TextColumn::make('ph_seq_of_volt')
                    ->alignCenter()
                    ->label('PH Sequence of Volt'),
                Tables\Columns\TextColumn::make('ph_assoc_conn_check')
                    ->alignCenter()
                    ->label('PH Association Connection Check'),
                Tables\Columns\TextColumn::make('instantaneous_ph_volt')
                    ->alignCenter()
                    ->label('Instantaneous PH Volt'),
                Tables\Columns\TextColumn::make('instantaneous_curr')
                    ->alignCenter()
                    ->label('Instantaneous Current'),
                Tables\Columns\TextColumn::make('instantaneous_freq')
                    ->alignCenter()
                    ->label('Instantaneous Frequency'),
                Tables\Columns\TextColumn::make('instantaneous_kw_with_sign')
                    ->alignCenter()
                    ->label('Instantaneous KW with Sign'),
                Tables\Columns\TextColumn::make('instantaneous_kva')
                    ->alignCenter()
                    ->label('Instantaneous KVA'),
                Tables\Columns\TextColumn::make('instantaneous_kv_ar')
                    ->alignCenter()
                    ->label('Instantaneous KV AR'),
                Tables\Columns\TextColumn::make('instantaneous_pf_with_sign')
                    ->alignCenter()
                    ->label('Instantaneous PF with Sign'),
                Tables\Columns\TextColumn::make('rd_with_elapsed_time_kva')
                    ->alignCenter()
                    ->label('RD with Elapsed Time KVA'),
                Tables\Columns\TextColumn::make('cum_active_import_energy')
                    ->alignCenter()
                    ->label('Cumulative Active Import Energy'),
                Tables\Columns\TextColumn::make('tod1_active_energy_6_9')
                    ->alignCenter()
                    ->label('TOD1 Active Energy 6-9'),
                Tables\Columns\TextColumn::make('tod2_active_energy_18_21')
                    ->alignCenter()
                    ->label('TOD2 Active Energy 18-21'),
                Tables\Columns\TextColumn::make('tod3_active_energy_21_22')
                    ->alignCenter()
                    ->label('TOD3 Active Energy 21-22'),
                Tables\Columns\TextColumn::make('tod4_active_energy_5_6_9_18')
                    ->alignCenter()
                    ->label('TOD4 Active Energy 5-6-9-18'),
                Tables\Columns\TextColumn::make('tod5_active_energy_22_5')
                    ->alignCenter()
                    ->label('TOD5 Active Energy 22-5'),
                Tables\Columns\TextColumn::make('cum_reac_lag_energy')
                    ->alignCenter()
                    ->label('Cumulative Reactive Lag Energy'),
                Tables\Columns\TextColumn::make('cum_reac_lead_energy')
                    ->alignCenter()
                    ->label('Cumulative Reactive Lead Energy'),
                Tables\Columns\TextColumn::make('cum_appar_energy')
                    ->alignCenter()
                    ->label('Cumulative Apparent Energy'),
                Tables\Columns\TextColumn::make('tod1_appar_energy_6_9')
                    ->alignCenter()
                    ->label('TOD1 Apparent Energy 6-9'),
                Tables\Columns\TextColumn::make('tod2_appar_energy_18_21')
                    ->alignCenter()
                    ->label('TOD2 Apparent Energy 18-21'),
                Tables\Columns\TextColumn::make('tod3_appar_energy_21_22')
                    ->alignCenter()
                    ->label('TOD3 Apparent Energy 21-22'),
                Tables\Columns\TextColumn::make('tod4_appar_energy_5_6_9_18')
                    ->alignCenter()
                    ->label('TOD4 Apparent Energy 5-6-9-18'),
                Tables\Columns\TextColumn::make('tod5_appar_energy_22_5')
                    ->alignCenter()
                    ->label('TOD5 Apparent Energy 22-5'),
                Tables\Columns\TextColumn::make('avg_pow_factor')
                    ->alignCenter()
                    ->label('Average Power Factor'),
                Tables\Columns\TextColumn::make('avg_freq_15min_last_ip')
                    ->alignCenter()
                    ->label('Average Frequency 15min Last IP'),
                Tables\Columns\TextColumn::make('net_kv_arh_high')
                    ->alignCenter()
                    ->label('Net KV ARH High'),
                Tables\Columns\TextColumn::make('net_kv_arh_low')
                    ->alignCenter()
                    ->label('Net KV ARH Low'),
                Tables\Columns\TextColumn::make('cum_md_kva')
                    ->alignCenter()
                    ->label('Cumulative MD KVA'),
                Tables\Columns\TextColumn::make('present_md_kva')
                    ->alignCenter()
                    ->label('Present MD KVA'),
                Tables\Columns\TextColumn::make('present_md_kva_date_time')
                    ->alignCenter()
                    ->label('Present MD KVA Date Time'),
                Tables\Columns\TextColumn::make('tod1_md_kva_6_9')
                    ->alignCenter()
                    ->label('TOD1 MD KVA 6-9'),
                Tables\Columns\TextColumn::make('tod2_md_kva_18_21')
                    ->alignCenter()
                    ->label('TOD2 MD KVA 18-21'),
                Tables\Columns\TextColumn::make('tod3_md_kva_21_22')
                    ->alignCenter()
                    ->label('TOD3 MD KVA 21-22'),
                Tables\Columns\TextColumn::make('tod4_md_kva_5_6_9_18')
                    ->alignCenter()
                    ->label('TOD4 MD KVA 5-6-9-18'),
                Tables\Columns\TextColumn::make('tod5_md_kva_22_5')
                    ->alignCenter()
                    ->label('TOD5 MD KVA 22-5'),
                Tables\Columns\TextColumn::make('total_pow_off_hours')
                    ->alignCenter()
                    ->label('Total Power Off Hours'),
                Tables\Columns\TextColumn::make('programming_count')
                    ->alignCenter()
                    ->label('Programming Count'),
                Tables\Columns\TextColumn::make('last_occ_res_event_type')
                    ->alignCenter()
                    ->label('Last Occurrence/Reset Event Type'),
                Tables\Columns\TextColumn::make('last_occ_res_event_date_time')
                    ->alignCenter()
                    ->label('Last Occurrence/Reset Event Date Time'),
                Tables\Columns\TextColumn::make('tamper_count')
                    ->alignCenter()
                    ->label('Tamper Count'),
                Tables\Columns\TextColumn::make('reset_count')
                    ->alignCenter()
                    ->label('Reset Count'),
                Tables\Columns\TextColumn::make('last_md_reset_date_time')
                    ->alignCenter()
                    ->label('Last MD Reset Date Time'),
                Tables\Columns\TextColumn::make('electrician_sign')
                    ->alignCenter()
                    ->label('Created By'),
                Tables\Columns\TextColumn::make('created_at')
                    ->alignCenter()
                    ->label('Created At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            // ->filters([
            //     Tables\Filters\TrashedFilter::make(),
            // ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
                Filter::make('advanced_filters')
                    ->label('Advanced Filters')
                    ->form([
                        Select::make('Plant')
                            ->label('Select Plant')
                            ->nullable()
                            // ->options(function () {
                            //     return Plant::pluck('name', 'id');
                            // })
                            ->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();
                            })
                            ->reactive()
                            ->afterStateUpdated(function ($state, callable $set, callable $get) {
                                $set('electrician_sign', null);
                            }),
                        TextInput::make('electrician_sign')
                            ->label('Created By'),
                        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),
                    ])
                    ->query(function ($query, array $data) {
                        // Hide all records initially if no filters are applied
                        if (empty($data['Plant']) && empty($data['electrician_sign'])) {
                            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['created_from'])) {
                            $query->where('created_at', '>=', $data['created_from']);
                        }

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

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

                    })
                    ->indicateUsing(function (array $data) {
                        $indicators = [];

                        if (! empty($data['Plant'])) {
                            $indicators[] = 'Plant: '.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['electrician_sign'])) {
                            $indicators[] = 'Created By: '.$data['electrician_sign'];
                        }

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

                        if (! empty($data['created_to'])) {
                            $indicators[] = 'To: '.$data['created_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 EB Readings')
                    ->color('warning')
                    ->importer(EbReadingImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import eb reading');
                    }),
                ExportAction::make()
                    ->label('Export EB Readings')
                    ->color('warning')
                    ->exporter(EbReadingExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export eb reading');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListEbReadings::route('/'),
            'create' => Pages\CreateEbReading::route('/create'),
            'view' => Pages\ViewEbReading::route('/{record}'),
            'edit' => Pages\EditEbReading::route('/{record}/edit'),
        ];
    }

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