<?php

namespace App\Filament\Resources;

use App\Filament\Exports\ConfigurationExporter;
use App\Filament\Imports\ConfigurationImporter;
use App\Filament\Resources\ConfigurationResource\Pages;
use App\Filament\Resources\ConfigurationResource\RelationManagers;
use App\Models\Configuration;
use App\Models\Line;
use App\Models\Plant;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Actions\ExportAction;

class ConfigurationResource extends Resource
{
    protected static ?string $model = Configuration::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
    protected static ?string $navigationGroup = 'Master Entries';
    protected static ?int $navigationSort = 10;

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->relationship('plant', 'name')
                    ->required()
                    ->reactive()
                    ->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();
                    })
                    ->default(function () {
                        return optional(Configuration::latest()->first())->plant_id;
                    })
                    ->disabled(fn (Get $get) => !empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        if (!$plantId) {
                            $set('cPlantError', 'Please select a plant first.');
                            return;
                        }
                        else
                        {
                            $set('cPlantError', null);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cPlantError') ? $get('cPlantError') : null)
                    ->hintColor('danger'),
                Forms\Components\Select::make('line_id')
                    ->label('Line')
                    ->relationship('line', 'name')
                    ->required()
                    ->reactive()
                    ->options(function (callable $get) {
                        if (!$get('plant_id')) {
                            return [];
                        }

                        return Line::where('plant_id', $get('plant_id'))
                            ->pluck('name', 'id')
                            ->toArray();
                    })
                    ->default(function () {
                        return optional(Configuration::latest()->first())->line_id;
                    })
                    ->disabled(fn (Get $get) => !empty($get('id')))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $lineId = $get('line_id');
                        if (!$lineId) {
                            $set('cLineError', 'Please select a line first.');
                            return;
                        }
                        else
                        {
                            $set('cLineError', null);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('cLineError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('cLineError') ? $get('cLineError') : null)
                    ->hintColor('danger'),
                Forms\Components\TextInput::make('c_type')
                    ->label('Type')
                    ->required(),
                Forms\Components\TextInput::make('c_group')
                    ->label('Group')
                    ->required(),
                Forms\Components\TextInput::make('c_name')
                    ->label('Name')
                    ->required(),
                Forms\Components\TextInput::make('c_value')
                    ->label('Value')
                    ->required(),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    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')
                    ->alignCenter()
                    ->label('Plant')
                    ->searchable(),
                Tables\Columns\TextColumn::make('line.name')
                    ->label('Line')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('c_type')
                    ->label('Type')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('c_group')
                    ->label('Group')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('c_name')
                    ->label('Name')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('c_value')
                    ->label('Value')
                    ->alignCenter()
                    ->searchable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->label('Updated At')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->label('Deleted At')
                    ->alignCenter()
                    ->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 Configurations')
                    ->color('warning')
                    ->importer(ConfigurationImporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view import configuration');
                    }),
                ExportAction::make()
                    ->label('Export Configurations')
                    ->color('warning')
                    ->exporter(ConfigurationExporter::class)
                    ->visible(function() {
                        return Filament::auth()->user()->can('view export configuration');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListConfigurations::route('/'),
            'create' => Pages\CreateConfiguration::route('/create'),
            'view' => Pages\ViewConfiguration::route('/{record}'),
            'edit' => Pages\EditConfiguration::route('/{record}/edit'),
        ];
    }

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