<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Http\Resources\VehicleAction\FinanceFactory;
use App\Traits\HasPlaceholderImage;
use App\VehicleRepository;
use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\CatalogOffer;
use Mtc\MercuryDataModels\Events\LoadVehicleDataFields;
use Mtc\MercuryDataModels\Traits\HasVehicleCustomAttributes;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleView;

class VehicleList extends JsonResource
{
    use FranchiseData;
    use HasPlaceholderImage;
    use HasVehicleCustomAttributes;

    private Collection $placeholder;
    public function __construct(
        public $resource,
        private readonly ?CatalogOffer $catalogOffer = null,
        private readonly bool $include_cross_sell = false
    ) {
        parent::__construct($resource);
    }

    /**
     * Transform the resource collection into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $this->trackViews();
        if ($this->resource instanceof LengthAwarePaginator) {
            $this->resource
                ->through(fn($vehicle) => $this->mapVehicle($vehicle));
        } else {
            $this->resource = $this->resource
                ->map(fn($vehicle) => $this->mapVehicle($vehicle));
        }

        $resource = $this->resource->toArray();

        if ($this->catalogOffer) {
            $resource = $this->addCatalogOffer($resource, $this->catalogOffer);
        }

        if ($this->include_cross_sell) {
            $resource = $this->addCrossSell($resource);
        }

        return $resource;
    }

    public function mapVehicle(Vehicle $vehicle)
    {
        $data = [
            'id' => $vehicle->id,
            'title' => $vehicle->title,
            'derivative' => $vehicle->derivative,
            'slug' => $vehicle->slug,
            'is_new' => $vehicle->is_new,
            'is_sold' => $vehicle->is_sold,
            'is_demo' => $vehicle->is_demo,
            'is_reserved' => $vehicle->is_reserved,
            'price' => $vehicle->price,
            'make' => [
                'name' => $vehicle->make->name ?? '',
                'slug' => $vehicle->make->slug ?? '',
                'logo' => Settings::get('automotive-vehicle-brand-on-filter-card')
                    ? $vehicle->make->logo ?? ''
                    : null
            ],
            'location' => $this->locationValue($vehicle),
            'deposit' => $vehicle->deposit,
            'dealership' => $this->getDealership($vehicle),
            'fuel_type' => $vehicle->fuelType?->name,
            'body_style' => $vehicle->bodyStyle?->name,
            'transmission' => $vehicle->transmission?->name,
            'odometer_mi' => $vehicle->odometer_mi,
            'odometer_km' => $vehicle->odometer_km,
            'manufacture_year' => $vehicle->manufacture_year,
            'registration_number' => $vehicle->registration_number,
            'finance_example' => $this->getFinanceExample($vehicle),
            'model' => Settings::get('automotive-vehicle-model-on-filter-card')
                ? [
                    'name' => $vehicle->model->name ?? '',
                    'slug' => $vehicle->model->slug ?? '',
                ]
                : $vehicle->model?->name,
            'original_price' => $vehicle->original_price,
            'previous_price' => $vehicle->previous_price,
            'rrp_price' => $vehicle->rrp_price,
            'type' => $vehicle->type,
            'extra' => $this->getExtraData($vehicle),
            'seo' => $vehicle->seo,
            'age_identifier' => $vehicle->getAgeIdentifier(),
            'custom' => $vehicle->getAllCustom(),
            'monthly_price' => $vehicle->monthly_price,
            'monthly_cost_type' => $vehicle->getMonthlyCostType(),
            'labels' => Settings::get('vehicle-labels-enabled')
                ? $vehicle->labels->whereIn('type', ['', 'all', 'srp'])->values()
                : [],
            'engine_size_cc' => $vehicle->engine_size_cc,
            'is_vat_applicable' => $vehicle->is_vat_applicable,
            'coming_soon' => $vehicle->getComingSoonStatus(),
            'attention_grabber' => $vehicle->attention_grabber,
            'images_count' => $vehicle->image_count ?? 0,
            'features' => $vehicle->features->pluck('name'),
            'main_video_url' =>  $vehicle->main_video_url ?? '',
        ];

        if (!empty($vehicle->first_registration_date)) {
            $data['first_registration_date'] = $vehicle->first_registration_date->format('Y-m-d');
        }

        if (Settings::get('autotrader-advert-performance')) {
            $data['autoTraderData'] =  [
                'price_point' => $vehicle->autoTraderData?->price_point,
            ];
        }
        if (Settings::get('vehicle-card-image-count') > 1) {
            $data['gallery'] = $this->getGallery($vehicle, Settings::get('vehicle-card-image-count'));
        } else {
            $data['thumbnail'] = [
                'small' => $vehicle->primaryMediaUse?->getUrl($this->thumbnailImageDimensions())
                    ?? $this->getPlaceholder($vehicle, $this->thumbnailImageDimensions(isPlaceholder: true)),
                'medium' => $vehicle->primaryMediaUse?->getUrl($this->mediumImageDimensions())
                    ?? $this->getPlaceholder($vehicle, $this->mediumImageDimensions(isPlaceholder: true)),
            ];
        }

        if (Settings::get('vehicle-list-load-finance-calculator')) {
            $data['finance_calculator'] = (new FinanceFactory())->widget($vehicle);
            $data['finance_examples'] = (new VehicleResource($vehicle))->getFinanceExamples();
        }

        $data['reservation_amount'] = $vehicle->getReservationAmount();

        return $data;
    }

    protected function getFinanceExample(Vehicle $vehicle)
    {
        if (Settings::get('vehicle-list-load-finance-example')) {
            $type = Settings::get('vehicle-list-load-finance-example-type', 'cheapest');
            if ($type !== 'cheapest') {
                $example = $vehicle->financeExamples->where('finance_type', $type)->sortBy('monthly_price')->first();
                if ($example) {
                    $example->makeHidden([
                        'id',
                        'vehicle_id',
                        'provider',
                        'created_at',
                        'updated_at',
                    ]);
                    return $example;
                }
            }
            $vehicle->defaultFinanceExample?->makeHidden([
                'id',
                'vehicle_id',
                'provider',
                'created_at',
                'updated_at',
            ]);
            return $vehicle->defaultFinanceExample;
        }

        return null;
    }

    protected function getExtraData(Vehicle $vehicle)
    {
        return collect(event(new LoadVehicleDataFields($vehicle, 'ui')))
            ->filter()
            ->mapWithKeys(fn($field) => $field)
            ->merge($this->getCustomAttributes($vehicle));
    }

    protected function getDealership(Vehicle $vehicle)
    {
        if (empty($vehicle->dealership)) {
            return null;
        }

        $dealership = $vehicle->dealership->only([
            'contact_no',
            'email',
            'name',
            'slug',
        ]);

        if (!empty($vehicle->dealership->franchise)) {
            $franchise = $vehicle->dealership->franchise;
            $dealership['franchise'] = $franchise->only([
                'logo',
                'name',
                'slug',
            ]);
            if (!empty($franchise->primaryMediaUse)) {
                $dealership['franchise']['logo'] = $this->sizesForFranchise($franchise, $franchise->primaryMediaUse);
            }
        }

        return $dealership;
    }

    protected function locationValue(Vehicle $vehicle): string
    {
        if (tenant()->hasMultipleLocations()) {
            return $vehicle->dealership->name ?? '';
        }

        return '';
    }

    protected function trackViews(): void
    {
        /** @var Collection $ids */
        $ids = $this->resource->pluck('id');
        $existing = VehicleView::query()
            ->whereIn('vehicle_id', $ids)
            ->where('date', Carbon::now()->format('Y-m-d'))
            ->pluck('vehicle_id');

        $missing = $ids->reject(fn($id) => $existing->search($id));

        if ($missing->isNotEmpty()) {
            $data = $missing->map(fn ($id) => [
                'vehicle_id' => $id,
                'hits' => 0,
                'filter_views' => 1,
                'date' => Carbon::now()->format('Y-m-d'),
            ]);
            VehicleView::query()->upsert($data->toArray(), ['vehicle_id', 'date']);
        }

        VehicleView::query()
            ->whereIn('vehicle_id', $existing)
            ->increment('filter_views');
    }

    protected function largeImageDimensions(): string
    {
        return 'large';
    }

    protected function mediumImageDimensions(?bool $isPlaceholder = null): string
    {
        return $isPlaceholder
            ? config(config("automotive.placeholder_media_sizes.placeholder-image-vehicle"))['medium']
            : 'medium';
    }

    protected function thumbnailImageDimensions(?bool $isPlaceholder = null): string
    {
        return $isPlaceholder
            ? config(config("automotive.placeholder_media_sizes.placeholder-image-vehicle"))['medium']
            : 'tile';
    }

    protected function addCatalogOffer($resource, CatalogOffer $catalogOffer)
    {
        $image = null;
        if ($catalogOffer->primaryMediaUse?->media) {
            $image = $catalogOffer->primaryMediaUse->media->type === 'image'
                ? $catalogOffer->getPreviewImage('325x250')
                :  $catalogOffer->primaryMediaUse->media->getOriginalUrlAttribute();
        }

        array_splice(
            $resource['data'],
            rand(0, count($resource['data'])),
            0,
            [
                [
                    'id' => $catalogOffer->id,
                    'title' => $catalogOffer->name,
                    'subtitle' => $catalogOffer->subtitle,
                    'image' => $image,
                    'link' => $catalogOffer->link,
                    'button_text' => $catalogOffer->button_text,
                    'type' => 'catalog-offer',
                ]
            ]
        );

        return $resource;
    }

    protected function addCrossSell($resource)
    {
        $crossSell = [];

        if (
            !empty($resource['data'])
            && Settings::get('vehicles-cross-sell-enabled')
            && in_array(Settings::get('vehicles-cross-sell-location', ''), ['all', 'srp'])
        ) {
            $vehicle_array = reset($resource['data']);

            $vehicle = Vehicle::query()->find($vehicle_array['id']);
            $crossSell =  $vehicle
                ? [
                    'name' => __('automotive.cross-sell.similar'),
                    'items' => App::make(VehicleRepository::class)
                        ->similar(
                            $vehicle,
                            request('cross-sell-count', 3),
                            Settings::get('vehicles-cross-sell-type')
                        )
                        ->toArray(null),
                ]
                : [];
        }

        $resource['cross_sell'] = $crossSell;

        return $resource;
    }
}
