<?php

namespace App\Filament\Resources;

use App\Filament\Resources\UserResource\Pages;
use App\Filament\Resources\UserResource\RelationManagers;
use App\Models\User;
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;

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

    protected static ?string $modelLabel = 'Ahli Keluarga';
    protected static ?string $pluralModelLabel = 'Senarai Ahli Keluarga';
    protected static ?string $navigationLabel = 'Ahli Keluarga';
    protected static ?string $navigationIcon = 'heroicon-o-users';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('Maklumat Peribadi')
                    ->schema([
                        Forms\Components\TextInput::make('name')
                            ->label('Nama Penuh')
                            ->required()
                            ->maxLength(255),
                        Forms\Components\Select::make('gender')
                            ->label('Jantina')
                            ->options([
                                'Lelaki' => 'Lelaki',
                                'Perempuan' => 'Perempuan',
                            ])
                            ->required(),
                        Forms\Components\DatePicker::make('dob')
                            ->label('Tarikh Lahir'),
                        Forms\Components\TextInput::make('dob_code')
                            ->label('Kod Lahir (6 Digit KP)')
                            ->maxLength(6)
                            ->numeric()
                            ->default(null),
                        Forms\Components\TextInput::make('phone_number')
                            ->label('Nombor Telefon')
                            ->tel()
                            ->maxLength(255)
                            ->unique(ignoreRecord: true)
                            ->default(null),
                        Forms\Components\Textarea::make('address')
                            ->label('Alamat')
                            ->columnSpanFull(),
                        Forms\Components\TextInput::make('email')
                            ->label('Emel (Pilihan)')
                            ->email()
                            ->maxLength(255)
                            ->default(null),
                        Forms\Components\FileUpload::make('profile_photo_path')
                            ->label('Gambar Profil')
                            ->image()
                            ->directory('profile-photos'),
                    ])->columns(2),

                Forms\Components\Section::make('Status Hidup')
                    ->schema([
                        Forms\Components\Toggle::make('is_alive')
                            ->label('Masih Hidup?')
                            ->default(true)
                            ->reactive(),
                        Forms\Components\DatePicker::make('date_of_death')
                            ->label('Tarikh Meninggal Dunia')
                            ->hidden(fn (Forms\Get $get) => $get('is_alive')),
                    ])->columns(2),
                
                Forms\Components\Section::make('Keluarga Asal')
                    ->schema([
                        Forms\Components\Select::make('father_id')
                            ->label('Bapa')
                            ->relationship('father', 'name', fn (\Illuminate\Database\Eloquent\Builder $query) => $query->where('gender', 'Lelaki')->where('id', '!=', 1))
                            ->searchable(),
                        Forms\Components\Select::make('mother_id')
                            ->label('Ibu')
                            ->relationship('mother', 'name', fn (\Illuminate\Database\Eloquent\Builder $query) => $query->where('gender', 'Perempuan')->where('id', '!=', 1))
                            ->searchable(),
                    ])->columns(2),

                Forms\Components\Section::make('Sistem')
                    ->schema([
                        Forms\Components\Select::make('role')
                            ->label('Peranan (Akses)')
                            ->options([
                                'user' => 'Ahli Keluarga Biasa',
                                'admin' => 'Pentadbir Sistem',
                            ])
                            ->default('user')
                            ->required(),
                        Forms\Components\Textarea::make('notes')
                            ->label('Catatan')
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('profile_photo_path')
                    ->label('Gambar')
                    ->circular(),
                Tables\Columns\TextColumn::make('name')
                    ->label('Nama Penuh')
                    ->searchable(),
                Tables\Columns\TextColumn::make('phone_number')
                    ->label('No Telefon')
                    ->searchable(),
                Tables\Columns\TextColumn::make('dob')
                    ->label('Umur')
                    ->formatStateUsing(fn ($state) => $state ? \Carbon\Carbon::parse($state)->age . ' tahun' : '-')
                    ->sortable(),
                Tables\Columns\IconColumn::make('is_alive')
                    ->label('Status')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger'),
                Tables\Columns\TextColumn::make('role')
                    ->label('Peranan')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'admin' => 'warning',
                        'user' => 'success',
                    }),
            ])
            ->filters([
                //
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                // Disabled temporarily to prevent intl extension error in XAMPP Mac
            ]);
    }

    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'),
        ];
    }
}
