<?php

namespace App\Filament\App\Resources;

use App\Filament\App\Resources\UserResource\Pages;
use App\Filament\App\Resources\UserResource\RelationManagers;
use App\Models\Departemen;
use App\Models\Jabatan;
use App\Models\Level;
use App\Models\Role;
use App\Models\User;
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\Support\Enums\Alignment;
use Filament\Support\Enums\FontWeight;
use Filament\Tables\Columns\Layout\Split;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\Layout\Panel;
use Filament\Tables\Columns\TextColumn;
use Illuminate\Support\Facades\Hash;

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

    //protected static ?string $navigationGroup = 'Manajemen Pengguna';
    protected static ?string $navigationIcon = 'heroicon-o-user-group';
    protected static ?string $label = 'Manajemen Pengguna';
    protected static ?string $navigationGroup = 'hidden-nav-2';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Split::make([
                    Forms\Components\Section::make([
                        Forms\Components\Fieldset::make('Akun Informasi')
                            ->columns(2)
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->label('Nama Akun')
                                    ->required()
                                    ->maxLength(255),
                                Forms\Components\TextInput::make('password')
                                    ->password()
                                    ->dehydrateStateUsing(fn(string $state): string => Hash::make($state))
                                    ->dehydrated(fn(?string $state): bool => filled($state))
                                    ->required(fn(string $context): bool => $context === 'create'),
                                Forms\Components\TextInput::make('pegawai_id')
                                    ->label('Nomer Pegawai')
                                    ->maxLength(255)
                                    ->unique(ignoreRecord: true),
                                Forms\Components\TextInput::make('email')
                                    ->email()
                                    ->required()
                                    ->maxLength(255),
                                Forms\Components\TextInput::make('telp')
                                    ->label('Nomer Telepon')
                                    ->tel(),
                                Forms\Components\Select::make('status')
                                    ->options([
                                        'Aktif' => 'Aktif',
                                        'Tidak Aktif' => 'Tidak Aktif',
                                        'Cuti' => 'Cuti',
                                        'Keluar' => 'Keluar',
                                    ])
                                    ->default('Aktif'),

                                Forms\Components\Hidden::make('is_guest')
                                    ->default('Internal')
                                // ->live(),
                            ]),
                        Forms\Components\Fieldset::make('Informasi Pengguna')
                            ->columns(2)
                            ->schema([
                                Forms\Components\Select::make('departemen_id')
                                    ->label('Departemen')
                                    ->preload()
                                    ->options(Departemen::all()->pluck('name', 'id'))
                                    ->searchable()
                                    ->live()
                                    ->columnSpanFull()
                                    ->afterStateUpdated(function (callable $set) {
                                        $set('jabatan_id', null);
                                    }),
                                Forms\Components\Select::make('jabatan_id')
                                    ->label('Jabatan')
                                    ->preload()
                                    ->live()
                                    ->options(function (callable $get) {
                                        return Jabatan::where('departemen_id', $get('departemen_id'))->pluck('name', 'id');
                                    })
                                    ->searchable(),
                                Forms\Components\Select::make('roles')
                                    ->relationship('roles', 'name')
                                    ->label('Level Akses')
                                    ->searchable()
                                    ->preload(),
                            ]),

                    ]),
                    Forms\Components\Section::make([
                        Forms\Components\FileUpload::make('avatar_url')
                            ->label('Foto Profil')
                            ->directory('avatar')
                            ->maxSize(10 * 1024 * 1024)
                            ->image()
                            ->avatar()
                            ->circleCropper()
                            ->imageEditor(),
                    ])->grow(false)
                ])->columnSpanFull()->from('md'),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Stack::make([


                    Split::make([
                        ImageColumn::make('avatar_url')
                            ->circular()
                            ->grow(false)
                            ->defaultImageUrl(fn() => asset('images/avatar.jpg')),
                        Stack::make([
                            TextColumn::make('name')
                                ->weight(FontWeight::Bold)
                                ->label('Nama')
                                ->searchable()
                                ->sortable()
                                ->limit(20)
                                ->tooltip(function (TextColumn $column): ?string {
                                    $state = $column->getState();

                                    if (strlen($state) <= $column->getCharacterLimit()) {
                                        return null;
                                    }
                                    // Only render the tooltip if the column content exceeds the length limit.
                                    return $state;
                                }),
                            Tables\Columns\TextColumn::make('status')
                                ->badge()
                                ->color(fn(string $state): string => match ($state) {
                                    'Aktif' => 'success',
                                    'Tidak Aktif' => 'gray',
                                    'Cuti' => 'warning',
                                    'Keluar' => 'danger',
                                }),

                        ]),
                        Stack::make([
                            TextColumn::make('pegawai_id')
                                ->icon('heroicon-m-identification')
                                ->searchable()
                                ->sortable(),
                            TextColumn::make('telp')
                                ->icon('heroicon-m-phone')
                                ->label('No Telepon')
                                ->searchable(),
                            TextColumn::make('email')
                                ->icon('heroicon-m-envelope')
                                ->searchable()
                                ->limit(20)
                                ->tooltip(function (TextColumn $column): ?string {
                                    $state = $column->getState();

                                    if (strlen($state) <= $column->getCharacterLimit()) {
                                        return null;
                                    }
                                    // Only render the tooltip if the column content exceeds the length limit.
                                    return $state;
                                })
                        ]),
                        Stack::make([
                            Tables\Columns\TextColumn::make('departemen.name')
                                ->sortable()
                                ->weight(FontWeight::Bold)
                                ->formatStateUsing(function ($state, $record) {
                                    if ($record->is_guest === '') {
                                        return 'External';
                                    }
                                    return $state;
                                })
                                ->default(''),
                            Tables\Columns\TextColumn::make('jabatan.name')
                                ->label('Akses')
                                ->prefix('')
                                ->sortable()
                        ]),
                    ]),
                ])

            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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