<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use App\Models\SocialPost;
use App\Services\SocialScraper;
use Illuminate\Support\Facades\Storage;

return new class extends Component
{
    use WithFileUploads;

    // ── Scraper state ──────────────────────────────────────────────
    public $scrapeUrl   = '';
    public $preview     = null;
    public $scrapeError = '';

    // ── Edit state ─────────────────────────────────────────────────
    public $editingId          = null;
    public $editTitle          = '';
    public $editDescription    = '';
    public $editAuthorName     = '';
    public $editThumbnailUrl   = '';   // existing URL or storage path
    public $editThumbnailFile  = null; // newly uploaded file
    public $editEmbedHtml      = '';

    public function render()
    {
        return $this->view()->layout('layouts::auth');
    }

    public function with(): array
    {
        return ['posts' => SocialPost::latest()->get()];
    }

    // ── Scraper ────────────────────────────────────────────────────

    public function fetch(): void
    {
        $this->validate(['scrapeUrl' => 'required|url']);
        $this->scrapeError = '';
        $this->preview     = null;

        try {
            $this->preview = (new SocialScraper())->scrape($this->scrapeUrl);
        } catch (\Exception $e) {
            $this->scrapeError = $e->getMessage();
        }
    }

    public function save(): void
    {
        if (! $this->preview) return;

        SocialPost::create($this->preview);

        $this->preview   = null;
        $this->scrapeUrl = '';
        session()->flash('message', 'Post saved successfully.');
    }

    public function cancelPreview(): void
    {
        $this->preview     = null;
        $this->scrapeUrl   = '';
        $this->scrapeError = '';
    }

    // ── Edit ───────────────────────────────────────────────────────

    public function openEdit(int $id): void
    {
        $post = SocialPost::find($id);
        if (! $post) return;

        $this->editingId         = $id;
        $this->editTitle         = $post->title ?? '';
        $this->editDescription   = $post->description ?? '';
        $this->editAuthorName    = $post->author_name ?? '';
        $this->editThumbnailUrl  = $post->thumbnail_url ?? '';
        $this->editEmbedHtml     = $post->embed_html ?? '';
        $this->editThumbnailFile = null;

        // Dismiss any open preview
        $this->preview = null;
    }

    public function updatePost(): void
    {
        $this->validate([
            'editTitle'         => 'required|string|max:500',
            'editAuthorName'    => 'nullable|string|max:255',
            'editDescription'   => 'nullable|string',
            'editThumbnailUrl'  => 'nullable|url',
            'editThumbnailFile' => 'nullable|image|max:2048',
            'editEmbedHtml'     => 'nullable|string',
        ]);

        $post = SocialPost::find($this->editingId);
        if (! $post) return;

        $thumbnailUrl = $post->thumbnail_url; // keep existing by default

        if ($this->editThumbnailFile) {
            // Delete old uploaded thumbnail if it was a storage file
            if ($post->thumbnail_url && ! str_starts_with($post->thumbnail_url, 'http')) {
                Storage::disk('public')->delete($post->thumbnail_url);
            }
            $thumbnailUrl = $this->editThumbnailFile->store('social-thumbnails', 'public');
        } elseif ($this->editThumbnailUrl !== $post->thumbnail_url) {
            // URL was manually changed — delete old file if it was stored
            if ($post->thumbnail_url && ! str_starts_with($post->thumbnail_url, 'http')) {
                Storage::disk('public')->delete($post->thumbnail_url);
            }
            $thumbnailUrl = $this->editThumbnailUrl;
        }

        $post->update([
            'title'         => $this->editTitle,
            'description'   => $this->editDescription,
            'author_name'   => $this->editAuthorName,
            'thumbnail_url' => $thumbnailUrl,
            'embed_html'    => $this->editEmbedHtml,
        ]);

        $this->cancelEdit();
        session()->flash('message', 'Post updated successfully.');
    }

    public function cancelEdit(): void
    {
        $this->editingId         = null;
        $this->editTitle         = '';
        $this->editDescription   = '';
        $this->editAuthorName    = '';
        $this->editThumbnailUrl  = '';
        $this->editThumbnailFile = null;
        $this->editEmbedHtml     = '';
        $this->resetValidation();
    }

    // ── Status / Delete ────────────────────────────────────────────

    public function toggleStatus(int $id): void
    {
        $post = SocialPost::find($id);
        if (! $post) return;
        $post->update(['status' => $post->status === 'show' ? 'hide' : 'show']);
    }

    public function delete(int $id): void
    {
        SocialPost::find($id)?->delete();
        if ($this->editingId === $id) $this->cancelEdit();
        session()->flash('message', 'Post deleted.');
    }

    protected function view($data = [])
    {
        return app('view')->file('D:\02-my freelance\00-DR_Padhi\DR_PADHI\storage\framework/views/livewire/views/0498a791.blade.php', $data);
    }
};
