<?php

namespace App\Filament\Resources;

use App\Filament\Exports\MfmParameterExporter;
use App\Filament\Imports\MfmParameterImporter;
use App\Filament\Resources\MfmParameterResource\Pages;
use App\Filament\Resources\MfmParameterResource\RelationManagers;
use App\Models\MfmParameter;
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 MfmParameterResource extends Resource
{
    protected static ?string $model = MfmParameter::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')
                    ->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();
                    })
                    ->required(),
                Forms\Components\Select::make('device_master_id')
                    ->label('Device Master')
                    ->relationship('deviceName', 'name')
                    ->required(),
                Forms\Components\Select::make('mfm_meter_id')
                    ->label('Mfm Meter')
                    ->relationship('mfmMeter', 'sequence')
                    ->required(),
                Forms\Components\TextInput::make('name')
                    ->label('Parameter Name')
                    ->required(),
                Forms\Components\TextInput::make('register_id')
                    ->label('Register ID')
                    ->required(),
                Forms\Components\TextInput::make('identifier')
                    ->label('Identifier')
                    ->required(),
                Forms\Components\TextInput::make('byte_to_convert')
                    ->label('Byte To Convert')
                    ->default(2)
                    ->required(),
                Forms\Components\TextInput::make('type_to_convert')
                    ->label('Type To Convert')
                    ->required(),
                Forms\Components\TextInput::make('decimal_to_display')
                    ->label('Decimal To Display')
                    ->default(1)
                    ->required(),
                    ])
                ->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')
                    ->label('Plant')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deviceName.name')
                    ->label('Device Name')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('mfmMeter.name')
                    ->label('Sequence')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Parameter Name')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('register_id')
                    ->label('Register ID')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('identifier')
                    ->label('Identifier')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('byte_to_convert')
                    ->label('Byte To Convert')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('type_to_convert')
                    ->label('Type To Convert')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('decimal_to_display')
                    ->label('Decimal To Display')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->alignCenter()
                    ->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 Parameters')
                    ->color('warning')
                    ->importer(MfmParameterImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import mfm parameter');
                    }),
                ExportAction::make()
                    ->label('Export MFM Parameters')
                    ->color('warning')
                    ->exporter(MfmParameterExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export mfm parameter');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListMfmParameters::route('/'),
            'create' => Pages\CreateMfmParameter::route('/create'),
            'view' => Pages\ViewMfmParameter::route('/{record}'),
            'edit' => Pages\EditMfmParameter::route('/{record}/edit'),
        ];
    }

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