<?php

namespace App\Filament\Pages;

use App\Models\Item;
use App\Models\ItemCharacteristic;
use App\Models\Plant;
use App\Models\StickerDetail;
use App\Models\StickerStructureDetail;
use App\Services\StickerPdfService;
use Filament\Facades\Filament;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\ViewField;
use Filament\Forms\Form;
use Filament\Forms\Get;
use Filament\Notifications\Notification;
use Filament\Pages\Dashboard\Concerns\HasFiltersForm;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Auth;

class StickerStructurePreviewPage extends Page
{
    use HasFiltersForm;

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

    protected static string $view = 'filament.pages.sticker-structure-preview-page';

    protected static ?string $navigationGroup = 'Customized Sticker Printing';

    public $stickerId;

    public $plantId;

    public $itemId;

    public ?string $pdfPreview = null;

    // public array $filters = [];

    public function mount(): void
    {
        session()->forget(['stick_id', 'selected_plant', 'selected_item']);
        $this->form->fill([
            'sticker_id' => null,
            'plant' => null,
            'item' => null,
        ]);
    }

    public function form(Form $form): Form
    {
        return $form
            ->statePath('filters') // Store form state in 'filters'
            ->schema([
                Section::make('')
                    ->schema([
                        Select::make('sticker_id')
                            ->label('Sticker ID')
                            ->nullable()
                            ->options(function (callable $get) {

                                return StickerStructureDetail::orderByDesc('id')->pluck('sticker_id', 'sticker_id')->toArray();
                            })
                            ->afterStateUpdated(callback: function ($state, callable $set) {
                                session(['stick_id' => $state]);
                                $set('plant', null);
                                $set('item', null);
                                $this->pdfPreview = null;
                            })
                            ->searchable()
                            ->reactive()
                            ->required(),
                        Select::make('plant')
                            ->label('Select Plant')
                            ->reactive()
                             // ->options(Plant::pluck('name', 'id'))
                            ->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, callable $set) {
                                session(['stick_id' => $state]);
                                session(['selected_plant' => $state]);
                                $set('item', null);
                                session()->forget('item');
                                $this->pdfPreview = null;
                            }),
                        Select::make('item')
                            ->label('Search by Item Code')
                            ->nullable()
                            ->options(function (callable $get) {
                                $plant = $get('plant');

                                return $plant ? ItemCharacteristic::where('plant_id', $plant)->with('item')->get()->pluck('item.code', 'id')->toArray() : []; // ->orderBy('plant_id')
                            })
                            ->afterStateUpdated(function ($state, callable $set) {
                                session(['stick_id' => $state]);
                                session(['selected_plant' => $state]);
                                session(['selected_item' => $state]);
                                $this->pdfPreview = null;
                                // $set('item_id', null);
                                // session()->forget('item');
                            })
                            ->searchable()
                            ->reactive(),
                        // ViewField::make('generate_template')
                        //     ->view('fields.generate-template-preview')
                        //     ->reactive()
                        //     // ->key(fn ($get) => 'generate-template' . ($get('sticker_id_live') ?? 'empty'))
                        //     ->key(fn (Get $get) => 'generate-template-'.
                        //         ($get('sticker_id') ?? 'empty').'-'.
                        //         ($get('plant') ?? 'empty').'-'.
                        //         ($get('item_characteristic_id') ?? 'empty')
                        //     )
                        //     // ->viewData(fn (Get $get) => [
                        //     //     'sticker_id' => $get('sticker_id_live') ?? 'empty',
                        //     // ]),
                        //     ->viewData(fn (Get $get) => [
                        //         'sticker_id' => $get('sticker_id') ?? 'empty',
                        //         'plant_id' => $get('plant') ?? 'empty',
                        //         'item_characteristic_id' => $get('item') ?? 'empty',
                        //     ])
                        //     ->hidden(fn (callable $get) => ($get('sticker_id') == null || $get('sticker_id') == '0' || empty($get('sticker_id'))) || (($get('plant') != null || $get('plant') != '') &&
                        //      ($get('item') == null || $get('item') == '' || empty($get('item'))))),
                    ])
                    ->columns(3),
            ]);
    }

    public function showPreview()
    {
        $state = $this->form->getState();
        $stickerId = trim($state['sticker_id'] ?? '') ?: null;
        // $stickerId = $this->form->getState()['sticker_id'];
        // $stickerId = trim($stickerId) ?? null;
        $this->stickerId = $stickerId;

        $plantId = trim($state['plant'] ?? '') ?: null;
        // $plantId = $this->form->getState()['plant'];
        // $plantId = trim($plantId) ?? null;
        $this->plantId = $plantId;

        $itemId = trim($state['item'] ?? '') ?: null;
        // $itemId = $this->form->getState()['item'];
        // $itemId = trim($itemId) ?? null;
        $this->itemId = $itemId;

        $this->pdfPreview = null;

        // $operatorName = Filament::auth()->user()->name;

        if (! $stickerId) {
            Notification::make()->title('Please select a Sticker ID first!')->danger()->duration(2000)->send();

            $this->form->fill([
                'sticker_id' => $stickerId ?? null,
                'plant' => $plantId ?? null,
                'item' => $itemId ?? null,
            ]);

            return;
        } elseif ($plantId && ! $itemId) {
            Notification::make()->title('Please select an Item Code!')->danger()->duration(2000)->send();

            $this->form->fill([
                'sticker_id' => $stickerId,
                'plant' => $plantId ?? null,
                'item' => $itemId ?? null,
            ]);

            return;
        } elseif ($stickerId && $plantId && $itemId != null && $itemId != '') {

            $itemCharacteristic = $itemId ? ItemCharacteristic::find($itemId) : null;

            $structure = StickerStructureDetail::where('sticker_id', $stickerId)->first();
            if (! $structure) {
                Notification::make()->title('Sticker structure not found!')->danger()->send();

                return;
            }

            $dynamicElements = StickerDetail::where('sticker_structure_detail_id', $structure->id)->get();

            try {
                $stickerPdfService = new StickerPdfService;
                $this->pdfPreview = $stickerPdfService->generateStickerItem($stickerId, $dynamicElements, $itemCharacteristic);

                Notification::make()
                    ->title('Sticker Preview Generated!')
                    ->success()
                    ->duration(2000)
                    ->send();
            } catch (\Exception $e) {
                Notification::make()
                    ->title('Error generating sticker preview!')
                    ->body($e->getMessage())
                    ->danger()
                    ->send();
            }
        } else {
            $elements = StickerStructureDetail::where('sticker_id', $stickerId)->first();

            try {
                $stickerPdfService = new StickerPdfService;
                $this->pdfPreview = $stickerPdfService->generateSticker($stickerId, $elements->toArray());

                Notification::make()
                    ->title('Sticker Preview Generated!')
                    ->success()
                    ->duration(2000)
                    ->send();
            } catch (\Exception $e) {
                Notification::make()
                    ->title('Error generating sticker preview!')
                    ->body($e->getMessage())
                    ->danger()
                    ->send();
            }
        }
    }

    public static function getNavigationLabel(): string
    {
        return 'Sticker Structure Preview';
    }

    public function getHeading(): string
    {
        return 'Sticker Structure Preview';
    }

    public static function canAccess(): bool
    {
        return Auth::check() && Auth::user()->can('view sticker structure preview');
    }
}
