<?php

namespace App\Components\Claim;

use App\Models\Client\Client;
use App\Models\Dsar\Dsar;
use App\Models\Institution\Institution;
use App\Services\DsarService;
use App\Services\HistoryService;
use Illuminate\Pagination\LengthAwarePaginator;
use Livewire\Component;
use Livewire\WithPagination;

class Dsars extends Component {
    public Client $client;
    public bool $showAdd = false;
    public $search = '';
    public array $selectedIds  = [];
    public array $postIds      = [];

    use WithPagination;

    public function showAddDsar() {
        $this->showAdd = true;
    }

    public function createDsars(DsarService $dsar, HistoryService $history) {
        $tranche = $this->client->claim->dsarTranches()->create([
            'status' => 'draft'
        ]);

        $pivotDates = $this->client->claim->institutions
            ->keyBy('id')
            ->map(fn($i) => $i->pivot->dates);

        $institutionsAdded = [];

        foreach ($this->selectedIds as $id) {
            $institution = Institution::find($id);

            if (!$institution) {
                throw new \Exception('Institution not found');
            }

            $tranche->dsars()->create([
                'solicitor_id' => $this->client->solicitor_id,
                'claim_id' => $this->client->claim->id,
                'user_id' => auth()->id(),
                'institution_id' => $id,
                'status' => 'draft',
                'content' => $dsar->buildContent($institution->dsarType, $this->client),
            ]);

            $institutionsAdded[] = $institution->display_name;
        }

        // Log the creation of DSARs
        $history->add(
            $this->client->claim,
            "Created DSAR Tranche with " . count($institutionsAdded) . " institutions.",
            [
                'tranche_id' => $tranche->id,
                'institutions' => $institutionsAdded
            ]
        );

        $this->hideAddDsar();

        return redirect()->route('dsars.tranches.view', $tranche);
    }

    public function hideAddDsar() {
        $this->showAdd = false;
        $this->reset(['search', 'selectedIds']);
    }

    public function selectAllPostable() {
        $this->postIds = $this->client->claim->dsars()
            ->where('status', 'needs posting')
            ->pluck('id')
            ->map(fn($id) => (string) $id)
            ->all();
    }

    public function markAsPosted(HistoryService $history) {
        if (empty($this->postIds)) {
            return;
        }

        Dsar::whereIn('id', $this->postIds)
            ->where('status', 'needs posting')
            ->each(function (Dsar $dsar) use ($history) {
                $dsar->update([
                    'status'    => 'sent',
                    'posted_at' => now(),
                ]);
                $history->add($dsar, 'DSAR marked as posted', [
                    'institution' => $dsar->institution?->display_name,
                    'posted_at'   => now()->toDateTimeString(),
                ]);
            });

        $this->reset('postIds');
        $this->dispatch('toast', message: 'DSARs marked as posted.', type: 'success');
    }

    public function render() {
        $dsarsQuery = $this->client->claim->dsars();

        $allInstitutions = $this->client->claim->careSettings
            ->pluck('institution')
            ->filter()
            ->flatMap(function ($institution)
            {
                return collect([$institution])->concat($institution->relatedInstitutions);
            })
            ->concat($this->client->claim->institutions)
            ->unique('id');

        // Global institutions (is_prioritised) not already in the claim list
        $claimInstitutionIds = $allInstitutions->pluck('id')->all();
        $globalInstitutions = Institution::where('is_prioritised', true)
            ->when($claimInstitutionIds, fn($q) => $q->whereNotIn('id', $claimInstitutionIds))
            ->orderBy('display_name')
            ->get();

        if (!empty($this->search)) {
            $term = strtolower($this->search);
            $allInstitutions = $allInstitutions->filter(
                fn($item) => str_contains(strtolower($item->display_name), $term)
            );
            $globalInstitutions = $globalInstitutions->filter(
                fn($item) => str_contains(strtolower($item->display_name), $term)
            );
        }

        $allInstitutions = $allInstitutions->values();

        $perPage = 10;
        $currentPage = LengthAwarePaginator::resolveCurrentPage('availPage');
        $currentItems = $allInstitutions->slice(($currentPage - 1) * $perPage, $perPage)->all();

        $paginatedInstitutions = new LengthAwarePaginator(
            $currentItems,
            $allInstitutions->count(),
            $perPage,
            $currentPage,
            [
                'path' => \request()->url(),
                'query' => request()->query(),
                'pageName' => 'availPage'
            ]
        );

        return view('components.claim.dsars', [
            'dsars'                 => $dsarsQuery->paginate(10, ['*'], 'dsarsPage'),
            'availableInstitutions' => $paginatedInstitutions,
            'globalInstitutions'    => $globalInstitutions,
        ]);
    }
}