<?php

namespace App\Components\LeadSource;

use App\Models\LeadSource\LeadSource;
use App\Models\LeadSource\LeadSourceEndpoint;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Str;
use Livewire\Component;

class Endpoints extends Component {
    use AuthorizesRequests;

    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(): void
    {
        $this->authorize($this->editingId ? 'sources.endpoints.edit' : 'sources.endpoints.create');
        $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;
        }

        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),
            ]
        );

        $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::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): void {
        $this->authorize('sources.endpoints.toggle');
        $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,
        ]);

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

    public function delete(int $endpointId): void {
        $this->authorize('sources.endpoints.delete');
        LeadSourceEndpoint::find($endpointId)->delete();
    }

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