<?php

namespace App\Livewire\Modals;

use App\Domains\QrCode\Models\QrCode;
use App\Domains\Workspace\Models\Workspace;
use App\Livewire\Pages\QrCodes\Index;
use Illuminate\View\View;
use LivewireUI\Modal\ModalComponent;

class CreateQrCode extends ModalComponent
{
    public string $workspaceUlid = '';

    public int $workspaceId = 0;

    public string $type = 'url';

    public string $label = '';

    // Generic payload (url, text, email, phone, sms, location)
    public string $url = '';

    // vCard
    public string $vcardName = '';

    public string $vcardPhone = '';

    public string $vcardEmail = '';

    public string $vcardCompany = '';

    public string $vcardWebsite = '';

    // WiFi
    public string $wifiSsid = '';

    public string $wifiPassword = '';

    public string $wifiEncryption = 'WPA';

    public bool $wifiHidden = false;

    // Style
    public string $fgColor = '#000000';

    public string $bgColor = '#ffffff';

    public string $logoUrl = '';

    public string $dotStyle = 'square';

    public int $size = 512;

    public int $margin = 4;

    public string $errorCorrection = 'M';

    public string $frame = 'none';

    public string $frameText = '';

    public string $frameColor = '#7c3aed';

    // Advanced
    public bool $isDynamic = true;

    public ?int $scanLimit = null;

    public string $expiresAt = '';

    public function mount(string $workspaceUlid = ''): void
    {
        if ($workspaceUlid) {
            $workspace = Workspace::where('ulid', $workspaceUlid)->firstOrFail();
            abort_unless(
                $workspace->owner_id === auth()->id() ||
                $workspace->members()->where('user_id', auth()->id())->exists(),
                404
            );
            $this->workspaceUlid = $workspaceUlid;
            $this->workspaceId = $workspace->id;
        }
    }

    public function updated(string $prop): void
    {
        $this->dispatch('qr-preview-update', payload: $this->buildPayload(), options: [
            'size' => $this->size,
            'margin' => $this->margin,
            'errorCorrection' => $this->errorCorrection,
            'fgColor' => $this->fgColor,
            'bgColor' => $this->bgColor,
        ]);
    }

    public function buildPayload(): string
    {
        return match ($this->type) {
            'email' => 'mailto:'.$this->url,
            'phone' => 'tel:'.$this->url,
            'sms' => 'sms:'.$this->url,
            'location' => 'geo:'.$this->url,
            'vcard' => $this->buildVcard(),
            'wifi' => $this->buildWifi(),
            default => $this->url,
        };
    }

    private function buildVcard(): string
    {
        return implode("\n", array_filter([
            'BEGIN:VCARD',
            'VERSION:3.0',
            $this->vcardName ? "FN:{$this->vcardName}" : null,
            $this->vcardPhone ? "TEL:{$this->vcardPhone}" : null,
            $this->vcardEmail ? "EMAIL:{$this->vcardEmail}" : null,
            $this->vcardCompany ? "ORG:{$this->vcardCompany}" : null,
            $this->vcardWebsite ? "URL:{$this->vcardWebsite}" : null,
            'END:VCARD',
        ]));
    }

    private function buildWifi(): string
    {
        $enc = $this->wifiEncryption ?: 'nopass';
        $hidden = $this->wifiHidden ? 'true' : 'false';

        return "WIFI:T:{$enc};S:{$this->wifiSsid};P:{$this->wifiPassword};H:{$hidden};;";
    }

    public function save(): void
    {
        $urlRule = match ($this->type) {
            'url' => 'required|url|max:2048',
            'email', 'phone', 'sms', 'location', 'text' => 'required|max:2048',
            default => 'nullable',
        };

        $this->validate([
            'type' => 'required|in:url,vcard,wifi,text,email,phone,sms,location,pdf,mp3',
            'label' => 'nullable|max:200',
            'url' => $urlRule,
        ]);

        $wsId = $this->workspaceId;
        if (! $wsId) {
            $ws = current_workspace();
            if (! $ws) {
                $this->addError('url', 'Workspace nicht gefunden.');

                return;
            }
            $wsId = $ws->id;
        }

        $dbType = match ($this->type) {
            'email', 'phone', 'sms', 'location' => 'url',
            default => $this->type,
        };

        QrCode::create([
            'workspace_id' => $wsId,
            'type' => $dbType,
            'payload' => [
                'data' => $this->buildPayload(),
                'label' => $this->label,
                'display_type' => $this->type,
            ],
            'style' => [
                'fg_color' => $this->fgColor,
                'bg_color' => $this->bgColor,
                'logo_url' => $this->logoUrl ?: null,
                'dot_style' => $this->dotStyle,
                'size' => $this->size,
                'margin' => $this->margin,
                'error_correction' => $this->errorCorrection,
                'frame' => $this->frame,
                'frame_text' => $this->frameText ?: null,
                'frame_color' => $this->frameColor,
            ],
            'is_dynamic' => $this->isDynamic,
            'scan_limit' => $this->scanLimit ?: null,
            'expires_at' => $this->expiresAt ?: null,
        ]);

        $this->dispatch('qr-created')->to(Index::class);
        $this->dispatch('toast', message: 'QR-Code erstellt', type: 'success');
        $this->closeModal();
    }

    public static function modalMaxWidth(): string
    {
        return '5xl';
    }

    public function render(): View
    {
        return view('livewire.modals.create-qr-code');
    }
}
