<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\LeadSource\LeadSource;
use App\Models\LeadSource\LeadSourceEndpoint;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Computed;
use Livewire\Component;

class EditLeadSource extends Component {
    use AuthorizesRequests;
    public Client $client;

    // We fetch sources once on mount since they rarely change
    public $leadSources;

    // Properties to track the currently selected items in the modal
    public $selectedLeadSourceId = null;
    public $selectedEndpointId = null;

    public function mount(Client $client) {
        $this->client = $client;
        $this->leadSources = LeadSource::orderBy('display_name')->get();

        // Initialize the modal state with the client's current data
        $this->selectedLeadSourceId = $client->lead_source_id;
        $this->selectedEndpointId = $client->lead_source_endpoint_id;
    }

    /**
     * Compute the endpoints dynamically based on the selected lead source.
     * This ensures we only query the DB when the source changes or is present.
     */
    #[Computed]
    public function endpoints() {
        if (!$this->selectedLeadSourceId) {
            return collect();
        }

        return LeadSourceEndpoint::where('lead_source_id', $this->selectedLeadSourceId)
            ->orderBy('display_name')
            ->get();
    }

    /**
     * Handle the user clicking a lead source in the list.
     */
    public function selectLeadSource($id) {
        $this->selectedLeadSourceId = $id;

        // If the user clicks back to the original source, restore their original endpoint.
        // Otherwise, clear the endpoint selection.
        if ($this->client->lead_source_id == $id) {
            $this->selectedEndpointId = $this->client->lead_source_endpoint_id;
        } else {
            $this->selectedEndpointId = null;
        }
    }

    public function selectEndpoint($id) {
        $this->selectedEndpointId = $id;
    }

    public function save(HistoryService $history) {
        $this->authorize('clients.edit');
        $oldSourceId = $this->client->lead_source_id;
        $oldEndpointId = $this->client->lead_source_endpoint_id;

        $this->client->update([
            'lead_source_id' => $this->selectedLeadSourceId,
            'lead_source_endpoint_id' => $this->selectedEndpointId,
        ]);

        $this->client->load(['leadSource', 'endpoint']);

        $history->add($this->client, 'Lead source set to "' . ($this->client->leadSource?->display_name ?? 'None') . '"', [
            'from_lead_source_id' => $oldSourceId,
            'to_lead_source_id' => $this->selectedLeadSourceId,
            'to_lead_source' => $this->client->leadSource?->display_name,
            'from_endpoint_id' => $oldEndpointId,
            'to_endpoint_id' => $this->selectedEndpointId,
            'to_endpoint' => $this->client->endpoint?->display_name,
        ]);

        $this->dispatch('close-modal', modalId: 'leadSourceModal-' . $this->client->id);
    }

    public function render() {
        return view('components.client.edit-lead-source');
    }
}
