<?php

namespace App\Livewire;

use App\Models\Setting;
use Illuminate\Contracts\View\View;
use Livewire\Component;

class Settings extends Component
{
    public bool $articleProcessingEnabled = true;

    public bool $publishingApprovalsEnabled = false;

    public int $articlePublishingInterval = 5;

    public int $feedStalenessThreshold = 48;

    public int $dailyPublishCap = 0;

    public ?string $successMessage = null;

    public ?string $errorMessage = null;

    public function mount(): void
    {
        $this->articleProcessingEnabled = Setting::isArticleProcessingEnabled();
        $this->publishingApprovalsEnabled = Setting::isPublishingApprovalsEnabled();
        $this->articlePublishingInterval = Setting::getArticlePublishingInterval();
        $this->feedStalenessThreshold = Setting::getFeedStalenessThreshold();
        $this->dailyPublishCap = Setting::getDailyPublishCap();
    }

    public function toggleArticleProcessing(): void
    {
        $this->articleProcessingEnabled = ! $this->articleProcessingEnabled;
        Setting::setArticleProcessingEnabled($this->articleProcessingEnabled);
        $this->showSuccess();
    }

    public function togglePublishingApprovals(): void
    {
        $this->publishingApprovalsEnabled = ! $this->publishingApprovalsEnabled;
        Setting::setPublishingApprovalsEnabled($this->publishingApprovalsEnabled);
        $this->showSuccess();
    }

    public function updateArticlePublishingInterval(): void
    {
        $this->validate([
            'articlePublishingInterval' => 'required|integer|min:0',
        ]);

        Setting::setArticlePublishingInterval($this->articlePublishingInterval);
        $this->showSuccess();
    }

    public function updateFeedStalenessThreshold(): void
    {
        $this->validate([
            'feedStalenessThreshold' => 'required|integer|min:0',
        ]);

        Setting::setFeedStalenessThreshold($this->feedStalenessThreshold);
        $this->showSuccess();
    }

    public function updateDailyPublishCap(): void
    {
        $this->validate([
            'dailyPublishCap' => 'required|integer|min:0',
        ]);

        Setting::setDailyPublishCap($this->dailyPublishCap);
        $this->showSuccess();
    }

    protected function showSuccess(): void
    {
        $this->successMessage = 'Settings updated successfully!';
        $this->errorMessage = null;

        // Clear success message after 3 seconds
        $this->dispatch('clear-message');
    }

    public function clearMessages(): void
    {
        $this->successMessage = null;
        $this->errorMessage = null;
    }

    public function render(): View
    {
        return view('livewire.settings')->layout('layouts.app');
    }
}
