<?php

namespace App\Livewire\Member;

use App\Models\Membership as MembershipModel;
use App\Models\Tier;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Membership')]
#[Layout('components.layouts.member')]
class Membership extends Component
{
    public ?MembershipModel $membership = null;

    public array $stats = [];

    public string $nextTierName = '';

    public string $currentSpending = '';

    public string $nextTierSpending = '';

    public string $progress = '0';

    public function mount(): void
    {
        $this->membership = MembershipModel::with(['tier'])->where('user_id', auth()->id())->first();

        if (! $this->membership) {
            return;
        }

        $nextTier = Tier::where('min_spending', '>', $this->membership->total_spending)
            ->orderBy('min_spending', 'asc')
            ->first();

        $this->nextTierName = $nextTier ? $nextTier->name : 'Maksimal';

        $this->currentSpending = formatCurrencyNumber($this->membership->total_spending, 'Rp');

        $this->nextTierSpending = $nextTier ? formatCurrencyNumber($nextTier->min_spending, 'Rp') : 'Maksimal';

        if ($nextTier) {
            $this->progress = ($this->membership->total_spending / $nextTier->min_spending) * 100;
        } else {
            $this->progress = '100';
        }

        $this->stats = [
            [
                'title' => 'Poin Hadiah',
                'value' => formatCurrencyNumber($this->membership->reward_points, ''),
                'description' => 'Gunakan poin untuk hadiah menarik',
            ],
            [
                'title' => 'Tier Sekarang',
                'value' => $this->membership->tier->name,
                'description' => 'Terdaftar sejak '.formatDateLocalized($this->membership->created_at),
            ],
            [
                'title' => 'Total Belanja',
                'value' => formatCurrencyNumber($this->membership->total_spending, 'Rp'),
                'description' => 'Akumulasi seluruh transaksi',
            ],
            [
                'title' => 'Tier Selanjutnya',
                'value' => $nextTier ? $nextTier->name : 'Maksimal',
                'description' => $nextTier ? formatCurrencyNumber($nextTier->min_spending - $this->membership->total_spending, 'Rp').' lagi' : 'Anda sudah berada di tier tertinggi',
            ],
        ];
    }

    public function render(): View
    {
        return view('livewire.member.memberships', [
            'pageTitle' => 'Membership',
        ]);
    }
}
