<?php

namespace App\Components\LeadSource;

use App\Models\LeadSource\LeadSource;
use App\Models\LeadSource\LeadSourceEndpoint;
use App\Services\HistoryService;
use Illuminate\Support\Str;
use Livewire\Component;

class Endpoints extends Component {

    public LeadSource $leadSource;

    public string $name = '';
    public bool $showOffcanvas = false;
    public ?LeadSourceEndpoint $selectedEndpoint = null;
    public ?int $editingId = null;

    public string $slug = '';
    public string $url = '';
    public string $status = 'draft';

    protected function rules(): array
    {
        return [
            'name' => 'required|string|max:255',
            'url' => 'nullable|string|max:255',
            'status' => 'required|in:draft,test,active,inactive',
        ];
    }


    protected $rules = [
        'name' => 'required|string|max:255',
    ];

    public function create(HistoryService $history): void
    {
        $this->validate();

        if (
            in_array($this->status, ['test', 'active'], true) &&
            $this->leadSource->status !== 'active'
        ) {
            $this->dispatch(
                'toast',
                type: 'error',
                message: 'Lead source must be active first 😬'
            );
            return;
        }

        $wasEditing = (bool) $this->editingId;

        $endpoint = LeadSourceEndpoint::updateOrCreate(
            [
                'id' => $this->editingId,
                'lead_source_id' => $this->leadSource->id,
            ],
            [
                'lead_source_id' => $this->leadSource->id,
                'display_name'   => $this->name,
                'status'         => $this->status,
                'url'            => $this->url,
                'key'            => $this->editingId
                    ? LeadSourceEndpoint::find($this->editingId)->key
                    : Str::random(40),
            ]
        );

        // Do NOT store the endpoint API key in the audit context.
        $history->addForActor(
            "Lead source endpoint '{$this->name}' " . ($wasEditing ? 'updated' : 'created (new API key issued)'),
            [
                'lead_source_id' => $this->leadSource->id,
                'endpoint_id'    => $endpoint->id,
                'name'           => $this->name,
                'status'         => $this->status,
            ]
        );

        $this->dispatch(
            'toast',
            type: 'success',
            message: $this->editingId
                ? 'Endpoint updated ✨'
                : 'Endpoint created ✨'
        );

        $this->closeOffcanvas();
    }

    /* ------------------------------
 | Offcanvas controls
 |------------------------------*/
    public function createForm(): void
    {
        $this->resetForm();
        $this->showOffcanvas = true;
    }

    /* ---------- Open Edit ---------- */
    public function editForm(int $endpointId): void
    {
        $endpoint = LeadSourceEndpoint::where('lead_source_id', $this->leadSource->id)
            ->findOrFail($endpointId);

        $this->editingId = $endpoint->id;
        $this->name = $endpoint->display_name;
        $this->status = $endpoint->status;

        $this->showOffcanvas = true;
    }

    public function closeOffcanvas(): void
    {
        $this->showOffcanvas = false;
        $this->resetForm();
    }

    protected function resetForm(): void
    {
        $this->reset([
            'editingId',
            'name',
            'slug',
            'status',
        ]);

        $this->status = 'draft';
    }

    public function toggle(int $endpointId, HistoryService $history): void {
        $endpoint = LeadSourceEndpoint::where('lead_source_id', $this->leadSource->id)
            ->findOrFail($endpointId);

        if (
            in_array($endpoint->status, ['draft', 'inactive'], true) &&
            $this->leadSource->status !== 'active'
        ) {
            $this->dispatch(
                'toast',
                type: 'error',
                message: 'Activate the lead source first.'
            );
            return;
        }

        $nextStatus = match ($endpoint->status) {
            'draft', 'inactive' => 'test',
            'test' => 'active',
            'active' => 'inactive',
            default => 'draft',
        };

        $endpoint->update([
            'status' => $nextStatus,
        ]);

        $history->addForActor("Lead source endpoint '{$endpoint->display_name}' set to {$nextStatus}", [
            'lead_source_id' => $this->leadSource->id,
            'endpoint_id'    => $endpoint->id,
            'status'         => $nextStatus,
        ]);

        $this->dispatch(
            'toast',
            type: 'success',
            message: "Endpoint set to {$nextStatus}"
        );
    }

    public function delete(int $endpointId, HistoryService $history): void {
        $endpoint = LeadSourceEndpoint::find($endpointId);

        if (!$endpoint) {
            return;
        }

        $context = [
            'lead_source_id' => $endpoint->lead_source_id,
            'endpoint_id'    => $endpoint->id,
            'name'           => $endpoint->display_name,
        ];

        $endpoint->delete();

        $history->addForActor("Deleted lead source endpoint '{$context['name']}'", $context);
    }

    public function render() {
        return view('components.lead-source.endpoints', [
            'endpoints' => $this->leadSource
                ->endpoints()
                ->orderBy('created_at')
                ->get(),
        ]);
    }
}
