<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Admin;

use CpCreation\VitiCore\Bridge\Symfony\Bundle\Form\Admin\InformationBlockType;
use CpCreation\VitiCore\Shop\Model\InformationBlock;
use CpCreation\VitiCore\Shop\Repository\InformationBlockRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/boutique/informations')]
#[IsGranted(new Expression("is_granted('ROLE_ADMIN')"))]
final class InformationBlockController extends AbstractController
{
    public function __construct(
        private readonly InformationBlockRepository $informationBlockRepository,
    ) {
    }

    #[Route('', name: 'admin_shop_information_block')]
    public function index(): Response
    {
        return $this->render('@CpCreationVitiCore/admin/information_block/index.html.twig', [
            'items' => $this->informationBlockRepository->findByPositionOrderAdmin(),
        ]);
    }

    #[Route('/new', name: 'admin_shop_information_block_new')]
    public function new(Request $request): Response
    {
        $informationBlock = new InformationBlock();
        $form = $this->createForm(InformationBlockType::class, $informationBlock);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var InformationBlock $data */
            $data = $form->getData();
            $this->validateZoneCapacity($form, $data);

            if (!$form->isValid()) {
                return $this->render('@CpCreationVitiCore/admin/information_block/new.html.twig', [
                    'form' => $form->createView(),
                ]);
            }

            $this->informationBlockRepository->prepareForSave($data);
            $this->informationBlockRepository->save($data);

            $this->addFlash('alert-success', 'Le bloc d’information '.$data->getTitle().' a été ajouté avec succès.');

            return $this->redirectToRoute('admin_shop_information_block');
        }

        return $this->render('@CpCreationVitiCore/admin/information_block/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/edit', name: 'admin_shop_information_block_edit')]
    public function edit(InformationBlock $informationBlock, Request $request): Response
    {
        $previousZone = $informationBlock->getDisplayZone();
        $form = $this->createForm(InformationBlockType::class, $informationBlock);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var InformationBlock $data */
            $data = $form->getData();
            $this->validateZoneCapacity($form, $data);

            if (!$form->isValid()) {
                return $this->render('@CpCreationVitiCore/admin/information_block/edit.html.twig', [
                    'item' => $informationBlock,
                    'form' => $form->createView(),
                ]);
            }

            $this->informationBlockRepository->prepareForSave($data, $previousZone);
            $this->informationBlockRepository->save($data);

            $this->addFlash('alert-success', 'Le bloc d’information '.$data->getTitle().' a été modifié avec succès.');

            return $this->redirectToRoute('admin_shop_information_block');
        }

        return $this->render('@CpCreationVitiCore/admin/information_block/edit.html.twig', [
            'item' => $informationBlock,
            'form' => $form->createView(),
        ]);
    }

    #[Route('/{id}/delete', name: 'admin_shop_information_block_delete')]
    public function delete(InformationBlock $informationBlock): RedirectResponse
    {
        $title = $informationBlock->getTitle();
        $this->informationBlockRepository->delete($informationBlock);

        $this->addFlash('alert-success', 'Le bloc d’information '.$title.' a été supprimé avec succès.');

        return $this->redirectToRoute('admin_shop_information_block');
    }

    #[Route('/{id}/move-up', name: 'admin_shop_information_block_move_up')]
    public function moveUp(InformationBlock $informationBlock): RedirectResponse
    {
        $this->informationBlockRepository->moveUp($informationBlock);

        return $this->redirectToRoute('admin_shop_information_block');
    }

    #[Route('/{id}/move-down', name: 'admin_shop_information_block_move_down')]
    public function moveDown(InformationBlock $informationBlock): RedirectResponse
    {
        $this->informationBlockRepository->moveDown($informationBlock);

        return $this->redirectToRoute('admin_shop_information_block');
    }

    #[Route('/{id}/disable', name: 'admin_shop_information_block_disable')]
    public function disable(InformationBlock $informationBlock): RedirectResponse
    {
        $this->informationBlockRepository->disable($informationBlock);

        return $this->redirectToRoute('admin_shop_information_block');
    }

    #[Route('/{id}/enable', name: 'admin_shop_information_block_enable')]
    public function enable(InformationBlock $informationBlock): RedirectResponse
    {
        if ($this->informationBlockRepository->countActiveInZone($informationBlock->getDisplayZone(), $informationBlock) >= 3) {
            $this->addFlash('alert-danger', 'La zone sélectionnée contient déjà 3 blocs publiés.');

            return $this->redirectToRoute('admin_shop_information_block');
        }

        $this->informationBlockRepository->enable($informationBlock);

        return $this->redirectToRoute('admin_shop_information_block');
    }

    private function validateZoneCapacity(FormInterface $form, InformationBlock $informationBlock): void
    {
        if ($informationBlock->isDisabled()) {
            return;
        }

        if ($this->informationBlockRepository->countActiveInZone($informationBlock->getDisplayZone(), $informationBlock) < 3) {
            return;
        }

        $form->get('displayZone')->addError(
            new FormError('Cette zone contient déjà 3 blocs publiés. Dépubliez ou déplacez un bloc existant avant d’en ajouter un nouveau.')
        );
    }
}
