<?php

namespace App\Filament\Resources;

use App\Filament\Exports\TempLiveReadingExporter;
use App\Filament\Imports\TempLiveReadingImporter;
use App\Filament\Resources\TempLiveReadingResource\Pages;
use App\Models\MfmMeter;
use App\Models\Plant;
use App\Models\TempLiveReading;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Section;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class TempLiveReadingResource extends Resource
{
    protected static ?string $model = TempLiveReading::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([
                Section::make('')
                    ->schema([
                        Forms\Components\Select::make('plant_id')
                            ->label('Plant')
                            ->relationship('plant', 'name')
                            ->reactive()
                            ->required()
                            ->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();
                            }),
                        Forms\Components\Select::make('mfm_meter_id')
                            ->label('MFM Meter ID')
                            ->required()
                            ->reactive()
                            ->options(function (callable $get) {
                                $plantId = $get('plant_id');
                                if (! $plantId) {
                                    return [];
                                }

                                return MfmMeter::where('plant_id', $plantId)
                                    ->pluck('sequence', 'id')
                                    ->toArray();
                            }),
                        Forms\Components\TextInput::make('register_data')
                            ->label('Register Data')
                            ->required(),
                        Forms\Components\Hidden::make('created_by')
                            ->default(Filament::auth()->user()?->name),
                    ])
                    ->columns(3),
            ]);
    }

    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')
                    ->numeric()
                    ->sortable(),
                // Tables\Columns\TextColumn::make('mfm_meter_id.sequence')
                //     ->label('Sequence')
                //     ->sortable(),
                Tables\Columns\TextColumn::make('mfmMeter.name')
                    ->label('Name')
                    ->sortable(),
                Tables\Columns\TextColumn::make('register_data')
                    ->label('Register Data')
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\TrashedFilter::make(),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                    Tables\Actions\ForceDeleteBulkAction::make(),
                    Tables\Actions\RestoreBulkAction::make(),
                ]),
            ]);
        // ->headerActions([
        //     ImportAction::make()
        //         ->importer(TempLiveReadingImporter::class)
        //         ->visible(function() {
        //             return Filament::auth()->user()->can('view import temp live reading');
        //         }),
        //     ExportAction::make()
        //         ->exporter(TempLiveReadingExporter::class)
        //         ->visible(function() {
        //             return Filament::auth()->user()->can('view export temp live reading');
        //         }),
        // ]);
    }

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

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

    public static function getHeading(): string
    {
        return 'Live Readings';
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTempLiveReadings::route('/'),
            'create' => Pages\CreateTempLiveReading::route('/create'),
            'view' => Pages\ViewTempLiveReading::route('/{record}'),
            'edit' => Pages\EditTempLiveReading::route('/{record}/edit'),
        ];
    }

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