<?php

namespace App\Components\Solicitor;

use App\Models\Solicitor\Solicitor;
use App\Models\Solicitor\SolicitorEmailSender;
use App\Services\HistoryService;
use Livewire\Component;

class EmailSenders extends Component {
    public Solicitor $solicitor;

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

    public string $display_name  = '';
    public string $email_address = '';
    public string $purpose       = 'general';
    public bool   $is_default    = false;
    public string $signature     = '';

    public static array $purposes = [
        'dsar'    => 'DSAR',
        'client'  => 'Client',
        'general' => 'General',
    ];

    protected function rules(): array {
        return [
            'display_name'  => ['required', 'string', 'max:255'],
            'email_address' => ['required', 'email', 'max:255'],
            'purpose'       => ['required', 'string', 'in:' . implode(',', array_keys(self::$purposes))],
            'is_default'    => ['boolean'],
            'signature'     => ['nullable', 'string'],
        ];
    }

    public function showAdd(): void {
        $this->reset('display_name', 'email_address', 'purpose', 'is_default', 'signature', 'editing', 'editingId');
        $this->purpose = 'general';
        $this->show    = true;
    }

    public function hideAdd(): void {
        $this->reset('display_name', 'email_address', 'purpose', 'is_default', 'signature', 'editing', 'editingId');
        $this->show = false;
    }

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

        $this->display_name  = $sender->display_name;
        $this->email_address = (string) $sender->email_address;
        $this->purpose       = $sender->purpose;
        $this->is_default    = $sender->is_default;
        $this->signature     = $sender->signature ?? '';
        $this->editing       = true;
        $this->editingId     = $id;
        $this->show          = true;
    }

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

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

        if ($this->editing && $this->editingId) {
            $sender = $this->solicitor->emailSenders()->findOrFail($this->editingId);
            $sender->update($data);
            $action = 'updated';
        } else {
            $sender = $this->solicitor->emailSenders()->create($data);
            $action = 'added';
        }

        $history->add($this->solicitor, 'Email sender "' . $data['email_address'] . '" ' . $action, [
            'sender_id'     => $sender->id,
            'display_name'  => $data['display_name'],
            'email_address' => $data['email_address'],
            'purpose'       => $data['purpose'],
            'is_default'    => (bool) $data['is_default'],
        ]);

        $this->hideAdd();
    }

    public function makeDefault(int $id, HistoryService $history): void {
        $this->authorize('solicitors.edit');
        $sender = $this->solicitor->emailSenders()->findOrFail($id);

        $this->solicitor->emailSenders()
            ->where('purpose', $sender->purpose)
            ->update(['is_default' => false]);

        $sender->update(['is_default' => true]);

        $history->add($this->solicitor, 'Email sender "' . $sender->email_address . '" set as default for ' . $sender->purpose, [
            'sender_id' => $sender->id,
            'purpose'   => $sender->purpose,
        ]);
    }

    public function deleteSender(int $id, HistoryService $history): void {
        $this->authorize('solicitors.edit');
        $sender = $this->solicitor->emailSenders()->findOrFail($id);
        $context = [
            'sender_id'     => $sender->id,
            'email_address' => $sender->email_address,
            'purpose'       => $sender->purpose,
        ];
        $sender->delete();

        $history->add($this->solicitor, 'Email sender "' . $context['email_address'] . '" deleted', $context);

        $this->hideAdd();
    }

    public function render() {
        return view('components.solicitor.email-senders', [
            'senders'  => $this->solicitor->emailSenders()->orderBy('purpose')->orderByDesc('is_default')->get(),
            'purposes' => self::$purposes,
        ]);
    }
}
