<?php

namespace App\Livewire\Machines;

use App\DTO\MachineDTO;
use App\Models\FingerprintMachine;
use App\Services\FingerprintMachineService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

use App\Traits\WithToastNotifications;
use Illuminate\Validation\Rule;

class MachineIndex extends Component
{
    use AuthorizesRequests, WithToastNotifications;

    // Modals state
    public bool $showFormModal = false;

    public bool $showDeleteModal = false;
    public bool $showHelpModal = false;

    // Form fields for Add/Edit
    public ?int $editingMachineId = null;
    public string $name = '';
    public string $machine_number = '1';
    public string $cloud_id = '';
    public string $personnel_target = 'both';



    // Delete fields
    public ?int $deletingMachineId = null;
    public string $deletingMachineName = '';

    // Removed Ngrok Connection Settings

    protected function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'machine_number' => ['nullable', 'string', 'max:20'],
            'cloud_id' => ['nullable', 'string', 'max:100'],
            'personnel_target' => ['required', 'in:guru,siswa,both'],
        ];
    }

    protected function messages(): array
    {
        return [
            'name.required' => 'Nama mesin wajib diisi.',
            'personnel_target.required' => 'Target personel wajib dipilih.',
        ];
    }

    public function create(): void
    {
        $this->authorize('create', FingerprintMachine::class);
        $this->resetForm();
        $this->showFormModal = true;
    }

    public function edit(int $id, FingerprintMachineService $machineService): void
    {
        $machine = FingerprintMachine::findOrFail($id);
        $this->authorize('update', $machine);

        $this->editingMachineId = $machine->id;
        $this->name = $machine->name;
        $this->machine_number = $machine->machine_number ?? '1';
        $this->cloud_id = $machine->cloud_id ?? '';
        $this->personnel_target = $machine->personnel_target?->value ?? 'both';

        $this->showFormModal = true;
    }

    public function save(FingerprintMachineService $machineService): void
    {
        $this->validate();

        // Build DTO — secrets are only included if a new non-empty value was submitted
        // For edits, blank fields mean "keep the existing stored value" (no overwrite)
        $dtoData = [
            'name' => $this->name,
            'machine_number' => $this->machine_number,
            'cloud_id' => $this->cloud_id,
            'personnel_target' => $this->personnel_target,
            'status' => 'offline',
        ];

        $machineDTO = MachineDTO::fromArray($dtoData);

        if ($this->editingMachineId) {
            $machine = FingerprintMachine::findOrFail($this->editingMachineId);
            $this->authorize('update', $machine);

            $updateData = $machineDTO->toArray(); 
            $machine->update($updateData);

            // Audit log only — do not call machineService->updateMachine() which would
            // call repository->update($machineDTO) and overwrite secrets with null
            $user = \Illuminate\Support\Facades\Auth::user();
            app(\App\Contracts\AuditLogServiceInterface::class)->log(
                $user,
                'MACHINE_UPDATED',
                "Memperbarui konfigurasi mesin: {$machine->name} (No: {$machine->machine_number})"
            );

            $this->notifySuccess('Pengaturan mesin fingerprint berhasil diperbarui.');
        } else {
            $this->authorize('create', FingerprintMachine::class);
            $machineService->createMachine($machineDTO);
            $this->notifySuccess('Mesin fingerprint baru berhasil ditambahkan.');
        }

        $this->closeModal();
    }




    public function confirmDelete(int $id): void
    {
        $machine = FingerprintMachine::findOrFail($id);
        $this->authorize('delete', $machine);

        $this->deletingMachineId = $machine->id;
        $this->deletingMachineName = $machine->name;
        $this->showDeleteModal = true;
    }

    public function deleteMachineDirect(int $id, FingerprintMachineService $machineService): void
    {
        $machine = FingerprintMachine::findOrFail($id);
        $this->authorize('delete', $machine);

        $machineService->deleteMachine($id);
        $this->notifySuccess("Mesin {$machine->name} berhasil dihapus.");

        $this->showDeleteModal = false;
        $this->deletingMachineId = null;
    }

    public function delete(FingerprintMachineService $machineService): void
    {
        if ($this->deletingMachineId) {
            $machine = FingerprintMachine::findOrFail($this->deletingMachineId);
            $this->authorize('delete', $machine);

            $machineService->deleteMachine($this->deletingMachineId);
            $this->notifySuccess('Mesin fingerprint berhasil dihapus.');
        }

        $this->showDeleteModal = false;
        $this->deletingMachineId = null;
    }

    public function openHelpModal(): void
    {
        $this->showHelpModal = true;
    }

    public function closeModal(): void
    {
        $this->showFormModal = false;

        $this->showDeleteModal = false;
        $this->showHelpModal = false;
        $this->resetForm();
    }

    private function resetForm(): void
    {
        $this->editingMachineId = null;
        $this->name = '';
        $this->machine_number = '1';
        $this->cloud_id = '';
        $this->personnel_target = 'both';
        $this->resetValidation();
    }

    public function render(FingerprintMachineService $machineService)
    {
        $this->authorize('viewAny', FingerprintMachine::class);

        $machines = $machineService->getAllMachines();

        return view('livewire.machines.machine-index', [
            'machines' => $machines,
        ])->layout('components.layouts.app');
    }
}
