<?php

namespace App\Livewire\Datatable\Loyalty;

use App\Models\Voucher;
use App\Traits\Datatable\WithAppendColumn;
use App\Traits\Datatable\WithConfiguration;
use App\Traits\Datatable\WithPrependColumn;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Blade;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Columns\ArrayColumn;

class VouchersTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithPrependColumn;

    protected $model = Voucher::class;

    public function columns(): array
    {
        return [
            Column::make('Nama')
                ->label(function ($row) {
                    return <<<HTML
                        <div>
                            <div>{$row->name}</div>
                            <span class="text-xs text-gray-400">{$row->code}</span>
                        </div>
                    HTML;
                })
                ->searchable(function ($query, $searchTerm) {
                    $query->where('name', 'like', "%{$searchTerm}%")
                        ->orWhere('code', 'like', "%{$searchTerm}%");
                })
                ->html(),

            Column::make('Tags', 'tags')
                ->searchable()
                ->sortable(),

            Column::make('Min. Belanja', 'min_purchase')
                ->format(fn ($value) => formatCurrencyNumber($value, 'Rp'))
                ->searchable()
                ->sortable(),

            ArrayColumn::make('Tier')
                ->data(
                    fn ($value, $row) => $row->tiers->pluck('name')->toArray() ?: ['Semua Tier']
                )
                ->outputFormat(fn ($index, $value) => Blade::render('<span class="text-xs text-gray-400 border border-gray-400 rounded px-1">'.$value.'</span>'))
                ->flexRow(['class' => 'gap-2 flex-wrap']),

            Column::make('Jumlah Diskon', 'discount_amount')
                ->label(fn ($row, $column) => formatDiscount($row->discount_amount, $row->type))
                ->searchable()
                ->sortable(),

            Column::make('Maks. Diskon')
                ->label(fn ($row, $column) => formatCurrencyNumber($row->max_discount, 'Rp'))
                ->searchable()
                ->sortable(),

            Column::make('Kuota / Sisa Voucher')
                ->label(function ($record) {
                    $quota = $record->quota
                        ? formatCurrencyNumber($record->quota)
                        : 'Tidak Terbatas';

                    $available = $record->available_count
                        ? formatCurrencyNumber($record->available_count)
                        : 'Tidak Terbatas';

                    return "{$quota} / {$available}";
                })
                ->searchable()
                ->sortable(),

            Column::make('Batas Per Pembeli', 'limit_per_user')
                ->format(fn ($value) => $value ? formatCurrencyNumber($value) : 'Tidak Terbatas')
                ->searchable()
                ->sortable(),

            ArrayColumn::make('Outlet')
                ->data(
                    fn ($value, $row) => $row->outlets->pluck('name')->toArray()
                )
                ->outputFormat(fn ($index, $value) => Blade::render('<span class="text-xs text-gray-400 border border-gray-400 rounded px-1">'.$value.'</span>'))
                ->flexRow(['class' => 'gap-2 flex-wrap']),

            Column::make('Visibilitas', 'is_show')
                ->label(fn ($row, $column) => Blade::render('<flux:badge color="'.$row->is_show->color().'">'.$row->is_show->label().'</flux:badge>'))
                ->html(),

            Column::make('Tanggal')
                ->label(function ($row) {
                    $startDate = formatDateLocalized($row->start_date);
                    $startAgo = formatRelativeTime($row->start_date);

                    $endDate = formatDateLocalized($row->end_date);
                    $endAgo = formatRelativeTime($row->end_date);

                    return <<<HTML
                        <div class="flex flex-col text-xs text-gray-700 dark:text-gray-300 gap-0.5">
                            <div>
                                <span class="font-medium text-gray-900 dark:text-white">Tgl Dimulai:</span>
                                <span>{$startDate}</span>
                                <span class="text-gray-500">({$startAgo})</span>
                            </div>
                            <div>
                                <span class="font-medium text-gray-900 dark:text-white">Tgl Berakhir:</span>
                                <span>{$endDate}</span>
                                <span class="text-gray-500">({$endAgo})</span>
                            </div>
                        </div>
                    HTML;
                })
                ->html(),

            Column::make('Aksi')
                ->label(function ($row) {
                    $actions = '';

                    if (auth()->user()->can('update voucher')) {
                        $actions .= view('components.actions.table.edit', [
                            'id' => $row->hash,
                            'editRoute' => route('studio.loyalty.voucher.edit', $row->hash),
                        ])->render();
                    }

                    if (auth()->user()->can('delete voucher')) {
                        $actions .= view('components.actions.table.delete', [
                            'id' => $row->hash,
                        ])->render();
                    }

                    return $actions;
                })
                ->html()
                ->hideIf(auth()->user()->cannot('update voucher') && auth()->user()->cannot('delete voucher')),
        ];
    }

    public function builder(): Builder
    {
        return Voucher::select('vouchers.id', 'vouchers.name', 'code', 'tags', 'min_purchase', 'discount_amount', 'max_discount', 'quota', 'available_count', 'limit_per_user', 'start_date', 'end_date', 'type', 'is_show', 'vouchers.created_at')
            ->with(['outlets', 'tiers'])
            ->whereHas(
                'outlets',
                fn ($q) => $q->whereIn('outlets.id', auth()->user()->outlets()->pluck('outlets.id'))
            );
    }
}
