<?php

namespace App\Http\Livewire\WireChat;

use Illuminate\Support\Facades\Auth;
use Livewire\Component;
use Namu\WireChat\Models\Conversation;

class DisappearingMessagesSettings extends Component
{
    public $conversationId;
    public $conversation;
    public $isEnabled = false;
    public $selectedDuration;
    public $allowUsersToKeep = true;
    public $userControl = false;
    public $platformDuration;
    public $platformEnabled = true;

    protected $listeners = ['refreshDisappearing' => '$refresh'];

    // Multi-guard authentication support
    public function getAuthProperty()
    {
        return Auth::guard('admin')->user()
            ?: Auth::guard('bank')->user()
            ?: Auth::guard('organization')->user()
            ?: Auth::guard('web')->user();
    }

    public function mount($conversationId)
    {
        $this->conversationId = $conversationId;
        $this->conversation = Conversation::findOrFail($conversationId);

        // Check if user belongs to conversation
        $user = $this->auth;
        if (!$user || !$user->belongsToConversation($this->conversation)) {
            abort(403, 'You do not belong to this conversation');
        }

        // Load configuration
        $this->allowUsersToKeep = timebank_config('wirechat.disappearing_messages.allow_users_to_keep', true);
        $this->userControl = false; // Always false (hardcoded)
        $this->platformEnabled = true; // Always enabled (hardcoded)

        // Get duration in days and convert to seconds
        $durationInDays = timebank_config('wirechat.disappearing_messages.duration', 30);
        $this->platformDuration = $durationInDays * 86400; // Convert days to seconds

        // Load current settings
        $this->isEnabled = $this->conversation->hasDisappearingTurnedOn();
        $this->selectedDuration = $this->conversation->disappearing_duration ?? $this->platformDuration;

        // Auto-enable if not yet enabled for this conversation (always enabled)
        if (!$this->isEnabled) {
            $this->enablePlatformDefault();
        }
    }

    /**
     * Enable disappearing messages with platform default settings
     */
    private function enablePlatformDefault()
    {
        try {
            $this->conversation->turnOnDisappearing($this->platformDuration);
            $this->isEnabled = true;
            $this->selectedDuration = $this->platformDuration;
        } catch (\InvalidArgumentException $e) {
            // Silently fail - this will be shown in the UI
            \Log::warning("Failed to enable disappearing messages for conversation {$this->conversationId}: " . $e->getMessage());
        }
    }

    /**
     * Get human-readable duration
     */
    public function getFormattedDurationProperty()
    {
        $seconds = $this->selectedDuration ?? $this->platformDuration;

        $days = floor($seconds / 86400);
        if ($days > 0) {
            return trans_choice('messages.wirechat.duration.day', $days, ['count' => $days]);
        }

        $hours = floor($seconds / 3600);
        if ($hours > 0) {
            return trans_choice('messages.wirechat.duration.hour', $hours, ['count' => $hours]);
        }

        $minutes = floor($seconds / 60);
        if ($minutes > 0) {
            return trans_choice('messages.wirechat.duration.minute', $minutes, ['count' => $minutes]);
        }

        if ($seconds > 0) {
            return trans_choice('messages.wirechat.duration.second', $seconds, ['count' => $seconds]);
        }

        return 'Unknown';
    }

    /**
     * Get human-readable kept messages duration
     */
    public function getFormattedKeptDurationProperty()
    {
        $daysFromConfig = timebank_config('wirechat.disappearing_messages.kept_messages_duration');

        if ($daysFromConfig === null) {
            return null; // Never delete
        }

        // Config is now in days, so use directly
        $days = $daysFromConfig;

        // Convert to months/years if applicable
        // Check for years only if it's at least 2 full years (730 days)
        if ($days >= 730) {
            $years = floor($days / 365);
            return trans_choice('messages.wirechat.duration.year', $years, ['count' => $years]);
        }

        // For 30+ days but less than 2 years, show in months
        if ($days >= 30) {
            $months = floor($days / 30);
            return trans_choice('messages.wirechat.duration.month', $months, ['count' => $months]);
        }

        if ($days > 0) {
            return trans_choice('messages.wirechat.duration.day', $days, ['count' => $days]);
        }

        return 'Unknown';
    }

    public function render()
    {
        return view('livewire.wire-chat.disappearing-messages-settings');
    }
}
