<?php

namespace App\Livewire\Datatable\Studio\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('Min. Belanja', 'min_purchase')
                ->format(fn ($value) => currency($value, 'Rp'))
                ->searchable()
                ->sortable(),

            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) => currency($row->max_discount, 'Rp'))
                ->searchable()
                ->sortable(),

            Column::make('Kuota', 'quota')
                ->format(fn ($value) => $value ? currency($value) : 'Tidak Terbatas')
                ->searchable()
                ->sortable(),

            Column::make('Sisa Voucher', 'available_count')
                ->format(fn ($value) => $value ? currency($value) : 'Tidak Terbatas')
                ->searchable()
                ->sortable(),

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

            ArrayColumn::make('Outlet')
                ->data(
                    fn ($value, $row) => $row->outlets->map(fn ($outlet) => [
                        'name' => $outlet->name,
                        'stock' => currency($outlet->pivot->stock, ''),
                    ])->toArray()
                )
                ->outputFormat(fn ($index, $value) => Blade::render('
                    <div class="flex items-center space-x-2 bg-gray-50 border border-gray-200 rounded-lg px-2 py-1 text-xs">
                        <span class="font-medium text-gray-700">{{ $value["name"] }}</span>
                    </div>', ['value' => $value]))
                ->flexRow(['class' => 'gap-2 flex-wrap']),

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

                    $endDate = formatDate($row->end_date);
                    $endAgo = timeAgo($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.datatables.edit', [
                            'id' => $row->hash,
                            'editRoute' => route('studio.loyalty.voucher.edit', $row->hash),
                        ])->render();
                    }

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

                    return $actions;
                })
                ->html(),
        ];
    }

    public function builder(): Builder
    {
        return Voucher::select('id', 'name', 'code', 'min_purchase', 'discount_amount', 'max_discount', 'quota', 'available_count', 'limit_per_user', 'start_date', 'end_date', 'type', 'created_at')->with('outlets');
    }
}
