<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TestingTempResource\Pages;
use App\Models\Plant;
use App\Models\TestingTemp;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Storage;

class TestingTempResource extends Resource
{
    protected static ?string $model = TestingTemp::class;

    protected static ?string $navigationIcon = 'heroicon-c-circle-stack';

    protected static ?string $navigationGroup = 'IIOT Temp';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant Name')
                    ->relationship('plant', 'name')
                    ->required()
                    ->searchable()
                    // ->preload()
                    ->nullable()
                    ->reactive()
                    ->columnSpan(1)
                    ->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();
                    })
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        $set('ivPlantError', null);
                        $set('name', null);
                        $set('selected_file', null);
                        $set('attachment', null);
                        if (! $plantId) {
                            $set('ivPlantError', 'Please select a plant first.');
                        } else {
                            $plantCode = Plant::find($plantId)?->code ?? null;

                            $directory = "uploads/temp/{$plantCode}";
                            if (! Storage::disk('local')->exists($directory)) {
                                Storage::disk('local')->makeDirectory($directory);
                            }
                        }

                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('ivPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('ivPlantError') ? $get('ivPlantError') : null)
                    ->hintColor('danger'),
                Forms\Components\TextInput::make('name')
                    ->label('File Name')
                    ->required()
                    ->reactive()
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        $fileNam = $get('name');
                        // $set('selected_file', null);
                        if (! $plantId) {
                            $set('name', null);
                        } elseif (! $fileNam) {
                            $set('attachment', null);
                        }
                        $set('updated_by', Filament::auth()->user()?->name);
                    }),
                Forms\Components\Select::make('selected_file')
                    ->label('Select Uploaded File')
                    ->searchable()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            return collect(Storage::disk('local')->files('uploads/temp'))
                                ->mapWithKeys(function ($file) {
                                    return [
                                        $file => basename($file), // value => label
                                    ];
                                })
                                ->toArray();
                        }

                        $plantCode = Plant::find($plantId)?->code ?? null;

                        return collect(Storage::disk('local')->files("uploads/temp/{$plantCode}"))
                            ->mapWithKeys(function ($file) {
                                return [
                                    $file => basename($file), // value => label
                                ];
                            })
                            ->toArray();
                    })
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        // $plantId = $get('plant_id');
                        // if (! $plantId) {
                        //     $set('selected_file', null);
                        // }
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->reactive(),
                // ->disabled(fn (callable $get) => ! $get('plant_id')),
                Forms\Components\FileUpload::make('attachment')
                    ->label('Choose File to Upload')
                    // ->acceptedFileTypes(['application/pdf'])
                    ->storeFiles(false)
                    ->disk('local')
                    ->directory(function (callable $get) {
                        $plantId = $get('plant_id');
                        $plantCode = Plant::find($plantId)?->code ?? null;

                        return "uploads/temp/{$plantCode}";
                    })
                    ->preserveFilenames()
                    ->maxSize(20480) // 20 MB
                    ->afterStateUpdated(function ($state, callable $set, callable $get) {
                        $plantId = $get('plant_id');
                        if (! $plantId) {
                            $set('attachment', null);
                        }
                        $set('updated_by', Filament::auth()->user()?->name);
                    })
                    ->required(function (callable $get) {
                        $selFile = $get('selected_file');
                        $selAtt = $get('attachment');
                        if (! $selAtt && ! $selFile) {
                            return true;
                        }

                        return false;
                    })
                    ->reactive()
                    ->disabled(fn (callable $get) => ! $get('plant_id') || ! $get('name')),
                Forms\Components\Actions::make([
                    Action::make('uploadNow')
                        ->label('Upload File')
                        ->icon('heroicon-c-cloud-arrow-up')
                        ->color('success')
                        ->requiresConfirmation(function (callable $get) {
                            $filePath = $get('attachment');
                            if ($filePath) {
                                return true;
                            }

                            return false;
                        })
                        ->action(function (callable $get, callable $set) {

                            $uploadedFiles = $get('attachment');

                            if (is_array($uploadedFiles) && count($uploadedFiles) > 0) {

                                $uploaded = reset($uploadedFiles);

                                if ($uploaded instanceof TemporaryUploadedFile) {

                                    $baseName = $get('name');
                                    $extension = $uploaded->getClientOriginalExtension();

                                    $finalFileName = $baseName.'.'.$extension;

                                    $plantId = $get('plant_id');
                                    $plantCode = Plant::find($plantId)?->code ?? null;

                                    if (! $plantCode) {
                                        Notification::make()
                                            ->title('Please select a plant first.')
                                            ->warning()
                                            ->send();

                                        return;
                                    } elseif (! $baseName) {
                                        Notification::make()
                                            ->title('Please enter a file name first.')
                                            ->warning()
                                            ->send();

                                        return;
                                    }
                                    // return "uploads/temp/{$plantCode}";

                                    $uploaded->storeAs(
                                        "uploads/temp/{$plantCode}",
                                        $finalFileName,
                                        'local'
                                    );

                                    $set('updated_by', Filament::auth()->user()?->name);

                                    Notification::make()
                                        ->title("File uploaded successfully: {$finalFileName}")
                                        ->success()
                                        ->send();
                                }

                            } else {
                                if (! $get('plant_id')) {
                                    Notification::make()
                                        ->title('Please select a plant first.')
                                        ->warning()
                                        ->send();
                                } elseif (! $get('name')) {
                                    Notification::make()
                                        ->title('Please enter a file name first.')
                                        ->warning()
                                        ->send();
                                } else {
                                    Notification::make()
                                        ->title('No file selected to upload')
                                        ->warning()
                                        ->send();
                                }
                            }
                        }),

                    Action::make('downloadAttachment')
                        ->label('Download File')
                        ->icon('heroicon-c-cloud-arrow-down')
                        ->color('warning')
                        ->requiresConfirmation(function (callable $get) {
                            $filePath = $get('selected_file');
                            if ($filePath) {
                                return true;
                            }

                            return false;
                        })
                        ->action(function (callable $get, callable $set) {
                            $filePath = $get('selected_file'); // uploads/filename.pdf

                            // if (! $get('plant_id')) {
                            //     Notification::make()
                            //         ->title('Please select a plant first.')
                            //         ->warning()
                            //         ->send();

                            //     return;
                            // } else
                            if (! $filePath) {
                                Notification::make()
                                    ->title('Please select a file first.')
                                    ->warning()
                                    ->send();

                                return;
                            } elseif (! Storage::disk('local')->exists($filePath)) {
                                Notification::make()
                                    ->title('File not found')
                                    ->danger()
                                    ->send();

                                return;
                            }

                            $set('updated_by', Filament::auth()->user()?->name);

                            Notification::make()
                                ->title('File downloaded successfully')
                                ->success()
                                ->send();

                            return response()->download(
                                Storage::disk('local')->path($filePath)
                            );
                        }),

                    Action::make('deleteAttachment')
                        ->label('Delete File')
                        ->icon('heroicon-c-trash')
                        ->color('danger')
                        ->requiresConfirmation(function (callable $get) {
                            $filePath = $get('selected_file');

                            if ($filePath) {
                                return true;
                            }

                            return false;
                        })
                        ->action(function ($get, $set) {

                            $filePath = $get('selected_file'); // uploads/filename.pdf

                            // if (! $get('plant_id')) {
                            //     Notification::make()
                            //         ->title('Please select a plant first.')
                            //         ->warning()
                            //         ->send();

                            //     return;
                            // } else
                            if (! $filePath) {
                                Notification::make()
                                    ->title('Please select a file first.')
                                    ->warning()
                                    ->send();

                                return;
                            } elseif (! Storage::disk('local')->exists($filePath)) {
                                Notification::make()
                                    ->title('File not found')
                                    ->danger()
                                    ->send();

                                return;
                            }

                            Storage::disk('local')->delete($filePath);

                            $set('selected_file', null);

                            Notification::make()
                                ->title('File deleted successfully')
                                ->success()
                                ->send();
                        }),

                ]),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name)
                    ->reactive(),
                Forms\Components\Hidden::make('updated_by')
                    ->label('Updated By')
                    ->default(Filament::auth()->user()?->name)
                    ->reactive(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('ID')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->dateTime()
                    ->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(),
                ]),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListTestingTemps::route('/'),
            'create' => Pages\CreateTestingTemp::route('/create'),
            'view' => Pages\ViewTestingTemp::route('/{record}'),
            'edit' => Pages\EditTestingTemp::route('/{record}/edit'),
        ];
    }

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