<?php

namespace App\Livewire;

use App\Models\News;
use Livewire\Component;
use Livewire\Attributes\On;
use App\Actions\Mistral\AiTextGeneration;

class NewsCard extends Component
{
    public $lastNews;
    public $editingNewsId = null;
    public $editingNewsName = '';
    public $editingNewsDescription = '';

    public function mount()
    {
        $this->loadNews();
    }

    public function loadNews()
    {
        $this->lastNews = News::with(['districts', 'categories'])
            ->latest()
            ->take(40)
            ->get();
    }

    public function changeStatus($newsId, $status)
    {
        try {
            $news = News::findOrFail($newsId);

            // Durum güncelle
            $news->status = $status;

            // Eğer yayında ise published_at tarihini güncelle
            if ($status === 'published' && is_null($news->published_at)) {
                $news->published_at = now();
            }

            $news->save();

            // Listeyi yenile
            $this->loadNews();

            // Başarı mesajı
            session()->flash('success', 'Haber durumu başarıyla güncellendi.');

        } catch (\Exception $e) {
            session()->flash('error', 'Bir hata oluştu: ' . $e->getMessage());
        }
    }

    public function editNews($newsId)
    {
        $news = News::findOrFail($newsId);
        $this->editingNewsId = $newsId;
        $this->editingNewsName = $news->ai_name;
        $this->editingNewsDescription = $news->ai_description;
    }

    public function cancelEdit()
    {
        $this->editingNewsId = null;
        $this->editingNewsName = '';
        $this->editingNewsDescription = '';
    }

    public function updateNews()
    {
        $this->validate([
            'editingNewsName' => 'required|min:3|max:255',
            'editingNewsDescription' => 'required|min:10|max:1000',
        ], [
            'editingNewsName.required' => 'Başlık alanı zorunludur.',
            'editingNewsName.min' => 'Başlık en az 3 karakter olmalıdır.',
            'editingNewsName.max' => 'Başlık en fazla 255 karakter olabilir.',
            'editingNewsDescription.required' => 'Açıklama alanı zorunludur.',
            'editingNewsDescription.min' => 'Açıklama en az 10 karakter olmalıdır.',
            'editingNewsDescription.max' => 'Açıklama en fazla 1000 karakter olabilir.',
        ]);

        try {
            $news = News::findOrFail($this->editingNewsId);
            $news->ai_name = $this->editingNewsName;
            $news->ai_description = $this->editingNewsDescription;
            $news->save();

            // Düzenleme modunu kapat
            $this->cancelEdit();

            // Listeyi yenile
            $this->loadNews();

            // Başarı mesajı
            session()->flash('success', 'Haber başarıyla güncellendi.');

        } catch (\Exception $e) {
            session()->flash('error', 'Bir hata oluştu: ' . $e->getMessage());
        }
    }

    #[On('newsUpdated')]
    public function refreshNews()
    {
        $this->loadNews();
    }

    public function regenerateAiTitle($newsId)
    {
        try {
            $news = News::findOrFail($newsId);

            // AI ile yeni başlık oluştur
            $aiTextGeneration = new AiTextGeneration();
            $prompt = "Aşağıdaki haberi açıklayan, ilgi çekici bir haber başlığı oluştur.\n"
            . "Uzun olmamalı en fazla 70 karakter olsun\n"
            . "Tek cümle olsun\n"
            . "Yorum içermesin\n"
            . "Başlık haberin ana konusunu net yansıtsın\n"
            . "Clickbait olmasın\n" . $news->ai_description;

            $response = $aiTextGeneration->execute($prompt, 'qwen-plus-latest');

            if (isset($response->choices[0]->message->content)) {
                $newTitle = trim($response->choices[0]->message->content);

                // Başlıktaki tırnak işaretlerini temizle
                $newTitle = str_replace(['"', "'", '«', '»'], '', $newTitle);

                $news->ai_name = $newTitle;
                $news->save();

                // Listeyi yenile
                $this->loadNews();

                session()->flash('success', 'Başlık AI ile yeniden oluşturuldu.');
            } else {
                session()->flash('error', 'AI yanıtı alınamadı.');
            }

        } catch (\Exception $e) {
            session()->flash('error', 'Bir hata oluştu: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.news-card');
    }
}
