<?php

namespace App\Filament\Resources;

use App\Filament\Exports\MfmMeterExporter;
use App\Filament\Imports\MfmMeterImporter;
use App\Filament\Resources\MfmMeterResource\Pages;
use App\Filament\Resources\MfmMeterResource\RelationManagers;
use App\Models\DeviceMaster;
use App\Models\MfmMeter;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Forms\Components\Section;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;

class MfmMeterResource extends Resource
{
    protected static ?string $model = MfmMeter::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')
                        ->relationship('plant', 'name')
                        ->label('Plant')
                        ->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::pluck('name', 'id')->toArray();
                        }),
                    Forms\Components\Select::make('device_master_id')
                        //->relationship('device', 'name')
                        ->options(function ($get) {
                            $plantId = $get('plant_id');
                            if (!$plantId) {
                                return [];
                            }
                            return DeviceMaster::where('plant_id', $plantId)->pluck('name', 'id');
                        })
                        ->label('Device Name')
                        ->required(),
                    Forms\Components\TextInput::make('sequence')
                        ->required(),
                    Forms\Components\TextInput::make('name')
                        ->required(),
                    Forms\Components\Hidden::make('created_by')
                    ->default(Filament::auth()->user()?->name),
                ])
                ->columns(4),

            ]);
    }

    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')
                    ->sortable(),
                Tables\Columns\TextColumn::make('devicemaster.name')
                    ->label('Device Name')
                    ->sortable(),
                Tables\Columns\TextColumn::make('sequence')
                    ->label('Sequence')
                    ->sortable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Meter Name')
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('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()
                    ->label('Import MFM Meters')
                    ->color('warning')
                    ->importer(MfmMeterImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import mfm meter');
                    }),
                ExportAction::make()
                    ->label('Export MFM Meters')
                    ->color('warning')
                    ->exporter(MfmMeterExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export mfm meter');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListMfmMeters::route('/'),
            'create' => Pages\CreateMfmMeter::route('/create'),
            'view' => Pages\ViewMfmMeter::route('/{record}'),
            'edit' => Pages\EditMfmMeter::route('/{record}/edit'),
        ];
    }

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