<?php

namespace App\Components\Claim\Application;

use App\Actions\Communications\EvaluateContactTriggersAction;
use App\Enum\Contact\TemplateTriggerType;
use App\Models\Client\Client;
use App\Services\AppMilestoneService;
use App\Services\ApplicationService;
use App\Services\EsignService;
use App\Services\WipService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Log;
use Livewire\Component;

class Application extends Component {
    use AuthorizesRequests;

    public Client $client;
    public $activeTab = 'care-settings';

    public $tabs = [
        'personal-details' => ['label' => 'Section 1 - Personal Details', 'icon' => 'bi-heart-pulse'],
        'contact-preferences' => ['label' => 'Section 2 - Contacting Client', 'icon' => 'bi-heart-pulse'],
        'confirm-identity' => ['label' => 'Section 3 - Confirming Client Identity', 'icon' => 'bi-heart-pulse'],
        'terminal-illness' => ['label' => 'Section 4 - Terminal Illness', 'icon' => 'bi-heart-pulse'],
        'beneficiary' => ['label' => 'Section 5 - Nominated Beneficiary', 'icon' => 'bi-people'],
        'redress-type' => ['label' => 'Section 6 - Redress Type', 'icon' => 'bi-people'],
        'care-settings' => ['label' => 'Section 7 - Care Settings', 'icon' => 'bi-hospital'],
        'further-information' => ['label' => 'Section 7a - Further Information', 'icon' => 'bi-hospital'],
        'impact-factors' => ['label' => 'Section 8 - Impact Factors', 'icon' => 'bi-exclamation-triangle'],
        'bank-details' => ['label' => 'Section 9 - Bank Details', 'icon' => 'bi-bank'],
        'provisional-value' => ['label' => '10 - Provisional Value', 'icon' => 'bi-bank'],
    ];

    /**
     * update the active tab
     */
    public function setTab($tab)
    {
        $this->activeTab = $tab;
    }

    public function generateApplication(ApplicationService $service) {
        try {
            $service->build($this->client);
            $this->dispatch('toast', message: "Application generated and saved.", type: 'success');
        } catch (\Exception $exception) {
            $this->dispatch('toast', message: $exception->getMessage(), type: 'error');
            Log::error($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
        }
    }

    public function sendCFARequest(EsignService $esign) {
        $docType = ['CFA', 'LOA'];
        if($esign->send(
            email: (string)$this->client->email_address,
            phone: $this->client->phone_number,
            documentType: $docType,
            prefillData: [],
            externalId: $this->client->slug,
        )) {
            $this->dispatch('toast', message: "Request sent.", type: 'success');
        } else {
            $this->dispatch('toast', message: "Request not sent.", type: 'error');
        }
    }

    public function sendToRedress(
        WipService $wipService,
        AppMilestoneService $milestones,
    ): void {
        $this->authorize('communications.send.email');
        $this->client->loadMissing('claim');

        if (!$this->client->claim) {
            $this->dispatch('toast', message: 'This client does not have a claim.', type: 'error');

            return;
        }

        try {
            app(EvaluateContactTriggersAction::class)(
                $this->client,
                TemplateTriggerType::SENT_TO_REDRESS,
                $this->client->getAttributes(),
            );

            $sentDate = today();
            $estimatedDays = $milestones->averageReceivalDays(
                (int) $this->client->claim->solicitor_id,
            );

            $this->client->claim->update([
                'app_sent_date' => $sentDate->toDateString(),
                'app_est_receival_date' => $sentDate->copy()
                    ->addDays($estimatedDays)
                    ->toDateString(),
            ]);

        } catch (\Throwable $exception) {
            Log::error('Application tab Redress send failed', [
                'client_id' => $this->client->id,
                'error' => $exception->getMessage(),
            ]);
            $this->dispatch(
                'toast',
                message: 'The Redress application could not be queued. Please check the communication log.',
                type: 'error',
            );

            return;
        }

        try {
            $wipService->create([
                'client_id' => $this->client->id,
                'claim_id' => $this->client->claim->id,
                'activity_type' => 'sent_to_redress',
                'seconds' => 720,
                'units' => 2,
                'description' => 'Sent application to the Scheme and confirmation to the client',
                'started_at' => now(),
                'ended_at' => now(),
                'is_manual' => false,
            ], $this->client);
        } catch (\Throwable $exception) {
            Log::error('Redress application queued but WIP booking failed', [
                'client_id' => $this->client->id,
                'error' => $exception->getMessage(),
            ]);
            $this->dispatch(
                'toast',
                message: 'Application queued, but the 2 WIP units could not be recorded.',
                type: 'warning',
            );

            return;
        }

        $this->dispatch(
            'toast',
            message: 'Scheme and client emails queued and 2 WIP units recorded.',
            type: 'success',
        );
    }

    public function render()
    {
        return view('components.claim.application.application');
    }
}
