<?php

namespace App\Components\Client;

use App\Models\Claim\CareSetting;
use App\Models\Claim\Status;
use App\Models\Client\Client;
use App\Models\Institution\Institution;
use App\Models\LeadSource\LeadSource;
use App\Models\LeadSource\LeadSourceEndpoint;
use App\Models\Tag;
use App\Models\Tranche;
use App\Models\User\User;
use App\Services\Client\ClientFilter;
use App\Services\ClientService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Lazy;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

#[Lazy]
class Index extends Component {

    use WithPagination, AuthorizesRequests;

    public $search = '';
    public $sortColumn = 'name_last';
    public $sortDirection = 'asc';
    public $perPage = 10;

    #[Url(history: true)]
    public $status_id = null;
    #[Url(history: true)]
    public $lead_source_id = null;
    #[Url(history: true)]
    public $url = null;
    #[Url(history: true)]
    public $date_from = null;
    #[Url(history: true)]
    public $date_to = null;
    #[Url(history: true)]
    public $care_setting_id = null;
    #[Url(history: true)]
    public $tranche_id = null;
    protected ClientService $clientService;
    #[Url(history: true)]
    public $priority;
    #[Url(history: true)]
    public $tag_id;
    #[Url(history: true)]
    public $handler = null;
    #[Url(history: true)]
    public $days_range = null;

    #[Url(history: true)]
    public $status_filter_type = null;

    public function placeholder() {
        return <<<'HTML'
        <div class="row">
            <div class="col-12 col-md-9">
                <div class="card">
                    <div class="card-body">
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-100"></div>
                        <div class="placeholder placeholder-wave w-75"></div>
                        <div class="placeholder placeholder-wave w-50"></div>
                    </div>
                </div>
            </div>
        </div>
        HTML;

    }

    public function boot(ClientService $clientService) {
        $this->clientService = $clientService;
    }


    public function render() {
        $clients = app(ClientFilter::class)
            ->apply(Client::query(), [
                'search'          => $this->search,
                'status_id'       => $this->status_id,
                'days_range'      => $this->days_range,
                'tranche_id'      => $this->tranche_id,
                'lead_source_id'  => $this->lead_source_id,
                'url'             => $this->url,
                'tag_id'          => $this->tag_id,
                'priority'        => $this->priority,
                'date_from'       => $this->date_from,
                'date_to'         => $this->date_to,
                'handler'         => $this->handler,
                'care_setting_id' => $this->care_setting_id,
                'status_filter_type' => $this->status_filter_type,
            ])
            ->with(['claim.status', 'claim.terminalIllness', 'tranche'])
            ->paginate($this->perPage);

        $endpoints = LeadSourceEndpoint::query()
            ->get(['id', 'url', 'display_name'])
            ->mapWithKeys(fn ($endpoint) => [
                $endpoint->id => "{$endpoint->url} - {$endpoint->display_name}"
            ])
            ->toArray();

        $tranches = Tranche::query()->get([
            'funder_name', 'tranche_name', 'id'
        ])->mapWithKeys(fn ($tranche) => [
            $tranche->id => "{$tranche->funder_name} - {$tranche->tranche_name}"
        ])->toArray();

        $endpoints = [0 => 'None Assigned'] + $endpoints;
        $tranches = [0 => 'None Assigned'] + $tranches;

        return view('components.client.client-list', [
            'clients' => $clients,
            'leadSources' => LeadSource::pluck('display_name', 'id')->toArray(),
            'urls' => $endpoints,
            'statuses' => Status::pluck('display_name', 'id')->toArray(),
            'careSettings' => Institution::orderBy('display_name')->pluck('display_name', 'id')->toArray(),
            'tags' => Tag::pluck('name', 'id')->toArray(),
            'tranches' => $tranches,
           'handlers' => [0 => 'Unassigned Cases'] + User::query()
            ->orderBy('name_first')
            ->orderBy('name_last')
            ->get()
            ->mapWithKeys(fn (User $user) => [
                $user->id => trim($user->name_first . ' ' . $user->name_last),
            ])
            ->toArray(),
        ]);
    }

    public function clearFilters() {
        $this->reset('lead_source_id', 'url', 'date_from', 'date_to', 'status_id', 'care_setting_id', 'days_range','status_filter_type','handler');
    }

    public function checkDeleteClient($clientId) {
        $this->dispatch('swal:confirm',
            itemId: $clientId,
            title: 'Are you absolutely sure?',
            text: 'You will not be able to recover this client.'
        );
    }

    public function deleteClient($clientId) {
        $this->authorize('clients.delete');

        $client = Client::findOrFail($clientId);
        if ($this->clientService->delete($client)) {
            $this->dispatch("alert", title: $client->name_first . " " . $client->name_last . " Deleted");
        }
    }
}
