<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Property;
use App\Models\InternalCharacteristics;

class InternalCharacteristicsManager extends Component
{
    // Propiedad pública para recibir el record desde Filament
    public $record;
    public $internal_id = '';

    protected $rules = [
        'internal_id' => 'required|exists:internal_characteristics,id',
    ];

    public function mount($record = null): void
    {
        // Si no viene por parámetro, intentar obtener de la propiedad pública
        if ($record) {
            $this->record = $record;
        }
        
        // Asegurar que sea un modelo Property
        if (!$this->record instanceof Property) {
            $this->record = Property::find($this->record);
        }
    }
    
    public function addCharacteristic(): void
    {
        $this->validate();

        if (!$this->record) {
            \Filament\Notifications\Notification::make()
                ->title('Error: No se encontró la propiedad')
                ->danger()
                ->send();
            return;
        }

        $exists = $this->record->internalCharacteristics()
            ->where('internal_id', $this->internal_id)
            ->exists();

        if ($exists) {
            \Filament\Notifications\Notification::make()
                ->title('Esta característica ya está asignada')
                ->warning()
                ->send();
            return;
        }

        $this->record->internalCharacteristics()->attach($this->internal_id);

        $this->reset('internal_id');
        
        \Filament\Notifications\Notification::make()
            ->title('Característica agregada')
            ->success()
            ->send();
            
        $this->dispatch('refreshComponent');
    }

    public function deleteCharacteristic($internalId): void
    {
        if (!$this->record) {
            return;
        }

        $this->record->internalCharacteristics()->detach($internalId);

        
        
        \Filament\Notifications\Notification::make()
            ->title('Característica eliminada')
            ->success()
            ->send();
            
        
        
    }

    public function render()
    {
        $availableCharacteristics = collect();
        $assignedCharacteristics = collect();
        
        if ($this->record) {
            $availableCharacteristics = InternalCharacteristics::all();
            $assignedCharacteristics = $this->record->internalCharacteristics()->get();
        }

        return view('filament.internal', [
            'availableCharacteristics' => $availableCharacteristics,
            'assignedCharacteristics' => $assignedCharacteristics,
        ]);
        
    }
}