<?php

namespace App\Livewire\Datatable\Catalog;

use App\Models\Perfume;
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 PerfumesTable extends DataTableComponent
{
    use WithAppendColumn, WithConfiguration, WithPrependColumn;

    protected $model = Perfume::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->sku}</span>
                        </div>
                    HTML;
                })
                ->searchable(function ($query, $searchTerm) {
                    $query->where('perfumes.name', 'like', "%{$searchTerm}%")
                        ->orWhere('sku', 'like', "%{$searchTerm}%");
                })
                ->html(),

            ArrayColumn::make('Kategori')
                ->data(fn ($value, $row) => $row->categories->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('Merek', 'brand.name')->searchable()->sortable(),

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

            Column::make('Harga Jual', 'sale_price')
                ->label(fn ($row, $column) => formatCurrencyNumber($row->sale_price, 'Rp'))
                ->searchable()
                ->sortable(),

            ArrayColumn::make('Outlet')
                ->data(
                    fn ($value, $row) => $row->outlets
                        ->filter(fn ($outlet) => auth()->user()->outlets->pluck('id')->contains($outlet->id))
                        ->map(fn ($outlet) => [
                            'id' => $outlet->hash,
                            'perfume_id' => $row->hash,
                            'name' => $outlet->name,
                            'stock' => formatCurrencyNumber($outlet->pivot->stock, ''),
                        ])->toArray()
                )
                ->outputFormat(function ($index, $value) {
                    $route = route('studio.catalog.perfume.audit', [$value['id'], $value['perfume_id']]);
                    $canAudit = auth()->user()->can('audit perfume');

                    $tag = ! $canAudit ? 'div' : 'a';
                    $attrs = ! $canAudit ? '' : 'href="'.$route.'" wire:navigate';

                    return Blade::render("
                        <{$tag} {$attrs}
                            class='flex items-center space-x-2 bg-gray-50 border border-gray-200 rounded-lg px-2 py-1 text-xs hover:bg-gray-100 transition'>
                            <span class='font-medium text-gray-700'>{{ \$value['name'] }}</span>
                            <span class='text-[10px] text-white bg-emerald-500 rounded px-1.5 py-0.5'>{{ \$value['stock'] }}</span>
                        </{$tag}>
                    ", [
                        'value' => $value,
                        'route' => $route,
                    ]);
                })
                ->flexRow(['class' => 'gap-2 flex-wrap']),

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

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

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

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

    public function builder(): Builder
    {
        return Perfume::select(
            'perfumes.id',
            'sku',
            'perfumes.name',
            'concentration',
            'cost_price',
            'sale_price'
        )
            ->with([
                'categories',
                'brand',
                'outlets',
            ])
            ->whereHas(
                'outlets',
                fn ($q) => $q->whereIn('outlets.id', auth()->user()->outlets()->pluck('outlets.id'))
            );
    }
}
