<?php

namespace App\Components\Contact\Admin;

use App\Enum\Contact\TemplateTriggerType;
use App\Models\Claim\Status;
use App\Models\Client\Client;
use App\Models\Claim\Claim;
use App\Models\Contact\ContactTemplate;
use App\Models\Contact\ContactTemplateTrigger;
use App\Models\Tag;
use Livewire\Component;

class TriggerManager extends Component
{
    public ?int $editingId = null;
    public array $form = [
        'contact_template_id' => null,
        'trigger_type' => 'status_changed',
        'model_type' => null,
        'conditions' => '{}',
        'dedupe_window_minutes' => 60,
        'is_active' => true,
    ];

    public array $conditionToStatusIds = [];
    public array $conditionFromStatusIds = [];
    public array $conditionTagIds = [];
    public bool $showAdvancedConditions = false;

    public function mount(): void
    {
        $this->authorize('communications.triggers.manage');
    }

    public function newTrigger(): void
    {
        $this->editingId = 0;
        $this->conditionToStatusIds = [];
        $this->conditionFromStatusIds = [];
        $this->conditionTagIds = [];
        $this->showAdvancedConditions = false;
    }

    public function edit(int $id): void
    {
        $t = ContactTemplateTrigger::findOrFail($id);
        $this->editingId = $t->id;
        $this->form = [
            'contact_template_id' => $t->contact_template_id,
            'trigger_type' => $t->trigger_type->value,
            'model_type' => $t->model_type,
            'conditions' => json_encode($t->conditions ?? new \stdClass(), JSON_PRETTY_PRINT),
            'dedupe_window_minutes' => $t->dedupe_window_minutes,
            'is_active' => (bool) $t->is_active,
        ];
        $this->loadConditionsIntoUi($t->conditions ?? []);
        $this->showAdvancedConditions = false;
    }

    public function updatedFormTriggerType(): void
    {
        $this->conditionToStatusIds = [];
        $this->conditionFromStatusIds = [];
        $this->conditionTagIds = [];
        $this->form['conditions'] = '{}';
        $this->showAdvancedConditions = false;
    }

    public function toggleAdvancedConditions(): void
    {
        $this->showAdvancedConditions = !$this->showAdvancedConditions;
        if ($this->showAdvancedConditions) {
            $this->form['conditions'] = json_encode($this->buildConditions(), JSON_PRETTY_PRINT);
        }
    }

    public function save(): void
    {
        $this->authorize('communications.triggers.manage');

        $data = $this->form;
        $data['trigger_type'] = TemplateTriggerType::from($data['trigger_type']);
        $data['conditions'] = $this->showAdvancedConditions
            ? (json_decode($data['conditions'] ?: '{}', true) ?: null)
            : ($this->buildConditions() ?: null);

        if ($this->editingId) {
            ContactTemplateTrigger::findOrFail($this->editingId)->update($data);
        } else {
            ContactTemplateTrigger::create($data);
        }

        $this->editingId = null;
        $this->reset('form');
        $this->conditionToStatusIds = [];
        $this->conditionFromStatusIds = [];
        $this->conditionTagIds = [];
        $this->showAdvancedConditions = false;
    }

    public function delete(int $id): void
    {
        $this->authorize('communications.triggers.manage');
        ContactTemplateTrigger::destroy($id);
    }

    private function buildConditions(): array
    {
        $type = $this->form['trigger_type'];
        $conditions = [];

        if ($type === TemplateTriggerType::STATUS_CHANGED->value) {
            if ($this->conditionToStatusIds) {
                $conditions['to_status_id'] = array_map('intval', $this->conditionToStatusIds);
            }
            if ($this->conditionFromStatusIds) {
                $conditions['from_status_id'] = array_map('intval', $this->conditionFromStatusIds);
            }
        } elseif (in_array($type, [TemplateTriggerType::TAG_ADDED->value, TemplateTriggerType::TAG_REMOVED->value])) {
            if ($this->conditionTagIds) {
                $conditions['tag_id'] = array_map('intval', $this->conditionTagIds);
            }
        }

        return $conditions;
    }

    private function loadConditionsIntoUi(array $conditions): void
    {
        $toStatus = $conditions['to_status_id'] ?? null;
        $this->conditionToStatusIds = is_array($toStatus)
            ? array_map('intval', $toStatus)
            : ($toStatus ? [(int) $toStatus] : []);

        $fromStatus = $conditions['from_status_id'] ?? null;
        $this->conditionFromStatusIds = is_array($fromStatus)
            ? array_map('intval', $fromStatus)
            : ($fromStatus ? [(int) $fromStatus] : []);

        $tagId = $conditions['tag_id'] ?? null;
        $this->conditionTagIds = is_array($tagId)
            ? array_map('intval', $tagId)
            : ($tagId ? [(int) $tagId] : []);
    }

    public function render()
    {
        return view('components.contact.admin.trigger-manager', [
            'triggers'       => ContactTemplateTrigger::with('template')->orderByDesc('id')->get(),
            'templates'      => ContactTemplate::where('allow_automatic_send', true)->orderBy('name')->get(),
            'triggerTypes'   => TemplateTriggerType::cases(),
            'statuses'       => Status::query()->orderBy('display_name')->get(['id', 'display_name']),
            'tags'           => Tag::query()->orderBy('name')->get(['id', 'name']),
            'statusMap'      => Status::query()->pluck('display_name', 'id'),
            'tagMap'         => Tag::query()->pluck('name', 'id'),
            'availableModels' => [
                ''            => 'Any record type',
                Client::class => 'Client / Claim',
            ],
        ]);
    }
}
