<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Components;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\Offer\Base;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Entity\Participant\ParticipantInterface;
use Ferienpass\CoreBundle\Enum\AttendanceStatus;
use Ferienpass\CoreBundle\Enum\AttendanceTransition;
use Ferienpass\CoreBundle\Notification\AttendanceNotificationChecker;
use Ferienpass\CoreBundle\Repository\ParticipantRepositoryInterface;
use Ferienpass\CoreBundle\Settings\SystemSettingsManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Uid\Uuid;
use Symfony\Component\Workflow\Exception\NotEnabledTransitionException;
use Symfony\Component\Workflow\WorkflowInterface;
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\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentToolsTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\TwigComponent\Attribute\ExposeInTemplate;

#[AsLiveComponent(route: 'live_component_admin')]
class OfferAssign extends AbstractController
{
    use ComponentToolsTrait;
    use DefaultActionTrait;

    /** @var Base */
    #[LiveProp(updateFromParent: true)]
    public OfferInterface $offer;

    #[LiveProp(updateFromParent: true)]
    public ?ParticipantInterface $participant = null;

    #[LiveProp(writable: true)]
    public bool $autoCommit = false;

    public bool $confirm = false;

    /** @var Attendance[] */
    #[ExposeInTemplate(name: 'attendances')]
    public array $notifiedAttendances = [];

    public ?string $notificationUuid = null;

    public function __construct(private readonly ParticipantRepositoryInterface $participants, private readonly SystemSettingsManager $systemSettingsManager, private readonly AttendanceNotificationChecker $notificationChecker)
    {
    }

    #[ExposeInTemplate]
    public function getPreferredPostalCodes(): array
    {
        return $this->systemSettingsManager->getPreferredPostalCodesArray();
    }

    #[LiveListener('selectParticipant')]
    public function selectParticipant(#[LiveArg] int $participant): void
    {
        $this->participant = $this->participants->createQueryBuilder('p')
            ->addSelect('p', 'u', 'u_blocked', 'address', 'duplicates', 'activity', 'createdBy')
            ->leftJoin('p.user', 'u')
            ->leftJoin('u.blockedContact', 'u_blocked')
            ->leftJoin('p.postalAddress', 'address')
            ->leftJoin('p.duplicates', 'duplicates')
            ->leftJoin('p.activity', 'activity')
            ->leftJoin('activity.createdBy', 'createdBy')
            ->where('p.id = :id')
            ->setParameter('id', $participant)
            ->getQuery()
            ->getOneOrNullResult();

        if ($this->participant) {
            $this->participants->createQueryBuilder('p')
                ->addSelect('p', 'a', 'o', 'e', 'd')
                ->leftJoin('p.attendances', 'a')
                ->leftJoin('a.offer', 'o')
                ->leftJoin('o.edition', 'e')
                ->leftJoin('o.dates', 'd')
                ->where('p.id = :id')
                ->setParameter('id', $participant)
                ->getQuery()
                ->getResult();
        }
    }

    #[LiveListener('unselectParticipant')]
    public function unselectParticipant(): void
    {
        $this->participant = null;
    }

    #[LiveAction]
    public function confirmAllWaiting(EntityManagerInterface $em, WorkflowInterface $attendanceStateMachine): void
    {
        $attendances = $this->offer->getAttendancesWaiting();

        $lastAttendance = $this->offer->getAttendancesConfirmed()->last();
        $sorting = $lastAttendance ? $lastAttendance->getSorting() : 0;

        if ($this->autoCommit && !$attendances->isEmpty()) {
            $this->notificationUuid = (string) Uuid::v7();
        }

        foreach ($attendances as $attendance) {
            try {
                $attendanceStateMachine->apply($attendance, AttendanceTransition::CONFIRM, [
                    'notify' => $this->autoCommit,
                    'reorder' => false,
                    'commit' => $this->autoCommit,
                    'group' => $this->notificationUuid,
                ]);

                if ($this->notificationUuid) {
                    $this->notifiedAttendances[] = $attendance;
                }

                $attendance->setSorting($sorting += 128);
            } catch (NotEnabledTransitionException) {
            }
        }

        if (!empty($this->notifiedAttendances)) {
            $this->confirm = \count($this->notifiedAttendances) > 0;
        }

        $em->flush();

        // Refresh because we changed the order of the attendances off-reference and that messes re-render
        $em->refresh($this->offer);
    }

    #[LiveAction]
    public function waitlistAllWaiting(EntityManagerInterface $em, WorkflowInterface $attendanceStateMachine): void
    {
        $attendances = $this->offer->getAttendancesWaiting();

        $lastAttendance = $this->offer->getAttendancesWaitlisted()->last();
        $sorting = $lastAttendance ? $lastAttendance->getSorting() : 0;

        foreach ($attendances as $attendance) {
            try {
                $attendanceStateMachine->apply($attendance, AttendanceTransition::WAITLIST, [
                    'notify' => $this->autoCommit,
                    'reorder' => false,
                    'commit' => $this->autoCommit,
                ]);

                $attendance->setSorting($sorting += 128);
            } catch (NotEnabledTransitionException) {
            }
        }

        $em->flush();

        // Refresh because we changed the order of the attendances off-reference and that messes re-render
        $em->refresh($this->offer);
    }

    #[LiveListener('statusChanged')]
    public function changeStatus(#[LiveArg] Attendance $attendance, #[LiveArg] string $newStatus, #[LiveArg] int $newIndex, EntityManagerInterface $em, WorkflowInterface $attendanceStateMachine): void
    {
        $this->denyAccessUnlessGranted('participants.view', $attendance->getOffer());

        if (!$attendance->getParticipant() instanceof ParticipantInterface) {
            return;
        }

        if ($newStatus === $attendance->getStatus()) {
            return;
        }

        $transition = match ($newStatus) {
            AttendanceStatus::CONFIRMED => AttendanceTransition::CONFIRM,
            AttendanceStatus::WAITLISTED => AttendanceTransition::WAITLIST,
            AttendanceStatus::WITHDRAWN => AttendanceTransition::WITHDRAW,
            AttendanceStatus::WAITING => AttendanceTransition::RESET,
            AttendanceStatus::REJECTED => AttendanceTransition::REJECT,
            default => null,
        };

        if (null === $transition) {
            return;
        }

        if ($this->autoCommit && $this->notificationChecker->shouldNotify($newStatus, false)) {
            $this->notificationUuid = (string) Uuid::v7();
        }

        try {
            $attendanceStateMachine->apply($attendance, $transition, [
                'notify' => $this->autoCommit,
                'reorder' => false,
                'commit' => $this->autoCommit,
                'group' => $this->notificationUuid,
            ]);

            if ($this->notificationUuid) {
                $this->notifiedAttendances[] = $attendance;
                $this->confirm = true;
            }

            $this->reorderList($attendance, $newIndex);

            $em->flush();

            // Refresh because we changed the order of the attendances off-reference and that messes re-render
            $em->refresh($this->offer);
        } catch (NotEnabledTransitionException) {
        }
    }

    #[LiveAction]
    public function change(#[LiveArg] Attendance $attendance, #[LiveArg] string $transition, EntityManagerInterface $em, WorkflowInterface $attendanceStateMachine): void
    {
        $this->denyAccessUnlessGranted('participants.view', $attendance->getOffer());

        if (!$attendance->getParticipant() instanceof ParticipantInterface) {
            return;
        }

        $newStatus = match ($transition) {
            AttendanceTransition::CONFIRM => AttendanceStatus::CONFIRMED,
            AttendanceTransition::REJECT => AttendanceStatus::REJECTED,
            default => null,
        };

        if ($this->autoCommit && $newStatus && $this->notificationChecker->shouldNotify($newStatus, false)) {
            $this->notificationUuid = (string) Uuid::v7();
        }

        try {
            $attendanceStateMachine->apply($attendance, $transition, [
                'notify' => $this->autoCommit,
                'reorder' => false,
                'commit' => $this->autoCommit,
                'group' => $this->notificationUuid,
            ]);

            if ($this->notificationUuid) {
                $this->notifiedAttendances[] = $attendance;
                $this->confirm = true;
            }

            $this->reorderList($attendance);

            $em->flush();

            // Refresh because we changed the order of the attendances off-reference and that messes re-render
            $em->refresh($this->offer);
        } catch (NotEnabledTransitionException) {
        }
    }

    #[LiveListener('indexUpdated')]
    public function changeIndex(#[LiveArg] Attendance $attendance, #[LiveArg] int $newIndex, EntityManagerInterface $em): void
    {
        $this->denyAccessUnlessGranted('participants.view', $attendance->getOffer());

        $this->reorderList($attendance, $newIndex);

        $em->flush();

        // Refresh because we changed the order of the attendances off-reference and that messes re-render
        $em->refresh($this->offer);
    }

    private function reorderList(Attendance $attendance, ?int $newIndex = null): void
    {
        /** @var Attendance[] $attendances */
        $attendances = array_values($attendance->getOffer()->getAttendancesWithStatus($attendance->getStatus())->toArray());
        $fromIndex = array_search($attendance, $attendances, true);

        if (null === $newIndex) {
            $newIndex = \count($attendances);
        }

        array_splice($attendances, $newIndex, 0, array_splice($attendances, $fromIndex, 1));

        $i = 0;
        foreach ($attendances as $a) {
            $a->setSorting(++$i * 128);
        }
    }
}
