<?php

namespace App\Components\Tranche;

use App\Models\Tranche;
use App\Services\HistoryService;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component {
    use WithPagination;

    // Search and State
    public $search = '';
    public $isModalOpen = false;
    public $confirmingDeletion = false;
    public $trancheId;

    // Form Fields
    public $funder_name;
    public $tranche_name;
    public $amount_per_case;
    public $description;
    public $funded_date;

    protected $rules = [
        'funder_name' => 'required|string|max:255',
        'tranche_name' => 'required|string|max:255',
        'amount_per_case' => 'required|numeric|min:0',
        'funded_date' => 'nullable|date',
        'description' => 'nullable|string',
    ];

    public function mount(): void {
        $this->authorize('tranches.view');
    }

    public function openModal() {
        $this->resetErrorBag();
        $this->resetForm();
        $this->isModalOpen = true;
    }

    public function resetForm() {
        $this->trancheId = null;
        $this->funder_name = '';
        $this->tranche_name = '';
        $this->amount_per_case = '';
        $this->description = '';
        $this->funded_date = null;
    }

    public function edit($id) {
        $tranche = Tranche::findOrFail($id);
        $this->trancheId = $id;
        $this->funder_name = $tranche->funder_name;
        $this->tranche_name = $tranche->tranche_name;
        $this->amount_per_case = $tranche->amount_per_case;
        $this->description = $tranche->description;
        $this->funded_date = $tranche->funded_date;

        $this->isModalOpen = true;
    }

    public function save(HistoryService $history) {
        $this->validate();

        $isNew = empty($this->trancheId);
        $attributes = [
            'funder_name' => $this->funder_name,
            'tranche_name' => $this->tranche_name,
            'amount_per_case' => $this->amount_per_case,
            'description' => $this->description,
            'funded_date' => $this->funded_date,
        ];

        $existing = $isNew ? null : Tranche::find($this->trancheId);
        $before = $existing ? $existing->only(array_keys($attributes)) : [];

        $tranche = Tranche::updateOrCreate(
            ['id' => $this->trancheId],
            $attributes
        );

        $changed = [];
        foreach ($tranche->getChanges() as $field => $newValue) {
            if (in_array($field, ['updated_at', 'created_at'])) {
                continue;
            }
            $changed[$field] = ['from' => $before[$field] ?? null, 'to' => $newValue];
        }

        $history->addForActor(
            ($isNew ? 'Created' : 'Updated') . " funding tranche '{$this->funder_name} - {$this->tranche_name}'",
            [
                'tranche_id'      => $tranche->id,
                'funder_name'     => $this->funder_name,
                'tranche_name'    => $this->tranche_name,
                'amount_per_case' => $this->amount_per_case,
                'changed'         => $changed,
            ]
        );

        $this->closeModal();

        $this->dispatch('toast', message: $this->trancheId ? 'Tranche updated successfully.' : 'Tranche created successfully.', type: 'success');
    }

    public function closeModal() {
        $this->isModalOpen = false;
    }

    public function confirmDelete($id) {
        $this->trancheId = $id;
        $this->confirmingDeletion = true;
    }

    public function delete(HistoryService $history) {
        $tranche = Tranche::findOrFail($this->trancheId);
        $context = [
            'tranche_id'      => $tranche->id,
            'funder_name'     => $tranche->funder_name,
            'tranche_name'    => $tranche->tranche_name,
            'amount_per_case' => $tranche->amount_per_case,
        ];
        $tranche->delete();

        $history->addForActor("Deleted funding tranche '{$context['funder_name']} - {$context['tranche_name']}'", $context);

        $this->confirmingDeletion = false;
        session()->flash('message', 'Tranche deleted successfully.');
    }

    public function render() {
        $tranches = Tranche::where('tranche_name', 'like', '%' . $this->search . '%')
            ->orWhere('funder_name', 'like', '%' . $this->search . '%')
            ->latest()
            ->paginate(10);

        return view('components.tranche.index', [
            'tranches' => $tranches
        ]);
    }
}
