<?php

namespace App\Filament\Resources;

use App\Filament\Exports\UserExporter;
use App\Filament\Imports\UserImporter;
use App\Filament\Resources\UserResource\Pages;
use App\Models\Plant;
use App\Models\User;
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\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Support\Facades\Hash;

class UserResource extends Resource
{
    protected static ?string $model = User::class;

    protected static ?string $navigationIcon = 'heroicon-c-user-group';

    protected static ?string $navigationGroup = 'User Management';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant Name')
                    ->relationship('plant', 'name')
                    ->nullable()
                    ->searchable()
                    ->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::orderBy('code')->pluck('name', 'id')->toArray();
                    })
                    ->default(function () {
                        return optional(User::latest()->first())->plant_id;
                    }),
                Forms\Components\TextInput::make('name')
                    ->label('Name')
                    ->required()
                    ->autofocus()
                    ->minLength(3)
                    // ->reactive()
                    ->live(debounce: 600)
                    ->disabled(fn (Get $get) => ! empty($get('id')) && Filament::auth()->user()?->name != 'Admin' && Filament::auth()->user()?->name != 'Dhanabalan S' && Filament::auth()->user()?->name != 'Ranjith B' && ($get('name') == 'Admin' || $get('name') == 'Dhanabalan S' || $get('name') == 'Ranjith B'))
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        if (Filament::auth()->user()?->name != 'Dhanabalan S') {
                            $set('email', $state.'@cripumps.com');
                        }
                    })
                    ->maxLength(255),
                Forms\Components\TextInput::make('email')
                    ->label('Email')
                    ->required()
                    // ->email()
                    ->unique(ignoreRecord: true)
                    ->readOnly(fn () => Filament::auth()->user()?->name != 'Dhanabalan S')
                    // ->rule(function (callable $get) {
                    //     return Rule::unique('users', 'email')
                    //         ->ignore($get('id')); // Ignore current record during updates
                    // })
                    ->reactive()
                    // ->prefix(fn ($get) => $get('name') ?? null)
                    // ->suffix('@cripumps.com')
                    ->maxLength(255),
                Forms\Components\DateTimePicker::make('email_verified_at')
                    ->label('Email Verified At'),
                Forms\Components\TextInput::make('password')
                    ->label('Password')
                    ->required()
                    ->password()
                    ->minLength(3)
                    ->revealable()
                    ->disabled(fn (Get $get) => ! empty($get('id')) && Filament::auth()->user()?->name != 'Admin' && Filament::auth()->user()?->name != 'Dhanabalan S' && Filament::auth()->user()?->name != 'Ranjith B' && ($get('name') == 'Admin' || $get('name') == 'Dhanabalan S' || $get('name') == 'Ranjith B'))
                    // ->dehydrateStateUsing(fn (string $state): string => Hash::make($state))
                    ->maxLength(255),
                // Forms\Components\Select::make('roles')
                //     ->multiple()
                //     ->relationship('roles', 'name'),
                Forms\Components\Select::make('roles')
                    ->label('Roles')
                    ->relationship('roles', 'name')
                    // ->relationship(name: 'roles', titleAttribute: 'name')
                    // ->saveRelationshipsUsing(function (Model $record, $state) {
                    //     $record->roles()->syncWithPivotValues($state, [config('permission.column_names.team_foreign_key') => getPermissionsTeamId()]);
                    // })
                    ->multiple()
                    ->preload()
                    ->searchable(),
                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // Tables\Columns\TextColumn::make('id')
                //     ->label('ID')
                //     ->numeric()
                //     ->sortable(),

                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 Name')
                    ->default('All')
                    ->alignCenter()
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('name')
                    ->label('User Name')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('email')
                    ->label('Email')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('email_verified_at')
                    ->label('Email Verified At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('roles.name')
                    ->label('Roles')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->dateTime()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->dateTime()
                    ->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 Users')
                    ->color('warning')
                    ->importer(UserImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import user');
                    }),
                ExportAction::make()
                    ->label('Export Users')
                    ->color('warning')
                    ->exporter(UserExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export user');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListUsers::route('/'),
            'create' => Pages\CreateUser::route('/create'),
            'view' => Pages\ViewUser::route('/{record}'),
            'edit' => Pages\EditUser::route('/{record}/edit'),
        ];
    }

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