<?php

namespace App\Livewire\Templates;

use App\Livewire\Campaigns\EmailTemplateGallery;
use App\Models\EmailTemplate;
use App\Traits\AuthorizesWorkspaceActions;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;

/**
 * Standalone Email Templates library.
 *
 * Library-only surface: list + filter + preview + duplicate + delete.
 * Authoring (Create / Edit) happens in the dedicated
 * /templates/builder route which mounts the existing
 * App\Livewire\Campaigns\EmailBuilder — the same block builder the
 * campaigns module uses. This keeps one builder, one block schema,
 * one rendering pipeline across the entire platform.
 */
class TemplatesManager extends Component
{
    use AuthorizesWorkspaceActions;

    /** Browsing state. */
    #[Url]
    public string $category = 'all';
    public string $search = '';

    /** Preview modal. */
    public ?int $previewId = null;

    public function mount(): void
    {
        if (!$this->authorizeWorkspaceAction('view')) return;
    }

    // ── BROWSE ─────────────────────────────────────────────────

    #[Computed]
    public function templates()
    {
        $workspaceId = auth()->user()->active_workspace_id;

        $query = EmailTemplate::forWorkspace($workspaceId);

        if ($this->category !== 'all') {
            $query->where('category', $this->category);
        }
        if ($this->search !== '') {
            $query->where('name', 'like', '%' . $this->search . '%');
        }

        return $query->orderByDesc('usage_count')->orderBy('name')->get();
    }

    #[Computed]
    public function categories(): array
    {
        return EmailTemplateGallery::categories();
    }

    // ── PREVIEW ────────────────────────────────────────────────

    public function preview(int $id): void
    {
        $this->previewId = $id;
    }

    public function closePreview(): void
    {
        $this->previewId = null;
    }

    #[Computed]
    public function previewHtml(): string
    {
        if (!$this->previewId) return '';

        $workspaceId = auth()->user()->active_workspace_id;
        $template = EmailTemplate::forWorkspace($workspaceId)->find($this->previewId);

        if (!$template) return '';

        return EmailTemplateGallery::renderBlocksPreview($template->blocks ?? []);
    }

    // ── DUPLICATE / DELETE ─────────────────────────────────────
    // Create and Edit are full-page redirects to /templates/builder
    // and happen via plain <a wire:navigate> links in the view — no
    // inline editor lives here anymore.

    public function duplicate(int $id): void
    {
        if (!$this->authorizeWorkspaceAction('manage')) return;

        $workspaceId = auth()->user()->active_workspace_id;
        $source = EmailTemplate::forWorkspace($workspaceId)->find($id);
        if (!$source) return;

        // Even for platform templates (workspace_id NULL), the copy is
        // owned by the workspace — that's the whole point of Duplicate:
        // start from a prebuilt as a fork-and-edit base.
        EmailTemplate::create([
            'workspace_id' => $workspaceId,
            'name'         => $source->name . ' ' . __('(copy)'),
            'category'     => $source->category,
            'blocks'       => $source->blocks,
            'is_default'   => false,
        ]);

        unset($this->templates);
        session()->flash('success', __('Template duplicated.'));
    }

    public function delete(int $id): void
    {
        if (!$this->authorizeWorkspaceAction('manage')) return;

        $workspaceId = auth()->user()->active_workspace_id;
        $template = EmailTemplate::forWorkspace($workspaceId)->find($id);
        if (!$template) return;

        // Platform templates aren't deletable from a workspace — refuse.
        if ($template->workspace_id === null) {
            session()->flash('error', __('Platform templates cannot be deleted.'));
            return;
        }

        $template->delete();
        unset($this->templates);
        session()->flash('success', __('Template removed.'));
    }

    public function render()
    {
        return view('livewire.templates.manager');
    }
}
