<?php

namespace App\Livewire\Territori;

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\Territorio;
use App\Models\Zona;
use App\Models\Tipologia;
use App\Services\TerritorioThumbnailService;
use Illuminate\Support\Facades\Storage;

class TerritorioEdit extends Component
{
    use WithFileUploads;

    public Territorio $territorio;
    public string $numero = '';
    public ?int $zona_id = null;
    public ?int $tipologia_id = null;
    public string $note = '';
    public string $confini = '';
    public $pdf;
    public bool $prioritario = false;

    public function mount(Territorio $territorio)
    {
        $this->territorio = $territorio;
        $this->numero = $territorio->numero;
        $this->zona_id = $territorio->zona_id;
        $this->tipologia_id = $territorio->tipologia_id;
        $this->note = $territorio->note ?? '';
        $this->confini = $territorio->confini ?? '';
        $this->prioritario = $territorio->prioritario;
    }

    protected function rules(): array
    {
        return [
            'numero' => 'required|string|max:20|unique:territori,numero,' . $this->territorio->id,
            'zona_id' => 'nullable|exists:zone,id',
            'tipologia_id' => 'nullable|exists:tipologie,id',
            'note' => 'nullable|string|max:5000',
            'confini' => 'nullable|string|max:5000',
            'pdf' => 'nullable|file|mimes:pdf|max:10240',
            'prioritario' => 'boolean',
        ];
    }

    public function save()
    {
        $this->validate();

        $data = [
            'numero' => $this->numero,
            'zona_id' => $this->zona_id,
            'tipologia_id' => $this->tipologia_id,
            'note' => $this->note ?: null,
            'confini' => $this->confini ?: null,
            'prioritario' => $this->prioritario,
        ];

        if ($this->pdf) {
            $thumbService = app(TerritorioThumbnailService::class);
            // Remove old PDF and thumbnail
            if ($this->territorio->pdf_path) {
                Storage::disk('public')->delete($this->territorio->pdf_path);
            }
            if ($this->territorio->thumbnail_path) {
                $thumbService->delete($this->territorio->thumbnail_path);
            }
            $pdfPath = $this->pdf->store('territori-pdf', 'public');
            $data['pdf_path'] = $pdfPath;
            $data['thumbnail_path'] = $thumbService->generate($pdfPath);
        }

        $this->territorio->update($data);

        session()->flash('success', "Territorio {$this->territorio->numero} aggiornato.");
        return redirect()->route('territori.show', $this->territorio);
    }

    public function removePdf()
    {
        if ($this->territorio->pdf_path) {
            Storage::disk('public')->delete($this->territorio->pdf_path);
            if ($this->territorio->thumbnail_path) {
                app(TerritorioThumbnailService::class)->delete($this->territorio->thumbnail_path);
            }
            $this->territorio->update(['pdf_path' => null, 'thumbnail_path' => null]);
            activity()->causedBy(auth()->user())
                ->performedOn($this->territorio)
                ->log('removed_pdf');
        }
    }

    public function render()
    {
        return view('livewire.territori.territorio-form', [
            'zone' => Zona::attive()->get(),
            'tipologie' => Tipologia::attive()->get(),
            'isEdit' => true,
            'title' => "Modifica Territorio {$this->territorio->numero}",
        ]);
    }
}
