<?php

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Twig\Components\Modal;

use CpCreation\VitiCore\Media\Model\Image as MediaImage;
use CpCreation\VitiCore\Product\Model\Product;
use CpCreation\VitiCore\Product\Model\ProductImage;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\Attribute\LiveArg;
use Symfony\UX\LiveComponent\Attribute\LiveListener;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;

#[AsLiveComponent('modal:SimpleModalProductDetail', template: '@components/modal/SimpleModalProductDetail.html.twig')]
final class SimpleModalProductDetail
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    public ?string $id = 'product-detail-modal';
    public bool $open = false;
    public string $title = '';
    public string $subtitle = '';
    public string $dosage = '';
    public string $introText = '';
    public string $description = '';
    /** @var list<string> */
    public array $assemblages = [];
    /** @var list<array{path: string, width: ?int, height: ?int}> */
    public array $galleryImages = [];
    public ?string $imagePath = null;
    public ?string $filePath = null;

    #[LiveListener('productDetailModal:open')]
    public function openProductDetailModal(
        #[LiveArg('productId')] Product $product,
    ): void {
        $this->title = $product->getName() ?? '';
        $this->subtitle = $product->getQuality() ?? '';
        $this->dosage = $product->getDosage() ?? '';
        $this->introText = $product->getIntroText() ?? '';
        $this->description = $product->getDescription() ?? '';
        $this->assemblages = array_values(array_filter(
            $product->getAssemblages() ?? [],
            static fn (mixed $assemblage): bool => \is_string($assemblage) && '' !== trim($assemblage),
        ));
        $this->galleryImages = $this->buildGalleryImages($product);
        $this->imagePath = $this->galleryImages[0]['path'] ?? null;
        $this->filePath = $product->getFile()?->getPath();
        $this->open = true;
    }

    #[LiveAction]
    public function close(): void
    {
        $this->open = false;
    }

    /**
     * @return list<array{path: string, width: ?int, height: ?int}>
     */
    private function buildGalleryImages(Product $product): array
    {
        $galleryImages = [];
        $seenPaths = [];

        $primaryImage = $product->getSecondImage() ?? $product->getImage();
        if ($primaryImage instanceof MediaImage && $primaryImage->getPath()) {
            $galleryImages[] = [
                'path' => $primaryImage->getPath(),
                'width' => $primaryImage->getWidth(),
                'height' => $primaryImage->getHeight(),
            ];
            $seenPaths[$primaryImage->getPath()] = true;
        }

        $images = $product->getImages()->toArray();
        usort($images, static function (ProductImage $left, ProductImage $right): int {
            return ($left->getPosition() ?? PHP_INT_MAX) <=> ($right->getPosition() ?? PHP_INT_MAX);
        });

        foreach ($images as $image) {
            $media = $image->getImage();

            if (!$media instanceof MediaImage || !$media->getPath() || isset($seenPaths[$media->getPath()])) {
                continue;
            }

            $galleryImages[] = [
                'path' => $media->getPath(),
                'width' => $media->getWidth(),
                'height' => $media->getHeight(),
            ];
            $seenPaths[$media->getPath()] = true;
        }

        return $galleryImages;
    }
}
