<?php

namespace App\Livewire\Documents;

use App\Domain\Document\DocumentSettings;
use App\Domain\Document\Enums\DocumentType;
use App\Domain\Document\Services\DocumentService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Shared\Models\SystemSetting;
use Illuminate\Database\Eloquent\Model;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;

#[Layout('layouts.app')]
#[Title('رفع مستند')]
class DocumentUploadWizard extends Component
{
    use WithFileUploads;

    public int $currentStep = 1;
    public int $totalSteps = 4;
    public bool $completed = false;

    public string $documentableType = '';
    public int $documentableId = 0;
    public string $documentableLabel = '';

    public string $documentType = '';
    public $file = null;
    public string $notes = '';

    public ?array $createdDocument = null;

    public function mount(string $documentableType, int $documentableId): void
    {
        $this->authorize('documents.upload');

        $this->documentableType = $documentableType;
        $this->documentableId = $documentableId;

        $model = $this->resolveDocumentable();
        abort_unless($model, 404);

        $this->documentableLabel = $model->name_ar ?? $model->name ?? "#{$model->id}";
    }

    public function nextStep(): void
    {
        $this->validate($this->rulesForStep($this->currentStep));
        $this->currentStep = min($this->currentStep + 1, $this->totalSteps);
    }

    public function previousStep(): void
    {
        $this->currentStep = max($this->currentStep - 1, 1);
    }

    public function goToStep(int $step): void
    {
        if ($step < $this->currentStep) {
            $this->currentStep = $step;
        }
    }

    public function confirm(DocumentService $service): void
    {
        try {
            $model = $this->resolveDocumentable();
            abort_unless($model, 404);

            $type = DocumentType::from($this->documentType);

            $document = $service->upload(
                $model,
                $this->file,
                $type,
                $this->notes ?: null,
                auth()->user()
            );

            $this->createdDocument = [
                'uuid' => $document->uuid,
                'type_label' => $type->label(),
                'status_label' => $document->status->label(),
                'original_filename' => $document->original_filename,
            ];

            $this->completed = true;
            $this->currentStep = $this->totalSteps;
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.documents.document-upload-wizard', [
            'allowedTypes' => app(DocumentService::class)->getAllowedTypes(),
            'maxSizeMb' => (int) SystemSetting::get(DocumentSettings::MAX_DOCUMENT_SIZE_MB, 10),
            'stepLabels' => $this->getStepLabels(),
        ]);
    }

    private function rulesForStep(int $step): array
    {
        $maxSize = (int) SystemSetting::get(DocumentSettings::MAX_DOCUMENT_SIZE_MB, 10);

        return match ($step) {
            1 => [
                'documentType' => 'required|in:' . implode(',', array_column(DocumentType::cases(), 'value')),
            ],
            2 => [
                'file' => "required|file|max:" . ($maxSize * 1024),
            ],
            3 => [
                'notes' => 'nullable|string|max:1000',
            ],
            default => [],
        };
    }

    private function getStepLabels(): array
    {
        return [
            1 => 'نوع المستند',
            2 => 'رفع الملف',
            3 => 'ملاحظات',
            4 => 'تأكيد',
        ];
    }

    private function resolveDocumentable(): ?Model
    {
        $map = [
            'participant' => \App\Domain\Participant\Models\Participant::class,
            'person' => \App\Domain\Identity\Models\Person::class,
            'employee' => \App\Domain\HR\Models\Employee::class,
            'trainer' => \App\Domain\HR\Models\Trainer::class,
        ];

        $class = $map[$this->documentableType] ?? null;
        if (!$class) {
            return null;
        }

        return $class::find($this->documentableId);
    }
}
