<?php

namespace App\Filament\Resources;

use App\Filament\Exports\ProcessOrderExporter;
use App\Filament\Imports\ProcessOrderImporter;
use App\Filament\Resources\ProcessOrderResource\Pages;
use App\Models\Plant;
use App\Models\ProcessOrder;
use Filament\Facades\Filament;
use Filament\Forms;
use Filament\Forms\Components\Actions\Action;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Forms\Set;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Actions\ExportAction;
use Filament\Tables\Actions\ImportAction;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Smalot\PdfParser\Parser;
use Storage;

class ProcessOrderResource extends Resource
{
    protected static ?string $model = ProcessOrder::class;

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

    protected static ?string $navigationGroup = 'Process Order';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Select::make('plant_id')
                    ->label('Plant')
                    ->reactive()
                    ->relationship('plant', 'name')
                    ->options(function (callable $get) {
                        $userHas = Filament::auth()->user()->plant_id;

                        return ($userHas && strlen($userHas) > 0) ? Plant::where('id', $userHas)->pluck('name', 'id')->toArray() : Plant::pluck('name', 'id')->toArray();
                    })
                    ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
                        $plantId = $get('plant_id');
                        $set('coil_number', null);
                        $set('sfg_number', null);
                        $set('machine_name', null);
                        if (! $plantId) {
                            $set('poPlantError', 'Please select a plant first.');
                            $set('coilNumberError', null);
                            $set('sfgNumberError', null);
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('poPlantError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('poPlantError') ? $get('poPlantError') : null)
                    ->hintColor('danger')
                    ->required(),
                Forms\Components\Select::make('item_id')
                    ->label('Item Code')
                    // ->relationship('item', 'id')
                    // ->required(),
                    ->reactive()
                    ->searchable()
                    ->options(function (callable $get) {
                        $plantId = $get('plant_id');
                        if (empty($plantId)) {
                            return [];
                        }

                        return \App\Models\Item::where('plant_id', $plantId)->pluck('code', 'id');
                    })
                    ->afterStateUpdated(function (callable $set, callable $get, ?string $state) {
                        $plantId = $get('plant_id');
                        $itemId = $get('item_id');
                        // dd($plantId);

                        if ($plantId && $itemId) {
                            // Get the item code using item_id
                            $itemCode = \App\Models\Item::where('id', $itemId)->value('code');

                            if ($itemCode) {
                                // Now get the item description using plant_id + code
                                $item = \App\Models\Item::where('plant_id', $plantId)
                                    ->where('code', $itemCode)
                                    ->first();

                                $set('item_description', $item?->description);
                            } else {
                                $set('item_description', null);
                            }
                        } else {
                            $set('item_description', null);
                        }
                    })
                    ->required(),

                Forms\Components\TextInput::make('item_description')
                    ->label('Description')
                    ->required()
                    ->reactive()
                    ->afterStateHydrated(function ($component, $state, Get $get, Set $set) {
                        $itemId = $get('item_id');
                        if ($get('id')) {

                            $item = \App\Models\Item::where('id', $itemId)->first()?->description;
                            if ($item) {
                                $set('item_description', $item);
                            } else {
                                $set('item_description', null);
                            }
                        }
                    }),

                Forms\Components\TextInput::make('id')
                    ->hidden()
                    ->readOnly(),
                // ->readOnly(true),

                Forms\Components\TextInput::make('process_order')
                    ->label('Process Order')
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
                        $plantId = $get('plant_id');
                        $set('coil_number', null);
                        $set('sfg_number', null);
                        $set('machine_name', null);
                        if (! $plantId) {
                            $set('poPlantError', 'Please select a plant first.');
                            $set('process_order', null);
                            $set('coilNumberError', null);
                            $set('sfgNumberError', null);
                        }
                    })
                    ->required(),
                Forms\Components\TextInput::make('coil_number')
                    ->label('Coil Number')
                    ->default('0')
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
                        $plantId = $get('plant_id');
                        $processOrder = $get('process_order');
                        $coilNo = $get('coil_number');
                        if (! $plantId) {
                            $set('poPlantError', 'Please select a plant first.');
                            $set('coil_number', null);
                            $set('sfg_number', null);
                            $set('machine_name', null);
                            $set('coilNumberError', null);
                            $set('sfgNumberError', null);
                        } elseif (! $processOrder) {
                            $set('coil_number', null);
                            $set('sfg_number', null);
                            $set('machine_name', null);
                            $set('poPlantError', null);
                            $set('coilNumberError', null);
                            $set('sfgNumberError', null);
                        } elseif ($coilNo || $coilNo == '0') {
                            $existing = ProcessOrder::where('plant_id', $plantId)
                                ->where('process_order', $processOrder)
                                ->where('coil_number', $coilNo)
                                ->first();

                            if ($existing) {
                                $set('poPlantError', null);
                                $set('coil_number', null);
                                $set('coilNumberError', "Duplicate Coil : '{$coilNo}' found!");
                            } else {
                                $set('poPlantError', null);
                                $set('coilNumberError', null);
                            }
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('coilNumberError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('coilNumberError') ? $get('coilNumberError') : null)
                    ->hintColor('danger')
                    ->required(),
                Forms\Components\TextInput::make('order_quantity')
                    ->label('Order Quantity')
                    ->required(),
                Forms\Components\TextInput::make('received_quantity')
                    ->label('Received Quantity')
                    ->default('0')
                    ->required(),
                Forms\Components\TextInput::make('sfg_number')
                    ->label('SFG Number')
                    ->reactive()
                    ->afterStateUpdated(function ($state, $set, callable $get, $livewire) {
                        $plantId = $get('plant_id');
                        $sfgNo = $get('sfg_number');
                        if (! $plantId) {
                            $set('poPlantError', 'Please select a plant first.');
                            $set('sfg_number', null);
                            $set('machine_name', null);
                            $set('sfgNumberError', null); // 'Please select a plant first.'
                        } elseif ($sfgNo) {
                            $existing = ProcessOrder::where('plant_id', $plantId)
                                ->where('sfg_number', $sfgNo)
                                ->first();

                            if ($existing) {
                                $set('poPlantError', null);
                                $set('sfg_number', null);
                                $set('machine_name', null);
                                $set('sfgNumberError', "Duplicate SFG : '{$sfgNo}' found!");
                            } else {
                                $set('poPlantError', null);
                                $set('sfgNumberError', null);
                            }
                        }
                    })
                    ->extraAttributes(fn ($get) => [
                        'class' => $get('sfgNumberError') ? 'border-red-500' : '',
                    ])
                    ->hint(fn ($get) => $get('sfgNumberError') ? $get('sfgNumberError') : null)
                    ->hintColor('danger'),
                Forms\Components\TextInput::make('machine_name')
                    ->label('Machine ID'),
                Forms\Components\FileUpload::make('attachment')
                    ->label('PDF Upload')
                    ->acceptedFileTypes(['application/pdf'])
                    ->storeFiles(false)
                    ->disk('local')
                    ->directory('uploads/temp')
                    ->preserveFilenames()
                    ->reactive(),
                Forms\Components\Actions::make([
                    Action::make('uploadNow')
                        ->label('Upload PDF Now')
                        ->action(function ($get, callable $set) {
                            $uploadedFiles = $get('attachment');

                            if (is_array($uploadedFiles) && count($uploadedFiles) > 0) {
                                $uploaded = reset($uploadedFiles);

                                if ($uploaded instanceof TemporaryUploadedFile) {
                                    $originalName = $uploaded->getClientOriginalName();
                                    $path = 'uploads/ProcessOrder/'.$originalName;

                                    // Check if file already exists
                                    if (Storage::disk('local')->exists($path)) {
                                        Notification::make()
                                            ->title('Duplicate File')
                                            ->body("The file '{$originalName}' already exists in uploads/ProcessOrder.")
                                            ->warning()
                                            ->send();

                                        return; // Stop here
                                    }

                                    $storedPath = $uploaded->storeAs(
                                        'uploads/ProcessOrder',
                                        $originalName,
                                        'local'
                                    );

                                    // $fullPath = storage_path('app/' . $storedPath);
                                    $fullPath = storage_path('app/'.$storedPath);

                                    // Parse PDF using smalot/pdfparser
                                    $parser = new Parser;
                                    $pdf = $parser->parseContent(file_get_contents($uploaded->getRealPath()));
                                    $text = $pdf->getText();

                                    // if (preg_match('/Batch ID:\s*(\d+)\s*--/i', $text, $matches))
                                    // {
                                    //     $batchId = $matches[1];
                                    // }
                                    if (preg_match('/Batch ID:\s*(\d+)(?:\s*--)?/i', $text, $matches)) {
                                        $batchId = $matches[1];
                                    } else {
                                        $batchId = null;
                                    }

                                    // Get the value of process_order field
                                    $processOrder = $get('process_order');

                                    if ($batchId != $processOrder) {
                                        Notification::make()
                                            ->title('Mismatch')
                                            ->body("Batch ID ($batchId) does not match Process Order ($processOrder)")
                                            ->danger()
                                            ->send();

                                        return;
                                    }

                                    if ($batchId == $processOrder) {
                                        // If batch matches, store the PDF permanently
                                        $storedPath = $uploaded->storeAs(
                                            'uploads/ProcessOrder',
                                            $originalName,
                                            'local'
                                        );

                                        Notification::make()
                                            ->title('Success')
                                            ->body("Batch ID matches Process Order: $batchId. PDF uploaded successfully.")
                                            ->success()
                                            ->send();

                                        return;
                                    }
                                }
                            } else {
                                Notification::make()
                                    ->title('No file selected to upload')
                                    ->warning()
                                    ->send();

                                return;
                            }
                        }),

                    Action::make('downloadAttachment')
                        ->label('Download PDF')
                        ->action(function ($get) {
                            $equipmentNumber = $get('process_order');

                            if (! $equipmentNumber) {
                                Notification::make()
                                    ->title('No process order entered')
                                    ->danger()
                                    ->send();

                                return;
                            }

                            $files = Storage::disk('local')->files('uploads/ProcessOrder');

                            $fileToDownload = null;
                            foreach ($files as $file) {
                                if (str_contains($file, $equipmentNumber)) {
                                    $fileToDownload = $file;
                                    break;
                                }
                            }

                            if (! $fileToDownload) {
                                Notification::make()
                                    ->title('PDF not found for this process order')
                                    ->danger()
                                    ->send();

                                return;
                            }

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

                    // Action::make('removeAttachment')
                    // ->label('Remove PDF')
                    // ->action(function ($get) {
                    //     $equipmentNumber = $get('process_order');

                    //     if (!$equipmentNumber) {
                    //         Notification::make()
                    //             ->title('No process order entered')
                    //             ->danger()
                    //             ->send();
                    //         return;
                    //     }

                    //       // Get all files from uploads/temp
                    //     $files = Storage::disk('local')->files('uploads/ProcessOrder');

                    //     $fileToDelete = null;
                    //     foreach ($files as $file) {
                    //         if (str_contains($file, $equipmentNumber)) {
                    //             $fileToDelete = $file;
                    //             break;
                    //         }
                    //     }

                    //     if (!$fileToDelete) {
                    //         Notification::make()
                    //             ->title('PDF not found for this process order')
                    //             ->danger()
                    //             ->send();
                    //         return;
                    //     }

                    //     // Delete the matched file
                    //     Storage::disk('local')->delete($fileToDelete);

                    //     Notification::make()
                    //         ->title('PDF removed successfully')
                    //         ->body("File for process order {$equipmentNumber} has been deleted.")
                    //         ->success()
                    //         ->send();
                    // }),
                ]),
                Forms\Components\Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Forms\Components\Hidden::make('updated_by')
                    ->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('plant.name')
                    ->label('Plant')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.code')
                    ->label('Item')
                    ->searchable()
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('item.description')
                    ->label('Description')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('process_order')
                    ->label('Process Order')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('coil_number')
                    ->label('Coil Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('order_quantity')
                    ->label('Order Quantity')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('received_quantity')
                    ->label('Received Quantity')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('sfg_number')
                    ->label('SFG Number')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('machine_name')
                    ->label('Machine ID')
                    ->alignCenter()
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Created At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_by')
                    ->label('Created By')
                    ->alignCenter()
                    ->sortable(),
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('Updated At')
                    ->alignCenter()
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('updated_by')
                    ->label('Updated By')
                    ->alignCenter()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                Tables\Columns\TextColumn::make('deleted_at')
                    ->label('Deleted At')
                    ->alignCenter()
                    ->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(),
                ]),
            ])
            ->headerActions([
                ImportAction::make()
                    ->label('Import Process Order')
                    ->color('warning')
                    ->importer(ProcessOrderImporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view import process order');
                    }),
                ExportAction::make()
                    ->label('Export Process Order')
                    ->color('warning')
                    ->exporter(ProcessOrderExporter::class)
                    ->visible(function () {
                        return Filament::auth()->user()->can('view export process order');
                    }),
            ]);
    }

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

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListProcessOrders::route('/'),
            'create' => Pages\CreateProcessOrder::route('/create'),
            'view' => Pages\ViewProcessOrder::route('/{record}'),
            'edit' => Pages\EditProcessOrder::route('/{record}/edit'),
        ];
    }

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