<?php

namespace App\Livewire\Datatable\Studio\Catalog;

use App\Models\PriceRequest;
use App\Models\Product;
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 Illuminate\Support\Str;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use Rappasoft\LaravelLivewireTables\Views\Columns\ArrayColumn;

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

    protected $model = Product::class;

    protected ?int $refreshTime = 3000;

    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('name', 'like', "%{$searchTerm}%")
                        ->orWhere('sku', 'like', "%{$searchTerm}%");
                })
                ->html(),

            Column::make('Harga Beli', 'cost_price')
                ->label(function ($row) {
                    $canSeePrice = PriceRequest::where('user_id', auth()->id())
                        ->where('model', Product::class)
                        ->whereNotNull('approved_at')
                        ->where('expires_at', '>', now())
                        ->exists();

                    if ($canSeePrice) {
                        return currency($row->cost_price, 'Rp');
                    }

                    $masked = Str::mask(currency($row->cost_price, 'Rp'), '*', 2);

                    return Blade::render('
                        <flux:modal.trigger name="show-price">
                            <flux:text class="cursor-pointer text-gray-400 hover:text-gray-600">
                                {{ $masked }}
                            </flux:text>
                        </flux:modal.trigger>
                    ', ['masked' => $masked]);
                })
                ->searchable()
                ->sortable()
                ->html(),

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

            ArrayColumn::make('Outlet')
                ->data(
                    fn ($value, $row) => $row->outlets->map(fn ($outlet) => [
                        'id' => $outlet->hash,
                        'product_id' => $row->hash,
                        'name' => $outlet->name,
                        'stock' => currency($outlet->pivot->stock, ''),
                    ])->toArray()
                )
                ->outputFormat(function ($index, $value) {
                    $route = route('studio.catalog.product.audit', [$value['id'], $value['product_id']]);

                    return Blade::render('
                        <a href="{{ $route }}" wire:navigate
                            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>
                        </a>', [
                        'value' => $value,
                        'route' => $route,
                    ]);
                })
                ->flexRow(['class' => 'gap-2 flex-wrap']),

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

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

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

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

    public function builder(): Builder
    {
        return Product::select('products.id', 'sku', 'products.name', 'cost_price', 'sale_price')->with('outlets');
    }
}
