<?php

namespace App\Nova\Resources\Ecommerce\Product\Product\Concerns;

use App\Nova\Resources\Ecommerce\Channel\Channel;
use App\Nova\Resources\Ecommerce\Product\Brand\Brand;
use App\Nova\Resources\Ecommerce\Product\Category\Category;
use App\Nova\Resources\Ecommerce\Product\Collection\Collection;
use App\Nova\Resources\Ecommerce\Product\Product\Product as ProductResource;
use App\Nova\Resources\Ecommerce\Product\Product\ProductVariant;
use App\Nova\Resources\Ecommerce\Product\Review\Review;
use Ebess\AdvancedNovaMediaLibrary\Fields\Images;
use Illuminate\Support\Str;
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\Boolean;
use Laravel\Nova\Fields\HasMany;
use Laravel\Nova\Fields\ID;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Fields\Select;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Trix;
use Laravel\Nova\Http\Requests\NovaRequest;
use Milon\Barcode\Facades\DNS1DFacade;
use Nurmuhammet\DynamicFields\DynamicFields;
use Nurmuhammet\ProductInventory\ProductInventory;
use Outl1ne\MultiselectField\Multiselect;
use ShuvroRoy\NovaTabs\Tab;
use ShuvroRoy\NovaTabs\Tabs;
use Trin4ik\NovaSwitcher\NovaSwitcher;

class ProductFieldsForDetail
{
    /**
     * Get the fields displayed by the resource on detail page.
     */
    public static function make(ProductResource $resource, NovaRequest $request): array
    {
        // nova has a wierd bug, can load detail fields while on Index
        if (! $request->isResourceDetailRequest()) {
            if ($request->viaResource && $request->viaRelationship && $request->relationshipType) {

            } else {
                return [];
            }

            if ($request->viaResource === 'inventory-history-resources') {
                return [];
            }
        }

        return [
            ID::make(),
            Text::make(__('Name'), 'name'),

            Images::make(__('Image'), 'uploads')
                ->conversionOnIndexView('thumb400x400'),

            Trix::make(__('Description'), 'description')->withFiles('public')->alwaysShow(),
            Text::make(__('Price'), 'cost_amount'),
            Text::make(__('Price For Sale'), 'price_amount'),
            Text::make(__('Price without discount'), 'old_price_amount'),
            NovaSwitcher::make(__('Active'), 'is_visible')->canSeeWhen('isAdmin', $resource),

            Tabs::make('Main', [
                Tab::make(__('Product relations'), [
                    BelongsTo::make(__('Brand'), 'brand', Brand::class),

                    Multiselect::make(__('Channel'), 'channels')
                        ->belongsToMany(Channel::class)
                        ->canSeeWhen('isAdmin', $resource),

                    Multiselect::make(__('Category'), 'categories')->belongsToMany(Category::class),
                    Multiselect::make(__('Collection'), 'collections')->belongsToMany(Collection::class),
                ]),
                Tab::make(__('Inventory'), [
                    ProductInventory::make(
                        name: __('Inventory'),
                        attribute: fn () => $resource->inventories()
                            ->get(['inventories.name', 'inventories.id'])
                            ->map(fn ($inventory) => [
                                'name' => Str::title($inventory->name),
                                'value' => $inventory->pivot?->stock,
                            ])->toArray()
                    )->fullWidth(),

                    Text::make('SKU', 'sku'),

                    Text::make(__('Barcode'), function () use ($resource) {
                        if (! is_numeric($resource->barcode)) {
                            return;
                        }

                        return view('vendor.nova.products.barcode', [
                            'barcode' => $resource->barcode,
                            'image' => DNS1DFacade::getBarcodeHTML(
                                code: $resource->barcode,
                                type: config('barcode.default_type'),
                            ),
                        ])->render();
                    })->asHtml()->showWhen(boolval($resource->barcode)),

                    Text::make(__('Stock'), 'stock'),
                    Text::make(__('Security stock'), 'security_stock'),
                ]),
                Tab::make(__('Shipping'), [
                    Boolean::make(__('Back order'), 'back_order'),

                    Number::make(__('Weight value'), 'weight_value'),
                    Select::make(__('Weight unit'), 'weight_unit'),

                    Number::make(__('Height value'), 'height_value'),
                    Select::make(__('Height unit'), 'height_unit'),

                    Number::make(__('Width value'), 'width_value'),
                    Select::make(__('Width unit'), 'width_unit'),

                    Number::make(__('Depth value'), 'depth_value'),
                    Select::make(__('Depth unit'), 'depth_unit'),

                    Number::make(__('Volume value'), 'volume_value'),
                    Select::make(__('Volume unit'), 'volume_unit'),
                ]),
                Tab::make(__('SEO'), [
                    Text::make(__('Seo title'), 'seo_title'),
                    Text::make(__('Seo description'), 'seo_description'),
                ]),
            ]),

            Tabs::make(__('Properties'), [
                DynamicFields::make('Attributes', 'attributes')
                    ->fields(function () use ($resource) {
                        $attributes = $resource->properties()->with(['attribute.values', 'values.value'])->get()->map(fn ($property) => [
                            'label' => $property->attribute->name,
                            'name' => $property->attribute->slug,
                            'type' => $property->attribute->type,
                            'default' => $property->attribute->type === 'select'
                                            ? $property->values->first()->value?->id ?? '-'
                                            : $property->values->first()->product_custom_value ?? '-',
                            'options' => $property->attribute->values->map(fn ($value) => [
                                'label' => $value->value,
                                'value' => $value->id,
                            ])->toArray(),
                        ]);

                        return $attributes->toArray();
                    }),
            ]),

            HasMany::make(__('Variations'), 'variations', ProductVariant::class),
            HasMany::make(__('Reviews'), 'reviews', Review::class),
        ];
    }
}
