<?php

namespace App\Filament\Resources;

use App\Filament\Resources\DriverMasterResource\Pages;
use App\Filament\Resources\DriverMasterResource\RelationManagers;
use App\Models\DriverMaster;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\TextInput;
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 Filament\Forms\Components\Actions;
use Filament\Forms\Components\Actions\Action;
use Filament\Notifications\Notification;
use League\Flysystem\Filesystem;
use League\Flysystem\FilesystemAdapter;
use League\Flysystem\Sftp\SftpAdapter;
use phpseclib3\Net\SFTP;

class DriverMasterResource extends Resource
{
    protected static ?string $model = DriverMaster::class;

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

    protected static ?string $navigationGroup = 'Transport Tracking';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label('Name')
                    ->required(),
                Forms\Components\TextInput::make('identification1')
                    ->label('Aadhar Number')
                    ->required(),
                Forms\Components\TextInput::make('identification2')
                    ->label('Driving License Number')
                    ->required(),
                Forms\Components\TextInput::make('identification3')
                    ->label('PAN Number'),
                Forms\Components\TextInput::make('contact_number')
                    ->label('Contact Number')
                    ->required(),
                Forms\Components\TextInput::make('alternate_number')
                    ->label('Alternate Number'),
                // Forms\Components\TextInput::make('file_name')
                //     ->label('File Name')
                //     ->placeholder('Enter file name without extension')
                //     ->required()
                //     ->reactive()
                //     ->extraAttributes([
                //     'onkeydown' => 'if(event.key == "Enter"){ event.preventDefault(); openFileDialog(); }',
                // ]),
                // Forms\Components\Actions::make([
                //     Action::make('read_folder')
                //         ->label('Read Folder')
                //         ->icon('heroicon-o-folder')
                //         ->color('info')
                //         //->extraAttributes(['onclick' => 'openFolderPicker()']),
                //          ->extraAttributes(['onclick' => 'openFileDialog()']),
                // ]),

                TextInput::make('file_name')
                    ->label('File Name')
                    ->required()
                    ->reactive()
                    ->extraAttributes([
                        'x-data' => '{ value: "" }',
                        'x-model' => 'value',
                        'x-on:keydown.enter.prevent' => '$wire.process(value)',
                    ]),

                // Filament Action inside your form/page
                 Actions::make([
                    Action::make('read_file')
                        ->label('Read File')
                        //->hidden()
                        ->action(function ($get) {
                            $fileName = $get('file_name');
                            if (!$fileName) {
                                Notification::make()
                                    ->title('File name is required!')
                                    ->danger()
                                    ->send();
                                return;
                            }

                            $ftpHost = env('SFTP_HOST');
                            $ftpUser = env('SFTP_USERNAME');
                            $ftpPass = env('SFTP_PASSWORD');
                            $remoteDir = env('SFTP_ROOT');
                            $port = env('SFTP_PORT');

                            $sftp = new SFTP($ftpHost, $port, 10);
                            if (! $sftp->login($ftpUser, $ftpPass)) {
                                Notification::make()->title('SFTP login failed')->danger()->send();
                                return;
                            }

                            // $files = $sftp->nlist();

                            // dd($files);

                            $remoteFile = $remoteDir . '/' . $fileName . '.txt';
                            $content = $sftp->get($remoteFile);

                            if ($content == false) {
                                Notification::make()
                                    ->title("File {$remoteFile} not found")
                                    ->danger()
                                    ->send();
                                return;
                            }

                            if ($content == false) {
                                Notification::make()
                                    ->title("Failed to read {$remoteDir} from SFTP")
                                    ->danger()
                                    ->send();
                                return;
                            }

                            $lines = array_map('trim', explode("\n", str_replace("\r", "", $content)));

                            DriverMaster::create([
                                'name' => $lines[0] ?? '',
                                'identification1' => $lines[1] ?? '',
                                'identification2' => $lines[2] ?? '',
                                'identification3' => $lines[3] ?? '',
                                'contact_number' => $lines[4] ?? '',
                                'alternate_number' => $lines[5] ?? '',
                            ]);

                            Notification::make()
                                ->title("File {$remoteDir} read and saved successfully!")
                                ->success()
                                ->send();
                            }),
                    ]),

                    Forms\Components\Hidden::make('created_by')
                        ->required()
                        ->default(Filament::auth()->user()?->name),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('No.')
                    ->label('No.')
                    ->getStateUsing(function ($record, $livewire, $column, $rowLoop) {
                        $paginator = $livewire->getTableRecords();
                        $perPage = method_exists($paginator, 'perPage') ? $paginator->perPage() : 10;
                        $currentPage = method_exists($paginator, 'currentPage') ? $paginator->currentPage() : 1;
                        return ($currentPage - 1) * $perPage + $rowLoop->iteration;
                    }),
                Tables\Columns\TextColumn::make('name')
                    ->label('Name')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('identification1')
                    ->label('Aadhar Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('identification2')
                    ->label('Driving License Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('identification3')
                    ->label('PAN Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('contact_number')
                    ->label('Contact Number')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('alternate_number')
                    ->label('Alternate Number')
                    ->alignCenter()
                    ->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\ListDriverMasters::route('/'),
            'create' => Pages\CreateDriverMaster::route('/create'),
            'view' => Pages\ViewDriverMaster::route('/{record}'),
            'edit' => Pages\EditDriverMaster::route('/{record}/edit'),
        ];
    }

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