<?php

namespace App\Components\Client;

use App\Models\Client\Client;
use App\Models\LeadSource\LeadSource;
use App\Models\LeadSource\LeadSourceEndpoint;
use Livewire\Attributes\Computed;
use Livewire\Component;

class EditLeadSource extends Component {
    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() {
        $this->client->update([
            'lead_source_id' => $this->selectedLeadSourceId,
            'lead_source_endpoint_id' => $this->selectedEndpointId,
        ]);

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

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

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