<?php

namespace App\Components;

use App\Facades\PrintQueue;
use App\Interface\DocumentOwner;
use App\Interface\HistoryOwner;
use App\Models\Document\Document;
use App\Models\Document\DocumentType;
use App\Services\HistoryService;
use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Ramsey\Uuid\Uuid;

class DocumentManager extends Component {
    use WithFileUploads, WithPagination;

    public DocumentOwner $owner;

    public bool $openAD = false;

    public $document_type_id;
    public $display_name;
    public $doc;

    public $filterType = '';

    public function openAddDoc() {
        $this->openAD = true;
    }

    public function closeAddDoc() {
        $this->openAD = false;
    }

    public function deleteDocument(HistoryService $history, $id) {
        $document = Document::find($id);

        if ($document) {
            $name = $document->display_name;
            $document->delete();

            $history->add($this->resolveHistoryOwner(), "Document deleted: {$name}", [
                'document_id' => $id,
                'display_name' => $name,
            ]);
        }
    }

    public function save(HistoryService $history) {
        $validated = $this->validate([
            'display_name' => 'required|string|max:255',
            'doc' => 'required|file|mimes:pdf,doc,docx,jpg,png,mp3|max:20480',
            'document_type_id' => 'required|integer|exists:document_types,id'
        ]);

        $originalName = $this->doc->getClientOriginalName();

        $path = $this->doc->storeAs(
            path: $this->owner->getDocumentStoragePath(),
            name: $originalName,
            options: 'public'
        );

        $document = $this->owner->documents()->create([
            'display_name' => $validated['display_name'],
            'file_name' => $originalName,
            'file_type' => $this->doc->getMimeType(),
            'file_size' => $this->doc->getSize(),
            'type_id' => $validated['document_type_id'],
            'user_id' => auth()->id()
        ]);

        if($validated['document_type_id'] == 4) {
            $this->owner?->claim?->keyDates()->syncWithoutDetaching([
                23 => ['date' => date('Y-m-d')],
                24 => ['date' => date('Y-m-d', strtotime('+14 day'))],
            ]);
        }

        $history->add($this->resolveHistoryOwner(), "Document uploaded: {$validated['display_name']}", [
            'document_id' => $document->id,
            'file_name' => $originalName,
            'mime_type' => $this->doc->getMimeType(),
        ]);

        $this->reset('doc', 'display_name', 'document_type_id');

        $this->closeAddDoc();
    }

    private function resolveHistoryOwner(): HistoryOwner {
        if ($this->owner instanceof \App\Models\Claim\Claim) {
            return $this->owner->client;
        }
        if ($this->owner instanceof \App\Models\Dsar\Dsar) {
            return $this->owner->claim->client;
        }
        return $this->owner;
    }

    public function print($id) {
        PrintQueue::add(Document::find($id));
        $this->dispatch('toast', message: "Sent document to print queue.", type: 'success');
    }

    public function render() {

        $query = $this->owner->documents();

        if ($this->filterType) {
            $query->where('type_id', $this->filterType);
        }

        return view('components.document-manager', [
            'docs' => $query->latest()->paginate(10),
            'types' => DocumentType::all(),
            'docTypes' => DocumentType::pluck('display_name', 'id')->toArray(),
        ]);
    }
}