<?php

use Livewire\Component;
use Livewire\WithFileUploads;
use Livewire\WithPagination;
use Livewire\Attributes\Url;
use App\Models\SocialPost;
use App\Services\SocialScraper;
use App\Services\ImageCompressor;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;

return new class extends Component
{
    use WithFileUploads, WithPagination;

    // ── Search & Filter ──────────────────────────────────────────
    #[Url(history: true)]
    public $search = '';

    #[Url(history: true)]
    public $platformFilter = '';

    #[Url(history: true)]
    public $statusFilter = '';

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

    // ── Bulk Import state ──────────────────────────────────────────
    public $activeTab = 'single'; // 'single' or 'bulk'
    public $bulkChannelInput = 'UCfxS5DCJygRmu3aQhzxlT3g';
    public $bulkNextPageToken = null;
    public $bulkImportCount = 0;
    public $bulkPlaylistId = null;
    public $isBulkImporting = false;
    public $bulkError = '';

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

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

    public function setTab(string $tab): void
    {
        $this->activeTab = $tab;
        $this->cancelPreview();
        $this->cancelEdit();
    }

    public function with(): array
    {
        $query = SocialPost::latest();

        if ($this->search) {
            $query->where(function($q) {
                $q->where('title', 'like', '%' . $this->search . '%')
                  ->orWhere('description', 'like', '%' . $this->search . '%')
                  ->orWhere('author_name', 'like', '%' . $this->search . '%');
            });
        }

        if ($this->platformFilter) {
            $query->where('platform', $this->platformFilter);
        }

        if ($this->statusFilter) {
            $query->where('status', $this->statusFilter);
        }

        return ['posts' => $query->paginate(10)];
    }

    public function updatingSearch() { $this->resetPage(); }
    public function updatingPlatformFilter() { $this->resetPage(); }
    public function updatingStatusFilter() { $this->resetPage(); }

    // ── Actions ────────────────────────────────────────────────────

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

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

    // ── 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;

        $data = $this->preview;

        if ($this->storeLocally && !empty($data['thumbnail_url'])) {
            $localPath = $this->downloadThumbnail($data['thumbnail_url']);
            if ($localPath) {
                $data['thumbnail_url'] = $localPath;
            }
        }

        SocialPost::create($data);

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

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

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

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

        $this->editingId         = $id;
        $this->editUrl           = $post->url ?? '';
        $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;
        $this->storeLocally      = false;

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

    public function refetch(): void
    {
        if (! $this->editUrl) return;

        try {
            $data = (new SocialScraper())->scrape($this->editUrl);
            $this->editTitle        = $data['title'] ?? $this->editTitle;
            $this->editDescription  = $data['description'] ?? $this->editDescription;
            $this->editAuthorName   = $data['author_name'] ?? $this->editAuthorName;
            $this->editThumbnailUrl = $data['thumbnail_url'] ?? $this->editThumbnailUrl;
            $this->editEmbedHtml    = $data['embed_html'] ?? $this->editEmbedHtml;

            session()->flash('edit_message', 'Data refetched from platform.');
        } catch (\Exception $e) {
            session()->flash('edit_error', 'Refetch failed: ' . $e->getMessage());
        }
    }

    public function updatePost(): void
    {
        $this->validate([
            'editTitle'         => 'required|string|max:500',
            'editAuthorName'    => 'nullable|string|max:255',
            'editDescription'   => 'nullable|string',
            'editThumbnailUrl'  => 'nullable|string', // could be a path or a 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
            $this->deleteOldThumbnail($post->thumbnail_url);
            $thumbnailUrl = app(ImageCompressor::class)->compress($this->editThumbnailFile, 'social-thumbnails');
        } elseif ($this->storeLocally && !empty($this->editThumbnailUrl) && str_starts_with($this->editThumbnailUrl, 'http')) {
            // User requested to store the current URL locally
            $this->deleteOldThumbnail($post->thumbnail_url);
            $localPath = $this->downloadThumbnail($this->editThumbnailUrl);
            $thumbnailUrl = $localPath ?: $this->editThumbnailUrl;
        } elseif ($this->editThumbnailUrl !== $post->thumbnail_url) {
            // URL was manually changed — delete old file if it was stored
            $this->deleteOldThumbnail($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->editUrl           = '';
        $this->editTitle         = '';
        $this->editDescription   = '';
        $this->editAuthorName    = '';
        $this->editThumbnailUrl  = '';
        $this->editThumbnailFile = null;
        $this->editEmbedHtml     = '';
        $this->storeLocally      = false;
        $this->resetValidation();
    }

    private function deleteOldThumbnail(?string $path): void
    {
        if ($path && ! str_starts_with($path, 'http')) {
            Storage::disk('public')->delete($path);
        }
    }

    private function downloadThumbnail(string $url): ?string
    {
        try {
            $response = Http::get($url);
            if ($response->successful()) {
                return app(ImageCompressor::class)->compressFromContent($response->body(), 'social-thumbnails');
            }
        } catch (\Exception $e) {
            // Log or handle error
        }
        return null;
    }

    public function startBulkImport(): void
    {
        $this->validate(['bulkChannelInput' => 'required']);
        $this->bulkError = '';
        $this->bulkImportCount = 0;
        $this->bulkNextPageToken = null;
        $this->isBulkImporting = true;

        $apiKey = config('services.youtube.api_key');
        
        // --- LITE MODE (RSS) ---
        if (!$apiKey) {
            $this->runLiteImport();
            return;
        }

        // --- FULL MODE (API) ---
        try {
            // Resolve channel to get uploads playlist ID
            $params = [
                'key' => $apiKey,
                'part' => 'contentDetails',
            ];

            if (str_starts_with($this->bulkChannelInput, '@')) {
                $params['forHandle'] = $this->bulkChannelInput;
            } else {
                $params['id'] = $this->bulkChannelInput;
            }

            $response = Http::get('https://www.googleapis.com/youtube/v3/channels', $params);

            if (!$response->successful() || empty($response->json()['items'])) {
                throw new \Exception('Channel not found or API key invalid.');
            }

            $this->bulkPlaylistId = $response->json()['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
            
            // Trigger first page processing
            $this->processBulkPage();
        } catch (\Exception $e) {
            $this->bulkError = $e->getMessage();
            $this->isBulkImporting = false;
        }
    }

    private function runLiteImport(): void
    {
        $channelId = $this->bulkChannelInput;

        // If it starts with @, we can't easily get the ID without an API key or scraping
        if (str_starts_with($channelId, '@')) {
            $this->bulkError = 'Lite Mode (No API Key) requires a Channel ID (starting with UC...). Handles (@) are only supported with an API key.';
            $this->isBulkImporting = false;
            return;
        }

        try {
            $rssUrl = "https://www.youtube.com/feeds/videos.xml?channel_id={$channelId}";
            $response = Http::get($rssUrl);

            if (!$response->successful()) {
                throw new \Exception('Could not fetch RSS feed. Ensure the Channel ID is correct.');
            }

            $xml = new \SimpleXMLElement($response->body());
            $xml->registerXPathNamespace('yt', 'http://www.youtube.com/xml/schemas/2015');
            $xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');

            $entries = $xml->entry;
            if (!$entries) {
                throw new \Exception('No videos found in the RSS feed.');
            }

            foreach ($entries as $entry) {
                $videoId = (string) $entry->children('yt', true)->videoId;
                $url = "https://www.youtube.com/watch?v={$videoId}";
                
                $media = $entry->children('media', true)->group;
                $thumbnail = (string) $media->thumbnail->attributes()->url;
                $description = (string) $media->description;

                SocialPost::updateOrCreate(
                    ['url' => $url],
                    [
                        'platform' => 'youtube',
                        'title' => (string) $entry->title,
                        'description' => $description,
                        'thumbnail_url' => $thumbnail,
                        'author_name' => (string) $entry->author->name,
                        'status' => 'show',
                        'embed_html' => '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $videoId . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="width:100%;aspect-ratio:16/9;border-radius:6px;"></iframe>',
                    ]
                );
                $this->bulkImportCount++;
            }

            $this->isBulkImporting = false;
            session()->flash('message', "Lite Import complete. Fetched {$this->bulkImportCount} latest videos via RSS.");
        } catch (\Exception $e) {
            $this->bulkError = "Lite Import Error: " . $e->getMessage();
            $this->isBulkImporting = false;
        }
    }

    public function processBulkPage(): void
    {
        if (!$this->isBulkImporting || !$this->bulkPlaylistId) return;

        try {
            $response = Http::get('https://www.googleapis.com/youtube/v3/playlistItems', [
                'key' => config('services.youtube.api_key'),
                'playlistId' => $this->bulkPlaylistId,
                'part' => 'snippet',
                'maxResults' => 50,
                'pageToken' => $this->bulkNextPageToken,
            ]);

            if (!$response->successful()) {
                throw new \Exception('Failed to fetch playlist items.');
            }

            $data = $response->json();
            foreach ($data['items'] as $item) {
                $videoId = $item['snippet']['resourceId']['videoId'];
                $url = "https://www.youtube.com/watch?v={$videoId}";
                
                SocialPost::updateOrCreate(
                    ['url' => $url],
                    [
                        'platform' => 'youtube',
                        'title' => $item['snippet']['title'],
                        'description' => $item['snippet']['description'] ?? '',
                        'thumbnail_url' => $item['snippet']['thumbnails']['high']['url'] ?? $item['snippet']['thumbnails']['default']['url'] ?? '',
                        'author_name' => $item['snippet']['channelTitle'],
                        'status' => 'show',
                        'embed_html' => '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . $videoId . '" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen style="width:100%;aspect-ratio:16/9;border-radius:6px;"></iframe>',
                    ]
                );
                $this->bulkImportCount++;
            }

            $this->bulkNextPageToken = $data['nextPageToken'] ?? null;

            if (!$this->bulkNextPageToken) {
                $this->isBulkImporting = false;
                session()->flash('message', "Bulk import complete. Total processed: {$this->bulkImportCount}");
            }
        } catch (\Exception $e) {
            $this->bulkError = "Import error: " . $e->getMessage();
            $this->isBulkImporting = false;
        }
    }

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