<?php

namespace App\Livewire;

use App\Models\AlertMailRule;
use App\Models\Item;
use App\Models\Line;
use App\Models\PanelBoxValidation;
use App\Models\Plant;
use App\Models\ProductCharacteristicsMaster;
use App\Models\ProductionCharacteristic;
use Filament\Facades\Filament;
use Livewire\Component;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Mail;
use App\Mail\InvalidQualityMail;

class PanelCheckList extends Component
{

public $records = [];

    public $existingRecords = [];

    // public bool $shouldSkipChecklist = false;

    public array $checklist = [];

    public $showChecklist = false;

    // public $skipChecklistValidation = false;

    // protected $listeners = ['focus-item-id' => 'handleFocus', 'trigger-create' => 'doCreate',];

    public $data =
    [
        'item_id' => '',
        'plant_id' => '',
    ];

    public $data1 = [
        'checklist' => [],
    ];

    // public function doCreate()
    // {
    //     $this->create();

    //     $this->shouldSkipChecklist = false;
    // }

    public function mount($records = [])
    {
        // $this->records = collect($records);
        $this->records = $records;

        // foreach ($records as $record) {
        //     $this->checklist[$record['id']] = 'ok';
        // }
    }

    public function cancel()
    {
        $this->dispatch('checklist-cancelled');
    }

    public function saveChecklist()
    {
        if (empty($this->checklist) || count($this->checklist) != count($this->records)) {
            Notification::make()
                ->title('Incomplete Checklist')
                ->body('Please complete all checklist fields before submitting.')
                ->danger()
                ->send();
            return;
        }

        $item = Item::where('code', $this->data['item_id'])->first();

        if (! $item) {
            Notification::make()
                ->title('Invalid Item Code')
                ->body('Item not found for given code.')
                ->danger()
                ->send();
            return;
        }

        $itemAgaPlant = Item::where('code', $this->data['item_id'])->where('plant_id', $this->data['plant_id'])->first();

        $plant = Plant::find($this->data['plant_id']);

        if (! $itemAgaPlant) {
            Notification::make()
                ->title('Invalid Item Code')
                ->body("Item code '$this->data['item_id']' not found for given plant code '{$plant?->code}'.")
                ->danger()
                ->send();
            return;
        }

        $itemId = $itemAgaPlant->id;

        $exists = PanelBoxValidation::where('plant_id', $this->data['plant_id'] ?? null)
            ->where('serial_number', $this->data['serial_number'] ?? null)
            ->first();

        $plan = Plant::find($this->data['plant_id']);

        if ($exists) {
            Notification::make()
                ->title('Duplicate Serial Number')
                ->body("serial number {$this->data['serial_number']} already exists for the selected plant $plan->code.")
                ->danger()
                ->send();
            return;
        }

        $qualityValidation = PanelBoxValidation::create([
            'plant_id' => $this->data['plant_id'] ?? null,
            'line_id'  => $this->data['line_id'] ?? null,
            'sticker_master_id'  => $this->data['sticker_master_id'] ?? null,
            'production_order'  => $this->data['production_order'] ?? null,
            'serial_number'  => $this->data['serial_number'] ?? null,
            'serial_number_panel'  => $this->data['serial_number_panel'] ?? null,
            'pack_slip_panel'  => $this->data['pack_slip_panel'] ?? null,
            'name_plate_panel'  => $this->data['name_plate_panel'] ?? null,
            'tube_sticker_panel'  => $this->data['tube_sticker_panel'] ?? null,
            'warranty_card_panel'  => $this->data['warranty_card_panel'] ?? null,
            'part_validation1'  => $this->data['part_validation1'] ?? null,
            'part_validation2'  => $this->data['part_validation2'] ?? null,
            'part_validation3'  => $this->data['part_validation3'] ?? null,
            'part_validation4'  => $this->data['part_validation4'] ?? null,
            'part_validation5'  => $this->data['part_validation5'] ?? null,
            'panel_box_supplier'  => $this->data['panel_box_supplier'] ?? null,
            'panel_box_serial_number'  => $this->data['panel_box_serial_number'] ?? null,
            'panel_box_code'  => $this->data['panel_box_code'] ?? null,
            'created_by'  => $this->data['created_by'] ?? null,
        ]);

        if (! $qualityValidation || ! $qualityValidation->exists) {
            Notification::make()
                ->title('Failed to save Panel Box Validation')
                ->body('Something went wrong while inserting data.')
                ->danger()
                ->send();

            return;
        }

        foreach ($this->checklist as $characteristicId => $value) {

            // $status = 'Ok';

            $characteristic = ProductCharacteristicsMaster::find($characteristicId);

            $itemCharacteristic = ProductCharacteristicsMaster::where('plant_id', $this->data['plant_id'])
                ->where('line_id', $this->data['line_id'])
                ->where('name', $characteristic->name)
                ->where('item_id', $itemId)
                ->first();

            // if (($characteristic?->inspection_type ?? null) === 'Value') {
            //     if ($characteristic && is_numeric($value) && (($value >= $characteristic->lower && $value <= $characteristic->upper) || $value == $characteristic->lower || $value == $characteristic->upper)
            //     ) {
            //         $status = 'Ok';
            //     } else {
            //         $status = 'NotOk';
            //     }
            // }
            // else {
            //     $status = $value;
            // }

            if (($itemCharacteristic?->inspection_type ?? null) === 'Value') {

                if ($itemCharacteristic && is_numeric($value) && $value >= $itemCharacteristic->lower && $value <= $itemCharacteristic->upper
                ) {
                    $status = 'Ok';
                } else {
                    $status = 'NotOk';
                }
            }
            else {
                $status = $value;
            }

            $prod = ProductionCharacteristic::create([
                'plant_id' => $this->data['plant_id'] ?? null,
                'item_id'  => $itemId ?? null,
                'line_id'  => $this->data['line_id'] ?? null,
                'machine_id'  => $characteristic?->machine_id ?? null,
                'production_order'  => $this->data['production_order'] ?? null,
                'serial_number'  => $this->data['serial_number'] ?? null,
                'characteristic_name' => $characteristic?->name ?? null,
                'observed_value'  => $value ?? null,
                'status' => $status,
                'inspection_status'  => $finalInspectionStatus ?? null,
                'created_by'  => $this->data['created_by'] ?? null,
                'updated_by'  => $this->data['updated_by'] ?? null,
            ]);
        }

        if (! $prod) {
            Notification::make()
                ->title('Failed to save Panel Box Validation')
                ->body('Something went wrong while inserting data.')
                ->danger()
                ->send();
            return;
        }

        $this->showChecklist = false;

        $this->dispatch('checklist-saved');
    }

    public function canSaveChecklist(): bool
    {
        if (empty($this->checklist) || count($this->checklist) != count($this->records)) {
            return false;
        }

        foreach ($this->checklist as $characteristicId => $value) {

            if ($value == null || $value == '') {
                return false;
            }

            $characteristic = ProductCharacteristicsMaster::find($characteristicId);

            if (! $characteristic || ! is_numeric($value) || ($value < $characteristic->lower || $value > $characteristic->upper)) {
                return false;
            }
        }
        return true;
    }

    public function getCharacteristicStatus($characteristicId): ?string
    {
        $value = $this->checklist[$characteristicId] ?? null;

        if ($value == null || $value == '') {
            return null;
        }

        $characteristic = ProductCharacteristicsMaster::find($characteristicId);

        $itemCode = $this->data['item_id'];

        $itemId = Item::where('plant_id', $characteristic->plant_id)->where('code', $itemCode)->value('id');

        $characteristic = ProductCharacteristicsMaster::find($characteristicId);

        $limit = ProductCharacteristicsMaster::where('plant_id', $characteristic->plant_id)
            ->where('line_id', $characteristic->line_id)
            ->where('name', $characteristic->name)
            ->where('item_id', $itemId)
            ->first();

        if (! $characteristic || ! is_numeric($value)) {
            return 'Not Ok';
        }
        // return ($value >= $characteristic->lower && $value <= $characteristic->upper) ? 'Ok' : 'Not Ok';

        return ($value >= $limit->lower && $value <= $limit->upper) ? 'Ok' : 'Not Ok';

    }

    // public static function getMailData($plantId)
    // {
    //     $globalEmails = AlertMailRule::where('plant', 0)
    //         ->where('module', 'QualityValidation')
    //         ->where('rule_name', 'QualityMail')
    //         ->where(fn ($q) => $q->whereNull('schedule_type')->orWhere('schedule_type', ''))
    //         ->pluck('email')
    //         ->toArray();

    //     if (! empty($globalEmails)) {
    //         return [
    //             'plant_id' => 0,
    //             'plant_name' => 'All Plants',
    //             'emails' => $globalEmails,
    //         ];
    //     }

    //     $mPlantName = Plant::where('id', $plantId)->value('name');

    //     $emails = AlertMailRule::where('plant', $plantId)
    //         ->where('module', 'QualityValidation')
    //         ->where('rule_name', 'QualityMail')
    //         ->where(fn ($q) => $q->whereNull('schedule_type')->orWhere('schedule_type', ''))
    //         ->pluck('email')
    //         ->toArray();

    //     return [
    //         'plant_id' => $plantId,
    //         'plant_name' => $mPlantName,
    //         'emails' => $emails,
    //     ];
    // }

    public function render()
    {
        return view('livewire.panel-check-list');
    }
}
