<?php

namespace App\Components\Report;

use App\Models\Report\ManagementReportRecipient;
use Illuminate\Validation\Rule;
use Livewire\Component;

class ManagementReportSettings extends Component
{
    public ?int $editingId = null;

    public string $name = '';

    public string $emailAddress = '';

    public bool $isActive = true;

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

        $user = auth()->user();
        abort_unless($user?->isPlatformUser(), 403, 'Only platform managers can manage global report recipients.');
    }

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

        $this->emailAddress = strtolower(trim($this->emailAddress));
        $data = $this->validate([
            'name' => ['nullable', 'string', 'max:255'],
            'emailAddress' => [
                'required',
                'email',
                'max:255',
                Rule::unique('management_report_recipients', 'email_address')
                    ->ignore($this->editingId),
            ],
            'isActive' => ['boolean'],
        ]);

        $values = [
            'name' => filled($data['name']) ? trim($data['name']) : null,
            'email_address' => $data['emailAddress'],
            'is_active' => $data['isActive'],
        ];

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

        $this->resetForm();
        session()->flash('success', 'Management report recipient saved.');
    }

    public function edit(int $id): void
    {
        $this->authorize('communications.settings.manage');
        $recipient = ManagementReportRecipient::findOrFail($id);

        $this->editingId = $recipient->id;
        $this->name = $recipient->name ?? '';
        $this->emailAddress = $recipient->email_address;
        $this->isActive = $recipient->is_active;
    }

    public function toggle(int $id): void
    {
        $this->authorize('communications.settings.manage');
        $recipient = ManagementReportRecipient::findOrFail($id);
        $recipient->update(['is_active' => ! $recipient->is_active]);
    }

    public function delete(int $id): void
    {
        $this->authorize('communications.settings.manage');
        ManagementReportRecipient::findOrFail($id)->delete();

        if ($this->editingId === $id) {
            $this->resetForm();
        }
    }

    public function cancelEdit(): void
    {
        $this->resetForm();
    }

    public function render()
    {
        return view('components.report.management-report-settings', [
            'recipients' => ManagementReportRecipient::query()
                ->orderByDesc('is_active')
                ->orderBy('name')
                ->orderBy('email_address')
                ->get(),
        ]);
    }

    private function resetForm(): void
    {
        $this->reset(['editingId', 'name', 'emailAddress']);
        $this->isActive = true;
        $this->resetValidation();
    }
}
