<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PeribadiResource\Pages;
use App\Filament\Resources\PeribadiResource\RelationManagers;
use App\Models\Pengguna;
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;
use Illuminate\Support\Facades\Auth;
use Filament\Tables\Columns\ImageColumn;
use Filament\Forms\Components\Select;
use Filament\Tables\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Notifications\Notification;

use App\Models\Gred;
use App\Models\InstitusiJabatan;
use Illuminate\Support\Facades\Hash;

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

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static ?string $navigationLabel = 'MAKLUMAT PERIBADI';

    protected static ?string $pluralModelLabel = 'MAKLUMAT PERIBADI';

    protected static ?string $navigationGroup = 'PERIBADI';

    protected static ?string $slug = 'peribadi';

    public static function form(Form $form): Form
    {
        $jenis_pengguna = auth()->user()->roles()->value('id');
        $email = Auth::user()->email;
        $no_institusi_jabatan = Auth::user()->no_institusi_jabatan;

        return $form
            ->schema([
                Forms\Components\TextInput::make('nama')->label('Nama')->rules(['required', 'max:100']),
                Forms\Components\TextInput::make('email')->email()->label('Emel')->disabled()->rules(['required', 'max:100']),
                Select::make('gred')
                    ->label('Gred Jawatan')
                    ->options(Gred::all()->pluck('nama', 'no'))
                    ->rules(['required'])
                    ->disabled(),
                Select::make('no_institusi_jabatan')
                    ->label('Institusi & Jabatan')
                    ->placeholder('Sila Pilih Maklumat')
                    ->options(function () use ($jenis_pengguna, $no_institusi_jabatan) {
                        // Eager load related models

                        $institusiJabatans = InstitusiJabatan::with('institusi', 'jabatan');

                        if ($jenis_pengguna == 2) {
                            $userId = Auth::id();
                            // Modify the query to include a where clause for jenis_pengguna = 2
                            $institusiJabatans->where('no', $no_institusi_jabatan);
                        }

                        $institusiJabatans = $institusiJabatans->get();

                        // Manipulate data to format as needed for select dropdown
                        return $institusiJabatans->mapWithKeys(function ($institusiJabatan) {
                            return [$institusiJabatan->no => $institusiJabatan->jabatan->nama];
                        });
                    })
                    ->rules(['required'])
                    ->disabled(),
            ]);
    }

    public static function table(Table $table): Table
    {

        $jenis_pengguna = Auth::user()->jenis_pengguna;
        $email = Auth::user()->email;
        $no_institusi_jabatan = Auth::user()->no_institusi_jabatan;

        $penggunaQuery = Pengguna::query()
            ->with(['senaraiGred', 'institusiJabatan'])->where('email', $email);

        return $table
            ->query($penggunaQuery)
            ->columns([
                ImageColumn::make('GAMBAR')
                    ->label('GAMBAR')
                    ->width(150)
                    ->height(150)
                    ->circular()
                    ->getStateUsing(function ($record) {
                        return url('storage/gambar/' . $record->email . '/' . $record->gambar);
                    }),
                Tables\Columns\TextColumn::make('nama')->label('NAMA'),
                Tables\Columns\TextColumn::make('email')->label('EMEL')->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('senaraigred.nama')->label('GRED'),
                Tables\Columns\TextColumn::make('institusiJabatan.institusi.nama')->label('INSTITUSI')->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('institusiJabatan.jabatan.nama')->label('JABATAN'),
            ])
            ->deferLoading()
            ->filters([
                //
            ])
            ->actions([
                Action::make('muat_turun')
                    ->label('')
                    ->icon('heroicon-o-arrow-up-tray')
                    ->form(function ($record) {
                        $formFields = [];

                        // Assuming $record->no is used to determine the form fields dynamically
                        switch ($record->no) {
                            case 1:
                            //
                            // break;
                            case 2:
                            //
                            // break;
                            case 3:
                            //
                            // break;
                            case 4:
                            //
                            // break;
                            case 5:
                            //
                            // break;
                            // Add more cases as needed

                            default:
                                // Default behavior if $record->no doesn't match any case
                                $formFields[] = FileUpload::make('gambar')
                                    ->label('MUAT NAIK GAMBAR')
                                    ->image()
                                    ->minSize(1)
                                    ->maxSize(2048)
                                    ->directory(function () use ($record) {
                                    $directory = 'gambar/' . $record->email;
                                    return $directory;
                                })
                                    ->visibility('private'); // Assuming Sesi is a model

                                break;
                        }

                        return $formFields;
                    })
                    ->action(function (array $data, Pengguna $record) {

                        // Pengguna::where('email', $record->email)->update([
                        //     'gambar' => 1,
                        // ]);

                        // Construct the full path of the file to delete
                        $filePath = storage_path('/app/public/gambar/' . $record->email . '/' . basename($record->gambar));

                        // unlink(storage_path('/app/public/gambar/' . $record->email . '/' . basename($record->gambar)));

                        if (file_exists($filePath)) {
                            // Delete the file
                            unlink(storage_path('/app/public/gambar/' . $record->email . '/' . basename($record->gambar)));
                        }

                        // Find the record using the email
                        $pengguna = Pengguna::where('email', $record->email)->first();

                        // Update the 'gambar' attribute
                        $pengguna->gambar = basename($data['gambar']);

                        // Save the changes
                        $pengguna->save();

                        // Send success notification
                        Notification::make()
                            ->title('Muat Naik berjaya.')
                            ->success()
                            ->send();
                    }),
                Action::make('password')
                    ->label('')
                    ->icon('heroicon-o-cog')
                    ->form(function ($record) {
                        $formFields = [];

                        // Assuming $record->no is used to determine the form fields dynamically
                        switch ($record->no) {
                            case 1:
                            //
                            // break;
                            case 2:
                            //
                            // break;
                            case 3:
                            //
                            // break;
                            case 4:
                            //
                            // break;
                            case 5:
                            //
                            // break;
                            // Add more cases as needed

                            default:
                                // Default behavior if $record->no doesn't match any case
                                $formFields[] = Forms\Components\TextInput::make('password')->label('KATA LALUAN')->rules(['required', 'max:100']); // Assuming Sesi is a model

                                break;
                        }

                        return $formFields;
                    })
                    ->action(function (array $data, Pengguna $record) {

                        // Find the record using the email
                        $pengguna = Pengguna::where('email', $record->email)->first();

                        // Update the 'gambar' attribute
                        $pengguna->password = Hash::make($data['password']);

                        // Save the changes
                        $pengguna->save();

                        // Send success notification
                        Notification::make()
                            ->title('Kata Laluan telah dikemaskini.')
                            ->success()
                            ->send();
                    }),
                Tables\Actions\EditAction::make()->label(''),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    //Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->paginated(false);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPeribadis::route('/'),
            'create' => Pages\CreatePeribadi::route('/create'),
            'edit' => Pages\EditPeribadi::route('/{record:slug}/edit'),
        ];
    }

    public static function canCreate(): bool
    {
        return false;
    }

    public static function canViewAny(): bool
    {
        // dd(auth()->user()->roles());
        return auth()
            ->user()
            ->hasAnyRole(['Super Admin', 'Penyelaras', 'Pengguna', 'Pengurusan']);
    }

}
