<?php

namespace App\Filament\Resources\Users;

use App\Models\User;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Schemas\Components\Section;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Select;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Filament\Tables;
use Illuminate\Support\Facades\Hash;
use Filament\Tables\Columns\TextColumn;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\BulkActionGroup;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Filament\Resources\Users\Pages\CreateUser;
use App\Filament\Resources\Users\Pages\EditUser;

// --- TAMBAHAN IMPORT BARU UNTUK FITUR KOMPLIT ---
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\Toggle;
use Filament\Tables\Columns\ImageColumn;
use Filament\Tables\Columns\ToggleColumn;
// ------------------------------------------------

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

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;

    public static function getNavigationGroup(): ?string
    {
        return 'Pengguna & Pengaturan';
    }
    public static function getNavigationSort(): ?int
    {
        return 1; // Ganti angkanya (1, 2, 3, dst) sesuai urutan yang diinginkan
    }

    public static function getModelLabel(): string
    {
        return 'Data Pengguna';
    }

    public static function getPluralModelLabel(): string
    {
        return 'Data Pengguna';
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                // --- Section Foto Profil ---
                Section::make('Foto Profil')
                    ->schema([
                        FileUpload::make('avatar')
                            ->image()
                            ->avatar()
                            ->directory('users/avatars')
                            ->label('Upload Avatar')
                            ->columnSpanFull()
                            ->alignCenter(),
                    ]),

                Section::make('Informasi Pengguna')
                    ->schema([
                        TextInput::make('name')
                            ->required()
                            ->label('Nama Lengkap')
                            ->maxLength(255),

                        TextInput::make('email')
                            ->email()
                            ->required()
                            ->label('Alamat Email')
                            ->unique(ignoreRecord: true)
                            ->maxLength(255),

                        // --- Input Nomor HP ---
                        TextInput::make('phone')
                            ->tel()
                            ->label('Nomor HP / WhatsApp')
                            ->maxLength(255),

                        TextInput::make('password')
                            ->password()
                            ->label('Password')
                            ->dehydrateStateUsing(fn($state) => Hash::make($state))
                            ->dehydrated(fn($state) => filled($state))
                            ->required(fn(string $context): bool => $context === 'create'),
                    ])->columns(2),

                // --- BARU: Section Verifikasi Data Mitra (Khusus Owner) ---
                Section::make('Verifikasi Mitra (Khusus Owner)')
                    ->description('Data identitas resmi pendaftaran pemilik kos')
                    ->schema([
                        TextInput::make('nik')
                            ->label('Nomor Induk Kependudukan (NIK)')
                            ->numeric()
                            ->maxLength(16)
                            ->placeholder('16 Digit NIK KTP'),

                        Select::make('approval_status')
                            ->label('Status Persetujuan Akun')
                            ->options([
                                'pending' => 'Menunggu Tinjauan (Pending)',
                                'approved' => 'Disetujui (Approved)',
                                'rejected' => 'Ditolak (Rejected)',
                            ])
                            ->default('approved')
                            ->required(),

                        TextInput::make('listing_quota')
                            ->label('Kuota Posting Properti')
                            ->numeric()
                            ->default(1)
                            ->required(),

                        FileUpload::make('ktp_image')
                            ->label('Foto KTP')
                            ->image()
                            ->disk('public')
                            ->directory('ktp_verifications')
                            ->columnSpanFull(),
                    ])->columns(2),

                // --- Section Detail & Hak Akses ---
                Section::make('Detail & Hak Akses')
                    ->schema([
                        Textarea::make('address')
                            ->label('Alamat Lengkap')
                            ->columnSpanFull(),

                        Select::make('roles')
                            ->relationship('roles', 'name')
                            ->multiple()
                            ->preload()
                            ->searchable()
                            ->label('Peran (Role)')
                            ->helperText('Pilih status user: super_admin, admin, Owner, atau tenant.'),

                        Toggle::make('is_active')
                            ->label('Akun Aktif?')
                            ->default(true)
                            ->helperText('Nonaktifkan untuk memblokir user dari aplikasi.'),
                    ])->columns(2),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                // --- Kolom Foto Profil ---
                ImageColumn::make('avatar')
                    ->circular()
                    ->label('Foto'),

                TextColumn::make('name')
                    ->searchable()
                    ->sortable()
                    ->label('Nama'),

                TextColumn::make('email')
                    ->searchable()
                    ->label('Email'),

                // --- Kolom Nomor HP ---
                TextColumn::make('phone')
                    ->searchable()
                    ->label('Nomor HP'),

                TextColumn::make('roles.name')
                    ->badge()
                    ->label('Role')
                    ->searchable(),

                // --- BARU: Kolom Status Persetujuan Akun ---
                TextColumn::make('approval_status')
                    ->label('Persetujuan')
                    ->badge()
                    ->color(fn(string $state): string => match ($state) {
                        'pending' => 'warning',
                        'approved' => 'success',
                        'rejected' => 'danger',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'pending' => 'Pending',
                        'approved' => 'Disetujui',
                        'rejected' => 'Ditolak',
                        default => $state,
                    })
                    ->sortable(),

                // --- Kolom Status Aktif ---
                ToggleColumn::make('is_active')
                    ->label('Status Aktif')
                    ->sortable(),

                TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                //
            ])
            ->actions([
                EditAction::make(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

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

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