<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use App\Models\Solicitor\SolicitorSmsSender;
use App\ValueObjects\PhoneNumber;
use Livewire\Component;

class SmsSenders extends Component
{
    public Solicitor $solicitor;

    public bool $show = false;
    public bool $editing = false;
    public ?int $editingId = null;

    public string $label = '';
    public string $type = SolicitorSmsSender::TYPE_NUMBER;
    public string $value = '';
    public bool $is_default = false;
    public bool $is_active = true;
    public ?string $twilio_subaccount_sid = null;
    public ?string $twilio_phone_number_sid = null;

    public static array $types = [
        SolicitorSmsSender::TYPE_NUMBER => 'Phone number',
        SolicitorSmsSender::TYPE_ALPHA_TAG => 'Alpha tag (sender ID)',
    ];

    protected function rules(): array
    {
        $valueRules = ['required', 'string'];

        if ($this->type === SolicitorSmsSender::TYPE_ALPHA_TAG) {
            // Alpha tag: 1-11 chars, alphanumeric + spaces only.
            $valueRules[] = 'max:11';
            $valueRules[] = 'regex:/^[A-Za-z0-9 ]+$/';
        } else {
            // Number: must parse as a UK phone (or generally any phone via try).
            $valueRules[] = 'max:30';
        }

        return [
            'label' => ['required', 'string', 'max:100'],
            'type' => ['required', 'string', 'in:' . implode(',', array_keys(self::$types))],
            'value' => $valueRules,
            'is_default' => ['boolean'],
            'is_active' => ['boolean'],
            'twilio_subaccount_sid' => ['nullable', 'string', 'max:64'],
            'twilio_phone_number_sid' => ['nullable', 'string', 'max:64'],
        ];
    }

    protected function messages(): array
    {
        return [
            'value.regex' => 'Alpha tags can only contain letters, digits and spaces.',
            'value.max' => 'Alpha tags must be 11 characters or fewer.',
        ];
    }

    public function showAdd(): void
    {
        $this->resetForm();
        $this->show = true;
    }

    public function hideAdd(): void
    {
        $this->resetForm();
        $this->show = false;
    }

    public function loadSender(int $id): void
    {
        $sender = $this->solicitor->smsSenders()->findOrFail($id);

        $this->editing = true;
        $this->editingId = $id;
        $this->label = $sender->label;
        $this->type = $sender->type;
        $this->value = $sender->value;
        $this->is_default = $sender->is_default;
        $this->is_active = $sender->is_active;
        $this->twilio_subaccount_sid = $sender->twilio_subaccount_sid;
        $this->twilio_phone_number_sid = $sender->twilio_phone_number_sid;
        $this->show = true;
    }

    public function save(): void
    {
        $this->authorize('solicitors.edit');
        $data = $this->validate();

        // For numbers, validate it parses as a UK phone.
        if ($data['type'] === SolicitorSmsSender::TYPE_NUMBER) {
            $phone = PhoneNumber::tryFrom($data['value']);
            if (!$phone) {
                $this->addError('value', 'Phone number is not a valid UK number.');
                return;
            }
        }

        if ($data['is_default']) {
            $this->solicitor->smsSenders()
                ->where('id', '!=', $this->editingId ?? 0)
                ->update(['is_default' => false]);
        }

        if ($this->editing && $this->editingId) {
            $this->solicitor->smsSenders()->findOrFail($this->editingId)->update($data);
        } else {
            $this->solicitor->smsSenders()->create($data);
        }

        $this->hideAdd();
    }

    public function makeDefault(int $id): void
    {
        $this->authorize('solicitors.edit');
        $this->solicitor->smsSenders()->update(['is_default' => false]);
        $this->solicitor->smsSenders()->findOrFail($id)->update(['is_default' => true]);
    }

    public function toggleActive(int $id): void
    {
        $this->authorize('solicitors.edit');
        $sender = $this->solicitor->smsSenders()->findOrFail($id);
        $sender->update(['is_active' => !$sender->is_active]);
    }

    public function deleteSender(int $id): void
    {
        $this->authorize('solicitors.edit');
        $this->solicitor->smsSenders()->findOrFail($id)->delete();
        $this->hideAdd();
    }

    public function render()
    {
        return view('components.solicitor.sms-senders', [
            'senders' => $this->solicitor->smsSenders()->orderByDesc('is_default')->orderBy('label')->get(),
            'types' => self::$types,
        ]);
    }

    private function resetForm(): void
    {
        $this->reset([
            'label', 'value', 'is_default', 'is_active',
            'twilio_subaccount_sid', 'twilio_phone_number_sid',
            'editing', 'editingId',
        ]);
        $this->type = SolicitorSmsSender::TYPE_NUMBER;
        $this->is_active = true;
    }
}
