<?php

namespace App\Livewire\CampaignManager;

use App\Campaigns\Manager\Editing\AdvancedEditFields;
use App\Campaigns\Manager\Editing\EditCapabilities;
use App\Campaigns\Manager\Editing\EditRefused;
use App\Campaigns\Manager\Editing\EntityEditor;
use App\Campaigns\Manager\ManagedCampaigns;
use App\Campaigns\Manager\ManagerFormat;
use App\Models\Campaign;
use App\Models\CampaignEntityEdit;
use App\Models\CampaignPlatformEntity;
use App\Services\LinkedIn\LinkedIn;
use App\Services\LinkedIn\LinkedInUrn;
use App\Support\CurrencyMinorUnits;
use Illuminate\Contracts\View\View;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Locked;
use Livewire\Component;

/**
 * Change one platform object in three steps: edit, review, result. Deleting
 * or duplicating it goes through the same review and result steps.
 *
 * Which step is shown follows from the stored edit, not from anything the
 * browser sends, and every action re-checks that the campaign is the user's
 * and the object is in it. The ids are locked, so a forged payload cannot
 * point the wizard at another object.
 */
#[Layout('layouts.mb', ['pageTitle' => 'Campaign manager'])]
class EditEntity extends Component
{
    #[Locked]
    public int $campaignId;

    #[Locked]
    public int $entityId;

    #[Locked]
    public ?int $editId = null;

    /** @var array<string, mixed> */
    public array $values = [];

    /** The user ticked the confirmations shown on the review step. */
    public bool $acknowledged = false;

    public ?string $problem = null;

    public string $copyConversionEvent = '';

    /** @var array<string, string> */
    #[Locked]
    public array $conversionRuleOptions = [];

    public function mount(Campaign $campaign, CampaignPlatformEntity $entity): void
    {
        $this->campaignId = $this->owned($campaign->id)->id;
        abort_unless($entity->campaign_id === $this->campaignId, 404);

        $this->entityId = $entity->id;
        $this->editId = $entity->edits()
            ->where('user_id', auth()->id())
            ->where('state', CampaignEntityEdit::Proposed)
            ->latest('id')
            ->value('id');
        $this->fill(['values' => $this->currentValues($entity)]);
    }

    /** Step one to two: write the proposal down against what was last read. */
    public function review(EntityEditor $editor): void
    {
        $this->problem = null;
        $this->acknowledged = false;
        $this->resetErrorBag();
        $campaign = $this->owned($this->campaignId);
        $entity = $this->entity();
        $values = array_intersect_key($this->values, array_flip($this->shown($entity, app(EditCapabilities::class)->editableFields($entity))));
        $current = $this->currentValues($entity);
        foreach ($values as $field => $value) {
            if ($value === ($current[$field] ?? null)) {
                unset($values[$field]);
            }
        }

        try {
            $this->editId = $editor->propose($campaign, $entity, auth()->user(), $values)->id;
        } catch (ValidationException $exception) {
            foreach ($exception->errors() as $field => $messages) {
                $this->addError('values.'.$field, $messages[0]);
            }
        } catch (EditRefused|InvalidArgumentException $exception) {
            $this->problem = $exception->getMessage();
        }
    }

    /** Step one to two for a delete or a duplicate, instead of new values. */
    public function propose(string $action, EntityEditor $editor): void
    {
        $this->problem = null;
        $this->acknowledged = false;
        $this->resetErrorBag();

        try {
            $this->editId = $editor->proposeAction($this->owned($this->campaignId), $this->entity(), auth()->user(), $action)->id;
        } catch (EditRefused|InvalidArgumentException $exception) {
            $this->problem = $exception->getMessage();
        }

    }

    public function reviewEventCopy(EntityEditor $editor): void
    {
        $this->problem = null;
        $this->acknowledged = false;
        $this->resetErrorBag();
        try {
            $this->editId = $editor->proposeAction(
                $this->owned($this->campaignId), $this->entity(), auth()->user(),
                CampaignEntityEdit::Duplicate, ['conversion_event' => $this->copyConversionEvent],
            )->id;
        } catch (EditRefused|InvalidArgumentException $exception) {
            $this->problem = $exception->getMessage();
        }

    }

    public function loadConversionRules(LinkedIn $linkedin): void
    {
        $this->problem = null;
        $campaign = $this->owned($this->campaignId);
        abort_unless($campaign->platform === 'linkedin' && $this->entity()->entity_type === 'campaign', 404);
        try {
            $rules = $linkedin->on($campaign->id, 'User#'.auth()->id().' campaign manager')->conversions((string) $campaign->ad_account_id);
            $this->conversionRuleOptions = [];
            foreach ($rules as $rule) {
                $id = LinkedInUrn::numericId((string) ($rule['id'] ?? ''));
                if ($id === null) {
                    throw new EditRefused('LinkedIn returned a conversion rule without a usable ID.');
                }
                $this->conversionRuleOptions['urn:lla:llaPartnerConversion:'.$id] = (string) ($rule['name'] ?? $id);
            }
            if ($rules === []) {
                $this->problem = 'This account has no enabled conversion rules. Create or enable one in LinkedIn Campaign Manager first.';
            }
        } catch (\RuntimeException $exception) {
            $this->problem = 'Conversion rules could not be retrieved: '.$exception->getMessage();
        }
    }

    /** Step two back to one, keeping what was typed. */
    public function back(EntityEditor $editor): void
    {
        $this->problem = null;
        $this->acknowledged = false;

        if ($edit = $this->edit()) {
            $this->values = [...$this->values, ...$this->displayed($edit->entity, $edit->patch())];
            $editor->cancel($edit, auth()->user());
        }

        $this->editId = null;
    }

    /** Step two to three: the user's approval of exactly this patch. */
    public function confirm(EntityEditor $editor): void
    {
        $this->problem = null;
        $edit = $this->edit() ?? abort(404);

        try {
            $edit = $editor->apply($edit, auth()->user(), $this->acknowledged);
        } catch (EditRefused $exception) {
            $this->problem = $exception->getMessage();

            return;
        }

        // A deleted campaign has nothing left to manage, so its page is gone too.
        if (! ManagedCampaigns::query()->whereKey($this->campaignId)->exists()) {
            session()->flash('campaign-manager.status', sprintf('%s was deleted on %s.', $edit->campaign->name, ManagerFormat::platform($edit->platform)));
            $this->redirectRoute('campaign-manager.index', navigate: true);
        }
    }

    /** From a result back to a fresh first step, against the latest read. */
    public function startOver(): void
    {
        $this->problem = null;
        $this->acknowledged = false;
        $this->editId = null;
        $this->values = $this->currentValues($this->entity());
        $this->resetErrorBag();
    }

    public function render(EditCapabilities $capabilities): View
    {
        $campaign = $this->owned($this->campaignId)->load('latestSuccessfulSyncRun');
        $entity = $this->entity();
        $edit = $this->edit();
        $fields = $this->shown($entity, $capabilities->editableFields($entity));

        return view('livewire.campaign-manager.edit-entity', [
            'campaign' => $campaign,
            'entity' => $entity,
            'edit' => $edit,
            'step' => match (true) {
                $edit === null => 'edit',
                $edit->isOpen() => 'review',
                default => 'result',
            },
            'fields' => $fields,
            'locked' => $capabilities->lockedFields($entity),
            'hints' => array_filter(array_combine($fields, array_map(fn (string $field): ?string => $capabilities->hint($entity, $field), $fields))),
            'currency' => EditCapabilities::currency($entity),
            'confirmations' => match (true) {
                ! $edit?->isOpen() => [],
                $edit->isStructural() => $capabilities->actionConfirmations($entity, $edit->action, (array) $edit->details),
                default => $capabilities->confirmations($entity, $edit->changes),
            },
            'actions' => $capabilities->actions($entity),
            'eventCopyRefusal' => $capabilities->eventCopyRefusal($entity),
            'eventCopyOptions' => array_diff_key(EditCapabilities::options($entity, 'conversion_event'), [
                (string) data_get($entity->settings, 'promoted_object.custom_event_type') => true,
            ]),
            'actionSummary' => $edit?->isStructural() ? $capabilities->actionSummary($entity, $edit->action) : null,
            'copyCampaign' => $edit?->action === CampaignEntityEdit::Duplicate && isset($edit->details['copy_campaign_id'])
                ? ManagedCampaigns::query()->where('user_id', auth()->id())->find($edit->details['copy_campaign_id'])
                : null,
            'copy' => $edit?->action === CampaignEntityEdit::Duplicate && isset($edit->details['copy_entity_id'])
                ? CampaignPlatformEntity::query()->where('campaign_id', $this->campaignId)->find($edit->details['copy_entity_id'])
                : null,
            'refusal' => $capabilities->refusal($entity),
            'warning' => $capabilities->warning($entity),
        ])->layoutData(['pageTitle' => 'Edit - '.($entity->name ?: $entity->external_id)]);
    }

    private function owned(int $campaignId): Campaign
    {
        return ManagedCampaigns::query()
            ->where('user_id', auth()->id())
            ->findOrFail($campaignId);
    }

    private function entity(): CampaignPlatformEntity
    {
        return CampaignPlatformEntity::query()
            ->where('campaign_id', $this->campaignId)
            ->findOrFail($this->entityId);
    }

    private function edit(): ?CampaignEntityEdit
    {
        if ($this->editId === null) {
            return null;
        }

        return CampaignEntityEdit::query()
            ->where('campaign_platform_entity_id', $this->entityId)
            ->where('user_id', auth()->id())
            ->find($this->editId);
    }

    /**
     * The fields the form shows: an amount only when the bid strategy chosen
     * in it reads that amount.
     *
     * @param  list<string>  $fields
     * @return list<string>
     */
    private function shown(CampaignPlatformEntity $entity, array $fields): array
    {
        if (! in_array('bid_strategy', $fields, true)) {
            return $fields;
        }

        $strategy = $this->values['bid_strategy'] ?? EditCapabilities::current($entity, 'bid_strategy');
        $reads = EditCapabilities::strategyAmount($entity, is_string($strategy) ? $strategy : null)['field'] ?? null;

        return array_values(array_filter(
            $fields,
            fn (string $field): bool => $field === $reads || ! in_array($field, EditCapabilities::strategyAmounts($entity), true),
        ));
    }

    /** @return array<string, mixed> */
    private function currentValues(CampaignPlatformEntity $entity): array
    {
        $values = [];

        foreach (app(EditCapabilities::class)->editableFields($entity) as $field) {
            $values[$field] = EditCapabilities::current($entity, $field);
        }

        return $this->displayed($entity, $values);
    }

    /**
     * Values as they go in the form: money with the currency's decimals and no
     * thousands separator, so 25 reads as 25.00 and posts back as typed; an
     * end as a local date-time in the zone the platform reports it in;
     * countries as one comma-separated line.
     *
     * @param  array<string, mixed>  $values
     * @return array<string, mixed>
     */
    private function displayed(CampaignPlatformEntity $entity, array $values): array
    {
        $decimals = CurrencyMinorUnits::decimals(EditCapabilities::currency($entity));

        foreach ($values as $field => $value) {
            if ($field === 'conversion_rules') {
                $values[$field] = $value;
            } elseif (AdvancedEditFields::structured($field)) {
                $values[$field] = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
            } elseif (EditCapabilities::isMoney($field) && is_numeric($value)) {
                $values[$field] = number_format((float) $value, $decimals, '.', '');
            } elseif (EditCapabilities::isSchedule($field)) {
                $values[$field] = EditCapabilities::inputMoment($entity, $value) ?? '';
            } elseif ($field === 'countries' && is_array($value)) {
                $values[$field] = implode(', ', $value);
            }
        }

        return $values;
    }
}
