<?php

namespace App\Filament\Pages;

use App\Models\Item;
use App\Models\Plant;
use Filament\Pages\Page;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Concerns\InteractsWithForms;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Forms\Components\Actions\Action;
use Filament\Facades\Filament;
use Filament\Forms\Components\Actions;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Contracts\HasForms;
use Illuminate\Support\Facades\Auth;
use Smalot\PdfParser\Parser;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Storage;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use setasign\Fpdi\Fpdi;


class WebcamCapture extends Page implements HasForms
{

    use InteractsWithForms;

    use HasFiltersForm;
    protected static ?string $navigationIcon = 'heroicon-o-document-text';

    protected static ?string $navigationGroup = 'OCR Validations';

    protected static string $view = 'filament.pages.webcam-capture';

    public $photo;


    // public function filtersForm(Form $form): Form
    // {
    //     return $form
    //         ->statePath('filters')
    //         ->schema([
    //             FileUpload::make('photo')
    //             ->dehydrated(false)
    //             ->label('Capture from Webcam')
    //             ->disk('local')
    //             ->directory('uploads')
    //             ->preserveFilenames()
    //             ->image()
    //             ->helperText('You can take a picture from your webcam'),
    //             Actions::make([
    //                 Action::make('uploadNow')
    //                     ->label('Upload PDF Now')
    //                     ->action(function ($get, callable $set) {
    //                         $uploadedFiles = $get('photo');

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

    //                             if ($uploaded instanceof TemporaryUploadedFile) {
    //                                 $originalName = $uploaded->getClientOriginalName();
    //                                 $path = 'uploads/OCR/' . $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/OCR.")
    //                                         ->warning()
    //                                         ->send();
    //                                     return; // Stop here
    //                                 }

    //                                 $storedPath = $uploaded->storeAs(
    //                                     'uploads/OCR',
    //                                     $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();

    //                                 dd($text);


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

    //         ])
    //         ->columns(1);
    // }

    public function filtersForm(Form $form): Form
    {
        return $form
        ->statePath('filters')
        ->schema([
            Section::make('') // You can give your section a title or leave it blank
            ->schema([
                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();
                    })
                    ->required(),
                Select::make('item_id')
                    ->label('Item Code')
                    ->reactive()
                    ->searchable()
                    ->options(function (callable $get) {
                        if (!$get('plant_id')) {
                            return [];
                        }

                        return Item::where('plant_id', $get('plant_id'))
                            ->pluck('code', 'id')
                            ->toArray();
                    })
                    ->required(),
                TextInput::make('gr_number')
                    ->label('GR Number')
                    ->minLength(7)
                    ->required(),
                     Actions::make([
                        // Action::make('uploadNow1')
                        // ->label('Upload OCR')
                        // ->action(function ($get, callable $set) {
                        //      $uploadedFiles = $get('photo');
                        //         // $serialNumbers = [
                        //         //     $get('serial_1'),
                        //         //     $get('serial_2'),
                        //         //     $get('serial_3'),
                        //         //     $get('serial_4'),
                        //         // ];

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

                        //         if ($uploaded instanceof TemporaryUploadedFile) {
                        //             $grNumber = $get('gr_number');
                        //             $safeName = preg_replace('/[^A-Za-z0-9_\-]/', '_', $grNumber);
                        //             // $originalName = $uploaded->getClientOriginalName();
                        //             // $path = 'uploads/GRNumber/' . $originalName;
                        //             $finalFileName = $safeName . '.jpg';
                        //             $finalPath = 'uploads/OCR/' . $finalFileName;

                        //             $storedPath = $uploaded->storeAs(
                        //                 'uploads/OCR',
                        //                 $finalFileName,
                        //                 'local'
                        //             );

                        //             // $storedPath = $uploaded->storeAs('uploads/OCR', $finalFileName, 'local');
                        //             // $fullPath = storage_path('app/' . $storedPath);
                        //             $storedPath = $uploaded->storeAs('uploads/OCR', $finalFileName, 'local');

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

                        //             $text = (new TesseractOCR($fullPath))->lang('eng')->run();

                        //             $rawText = $text;

                        //             preg_match_all('/\d+/', $rawText, $matches);

                        //             $serialNumbers = $matches[0];

                        //             $serialNumbers = array_slice($serialNumbers, 0, 4);

                        //             //dd($serialNumbers);

                        //             $processOrder = $get('gr_number');

                        //             $itemId = $get('item_id');

                        //             $plant = $get('plant_id');

                        //             $item = Item::find($itemId);

                        //             $plant = Plant::find($plant);

                        //             $templatePath = storage_path('app/private/uploads/StickerTemplateOcr/multi.pdf');

                        //             $outputPath = storage_path('app/private/uploads/StickerTemplateOcr/multi_filled.pdf');

                        //             $storedPath = $uploaded->storeAs(
                        //                 'uploads/GRNumber',
                        //                 $finalFileName,
                        //                 'local'
                        //             );

                        //             $pdf = new Fpdi('P', 'mm', [90, 90]);

                        //             $templateId = $pdf->setSourceFile($templatePath);
                        //             $templatePage = $pdf->importPage(1);

                        //             $pdf->AddPage();
                        //             $pdf->useTemplate($templatePage, 0, 0, 90, 90);

                        //             $pdf->SetFont('Helvetica', '', 10);
                        //             $pdf->SetTextColor(0, 0, 0);

                        //             $slots = [
                        //                 ['x' => 5.7,  'y' => 41.9, 'w' => 46.5, 'h' => 3.5],  // 1st serial
                        //                 ['x' => 50, 'y' => 41.5, 'w' => 46.6, 'h' => 3.9],  // 2nd serial
                        //                 ['x' => 5.7,  'y' => 60, 'w' => 46.5, 'h' => 3.5],  // 3rd serial
                        //                 ['x' => 50, 'y' => 60, 'w' => 46.6, 'h' => 3.5],  // 4rd serial
                        //             ];

                        //             $qrSlots = [
                        //                 ['x' => 17.3,  'y' => 29.2, 'size' => 11.4],
                        //                 ['x' => 61.5,   'y' => 29, 'size' => 11.5],
                        //                 ['x' => 17.7,  'y' => 46.7, 'size' => 11.4],
                        //                 ['x' => 61.7,   'y' => 46.7, 'size' => 11.4],
                        //             ];

                        //            foreach ($serialNumbers as $i => $serial) {
                        //                 if (!isset($slots[$i]) || !isset($qrSlots[$i])) continue;

                        //                 // Erase old QR completely (slightly larger)
                        //                 $pdf->SetFillColor(255, 255, 255);
                        //                 $pdf->Rect($qrSlots[$i]['x']-1, $qrSlots[$i]['y']-1, $qrSlots[$i]['size']+2, $qrSlots[$i]['size']+2, 'F');

                        //                 // Generate new QR code
                        //                 $qrPath = storage_path("app/private/uploads/QR/qr_$serial.png");
                        //                 $qrDir = storage_path('app/private/uploads/QR');
                        //                 if (!file_exists($qrDir)) mkdir($qrDir, 0777, true);
                        //                 QrCode::format('png')->size(100)->generate($serial, $qrPath);

                        //                 // Place QR code
                        //                 $pdf->Image($qrPath, $qrSlots[$i]['x'], $qrSlots[$i]['y'], $qrSlots[$i]['size'], $qrSlots[$i]['size']);

                        //                 // Erase old serial
                        //                 $pdf->SetFillColor(255, 255, 255);
                        //                 $pdf->Rect($slots[$i]['x'], $slots[$i]['y'], $slots[$i]['w'], $slots[$i]['h'], 'F');

                        //                 // Write new serial
                        //                 $pdf->SetXY($slots[$i]['x'], $slots[$i]['y']);
                        //                 $pdf->Cell($slots[$i]['w'], $slots[$i]['h'], $serial, 0, 0, 'L');
                        //             }

                        //             // Save the final PDF
                        //             $pdf->Output('F', $outputPath);

                        //             // Download
                        //             return response()->download($outputPath);
                        //         }
                        //     }
                        //     else
                        //     {
                        //         Notification::make()
                        //             ->title('No file selected to upload')
                        //             ->warning()
                        //             ->send();
                        //             return;
                        //     }
                        // }),

                         Action::make('uploadNow1')
                        ->label('Upload OCR')
                        ->action(function ($get, callable $set) {

                            // $serialNumbers = [
                            //     $get('serial_1'),
                            //     $get('serial_2'),
                            //     $get('serial_3'),
                            //     $get('serial_4'),
                            // ];

                            // $hasSerial = collect($serialNumbers)->some(fn($s) => !empty($s));
                            $serialNumbersJson = $get('serialNumbers'); // input name matches hidden input
                            $serialNumbers = json_decode($serialNumbersJson, true) ?? [];

                            if (empty($serialNumbers)) {
                                Notification::make()
                                    ->title('Serial numbers cannot be empty!')
                                    ->danger()
                                    ->send();
                                return;
                            }

                            // Now you can proceed with your PDF logic
                            //$serialNumbers = array_slice($serialNumbers, 0, 4);

                                $serialNumbers = array_slice($serialNumbers, 0, 4);

                                //dd($serialNumbers);

                                $itemId = $get('item_id');

                                $plant = $get('plant_id');

                                $item = Item::find($itemId);

                                $plant = Plant::find($plant);

                                $templatePath = storage_path('app/private/uploads/StickerTemplateOcr/multi.pdf');

                                $outputPath = storage_path('app/private/uploads/StickerTemplateOcr/multi_filled.pdf');

                                // $storedPath = $uploaded->storeAs(
                                //     'uploads/GRNumber',
                                //     $finalFileName,
                                //     'local'
                                // );

                                $pdf = new Fpdi('P', 'mm', [90, 90]);

                                $templateId = $pdf->setSourceFile($templatePath);
                                $templatePage = $pdf->importPage(1);

                                $pdf->AddPage();
                                $pdf->useTemplate($templatePage, 0, 0, 90, 90);

                                $pdf->SetFont('Helvetica', '', 10);
                                $pdf->SetTextColor(0, 0, 0);

                                $slots = [
                                    ['x' => 5.7,  'y' => 41.9, 'w' => 46.5, 'h' => 3.5],  // 1st serial
                                    ['x' => 50, 'y' => 41.5, 'w' => 46.6, 'h' => 3.9],  // 2nd serial
                                    ['x' => 5.7,  'y' => 60, 'w' => 46.5, 'h' => 3.5],  // 3rd serial
                                    ['x' => 50, 'y' => 60, 'w' => 46.6, 'h' => 3.5],  // 4rd serial
                                ];

                                $qrSlots = [
                                    ['x' => 17.3,  'y' => 29.2, 'size' => 11.4],
                                    ['x' => 61.5,   'y' => 29, 'size' => 11.5],
                                    ['x' => 17.7,  'y' => 46.7, 'size' => 11.4],
                                    ['x' => 61.7,   'y' => 46.7, 'size' => 11.4],
                                ];

                                foreach ($serialNumbers as $i => $serial) {
                                    if (!isset($slots[$i]) || !isset($qrSlots[$i])) continue;

                                    // Erase old QR completely (slightly larger)
                                    $pdf->SetFillColor(255, 255, 255);
                                    $pdf->Rect($qrSlots[$i]['x']-1, $qrSlots[$i]['y']-1, $qrSlots[$i]['size']+2, $qrSlots[$i]['size']+2, 'F');

                                    // Generate new QR code
                                    $qrPath = storage_path("app/private/uploads/QR/qr_$serial.png");
                                    $qrDir = storage_path('app/private/uploads/QR');
                                    if (!file_exists($qrDir)) mkdir($qrDir, 0777, true);
                                    QrCode::format('png')->size(100)->generate($serial, $qrPath);

                                    // Place QR code
                                    $pdf->Image($qrPath, $qrSlots[$i]['x'], $qrSlots[$i]['y'], $qrSlots[$i]['size'], $qrSlots[$i]['size']);

                                    // Erase old serial
                                    $pdf->SetFillColor(255, 255, 255);
                                    $pdf->Rect($slots[$i]['x'], $slots[$i]['y'], $slots[$i]['w'], $slots[$i]['h'], 'F');

                                    // Write new serial
                                    $pdf->SetXY($slots[$i]['x'], $slots[$i]['y']);
                                    $pdf->Cell($slots[$i]['w'], $slots[$i]['h'], $serial, 0, 0, 'L');
                                }

                                // Save the final PDF
                                $pdf->Output('F', $outputPath);

                                // Download
                                return response()->download($outputPath);

                        }),


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

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

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

                            $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));
                        }),
                    ]),
                Field::make('camera_capture')
                    ->view('fields.web-camera-capture'),
                Hidden::make('created_by')
                    ->label('Created By')
                    ->default(Filament::auth()->user()?->name),
                Hidden::make('updated_by')
                    ->default(Filament::auth()->user()?->name),

                ])->columns(1),
            ]);
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('create web capture page');
    }
}
