<?php

namespace App\Livewire\Admin;

use App\Models\Blog;
use App\Models\Category;
use App\Models\SubCategory;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Str;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Layout;

#[Layout('components.admin-layout')]
class Blogs extends Component
{
    use WithPagination, WithFileUploads;

    public $search = '';
    public $sortField = 'name';
    public $sortDirection = 'asc';
    public $perPage = 10;

    // Form properties
    public $showForm = false;
    public $formType = 'create';
    public $blogId = null;
    public $name = '';
    public $description = '';
    public $image;
    public $meta_title = '';
    public $meta_description = '';
    public $meta_keywords = '';
    public $meta_tags = '';
    public $page_schemas = '';
    public $category_id = '';

    // SEO Analysis properties
    public $seoScore = 0;
    public $seoMetrics = [];

    // Add this property for filtered subcategories
    public $filteredSubcategories = [];

    protected $queryString = [
        'search' => ['except' => ''],
        'sortField' => ['except' => 'name'],
        'sortDirection' => ['except' => 'asc'],
        'perPage' => ['except' => 10]
    ];

    protected $rules = [
        'name' => 'required|string|max:255',
        'description' => 'required|string',
        'image' => 'nullable|image|max:2048',
        'meta_title' => 'nullable|string|max:255',
        'meta_description' => 'nullable|string',
        'meta_keywords' => 'nullable|string',
        'meta_tags' => 'nullable|string',
        'page_schemas' => 'nullable|string',
        'category_id' => 'nullable|exists:categories,id',
    ];

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

    // Add this method to load subcategories based on selected category
    public function loadFilteredSubcategories()
    {
        if ($this->category_id) {
            $this->filteredSubcategories = SubCategory::where('category_id', $this->category_id)->get();
        } else {
            $this->filteredSubcategories = collect();
        }
    }

    // Add this method to update subcategories when category changes
    

    public function resetForm()
    {
        $this->reset([
            'showForm', 'formType', 'blogId', 'name', 'description', 
            'image', 'meta_title', 'meta_description', 
            'meta_keywords', 'meta_tags', 'page_schemas',
            'seoScore', 'seoMetrics', 'category_id',
            'filteredSubcategories' // Reset this too
        ]);
        $this->resetErrorBag();
        $this->loadFilteredSubcategories();
    }

    public function analyzeSeo()
    {
        $this->seoMetrics = [];
        
        // Analyze Title
        $titleLength = strlen($this->name);
        $this->seoMetrics[] = [
            'name' => 'Title Length',
            'status' => $titleLength >= 10 && $titleLength <= 60,
            'message' => "{$titleLength}/60 chars",
            'weight' => 20
        ];

        // Analyze Meta Title
        $metaTitleLength = strlen($this->meta_title);
        $this->seoMetrics[] = [
            'name' => 'Meta Title',
            'status' => $metaTitleLength >= 10 && $metaTitleLength <= 60,
            'message' => "{$metaTitleLength}/60 chars",
            'weight' => 15
        ];

        // Analyze Meta Description
        $metaDescLength = strlen($this->meta_description);
        $this->seoMetrics[] = [
            'name' => 'Meta Description',
            'status' => $metaDescLength >= 120 && $metaDescLength <= 160,
            'message' => "{$metaDescLength}/160 chars",
            'weight' => 15
        ];

        // Analyze Content
        $textContent = strip_tags($this->description);
        $wordCount = str_word_count($textContent);
        $this->seoMetrics[] = [
            'name' => 'Content Length',
            'status' => $wordCount >= 300,
            'message' => "{$wordCount}/300+ words",
            'weight' => 20
        ];

        // Analyze Headings
        $h1Count = substr_count(strtolower($this->description), '<h1');
        $h2Count = substr_count(strtolower($this->description), '<h2');
        $this->seoMetrics[] = [
            'name' => 'Heading Structure',
            'status' => $h1Count === 1 && $h2Count >= 1,
            'message' => "H1: {$h1Count}, H2: {$h2Count}",
            'weight' => 15
        ];

        // Analyze Keyword Density
        $keywordScore = $this->analyzeKeywordDensity($textContent);
        $this->seoMetrics[] = [
            'name' => 'Keyword Optimization',
            'status' => $keywordScore['status'],
            'message' => $keywordScore['message'],
            'weight' => 15
        ];

        // Calculate overall score
        $this->calculateSeoScore();
    }

    private function analyzeKeywordDensity($content)
    {
        $words = str_word_count(strtolower($content), 1);
        if (empty($words)) {
            return ['status' => false, 'message' => 'No content'];
        }

        $wordFreq = array_count_values($words);
        
        // Remove common words
        $commonWords = ['the', 'and', 'for', 'with', 'this', 'that', 'are', 'was', 'were', 'have', 'has', 'had', 'but', 'not', 'you', 'your', 'they', 'their'];
        foreach ($commonWords as $common) {
            unset($wordFreq[$common]);
        }
        
        arsort($wordFreq);
        $topKeywords = array_slice($wordFreq, 0, 5, true);
        
        $primaryKeyword = key($topKeywords);
        $density = $primaryKeyword ? 
            ($topKeywords[$primaryKeyword] / count($words) * 100) : 0;

        return [
            'status' => $density >= 1 && $density <= 3,
            'message' => round($density, 1) . "% density"
        ];
    }

    private function calculateSeoScore()
    {
        $totalWeight = 0;
        $achievedWeight = 0;

        foreach ($this->seoMetrics as $metric) {
            $totalWeight += $metric['weight'];
            if ($metric['status']) {
                $achievedWeight += $metric['weight'];
            }
        }

        $this->seoScore = $totalWeight > 0 ? 
            round(($achievedWeight / $totalWeight) * 100) : 0;
    }

    public function sortBy($field)
    {
        if ($this->sortField === $field) {
            $this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortField = $field;
            $this->sortDirection = 'asc';
        }
    }

    // Add the missing create method
    public function create()
    {
        $this->resetForm();
        $this->formType = 'create';
        $this->showForm = true;
        $this->analyzeSeo();
    }

    public function edit($blogId)
    {
        $blog = Blog::findOrFail($blogId);
        
        $this->formType = 'edit';
        $this->blogId = $blog->id;
        $this->name = $blog->name;
        $this->description = $blog->description;
        $this->meta_title = $blog->meta_title;
        $this->meta_description = $blog->meta_description;
        $this->meta_keywords = $blog->meta_keywords;
        $this->meta_tags = $blog->meta_tags;
        $this->page_schemas = $blog->page_schemas;
        $this->category_id = $blog->category_id;
        
        // Load subcategories for the selected category
        $this->loadFilteredSubcategories();
        
        $this->showForm = true;
        $this->analyzeSeo();
    }

    public function save()
    {
        $this->validate();

        $data = [
            'name' => $this->name,
            'slug' => Str::slug($this->name),
            'description' => $this->description,
            'meta_title' => $this->meta_title,
            'meta_description' => $this->meta_description,
            'meta_keywords' => $this->meta_keywords,
            'meta_tags' => $this->meta_tags,
            'page_schemas' => $this->page_schemas,
            'category_id' => $this->category_id,
        ];

        // Handle image upload
        if ($this->image) {
            $imagePath = $this->image->store('blogs', 'public');
            $data['image'] = $imagePath;
        }

        if ($this->formType === 'create') {
            Blog::create($data);
            session()->flash('success', 'Blog created successfully.');
        } else {
            $blog = Blog::findOrFail($this->blogId);
            
            // Delete old image if new one is uploaded
            if ($this->image && $blog->image) {
                Storage::disk('public')->delete($blog->image);
            }
            
            $blog->update($data);
            session()->flash('success', 'Blog updated successfully.');
        }

        $this->resetForm();
    }

    public function delete($blogId)
    {
        $blog = Blog::findOrFail($blogId);
        
        // Delete associated image if exists
        if ($blog->image) {
            Storage::disk('public')->delete($blog->image);
        }

        $blog->delete();
        session()->flash('success', 'Blog deleted successfully.');
    }

    public function render()
    {
        $blogs = Blog::when($this->search, function ($query) {
                $query->where('name', 'like', '%' . $this->search . '%')
                      ->orWhere('description', 'like', '%' . $this->search . '%')
                      ->orWhere('meta_title', 'like', '%' . $this->search . '%')
                      ->orWhere('meta_keywords', 'like', '%' . $this->search . '%');
            })
            ->orderBy($this->sortField, $this->sortDirection)
            ->paginate($this->perPage);
        $categories = Category::all();

        return view('livewire.admin.blogs', [
            'blogs' => $blogs,
            'categories' => $categories,
        ]);
    }
}