<?php

namespace App\Components\Claim;

use App\Models\Claim\Claim;
use App\Models\KeyDate;
use App\Services\HistoryService;
use Livewire\Component;

class KeyDatesManager extends Component {
    public Claim $claim;
    public $dates = [];

    public function mount() {
        $this->dates = $this->claim->keyDates()
            ->get()
            ->pluck('pivot.date', 'id')
            ->map(fn($date) => $date ? \Carbon\Carbon::parse($date)->format('Y-m-d') : null)
            ->toArray();
    }

    public function updateDate($dateTypeId, HistoryService $history) {
        $value = $this->dates[$dateTypeId] ?? null;
        $dateType = KeyDate::find($dateTypeId);

        try {
            if (empty($value)) {
                $this->claim->keyDates()->detach($dateTypeId);
                $history->addForClaim($this->claim, 'Key date "' . ($dateType->display_name ?? 'Unknown') . '" cleared', [
                    'key_date_id' => $dateTypeId,
                ]);
            } else {
                $this->claim->keyDates()->syncWithoutDetaching([
                    $dateTypeId => ['date' => $value]
                ]);

                $history->addForClaim($this->claim, 'Key date "' . ($dateType->display_name ?? 'Unknown') . '" set to ' . $value, [
                    'key_date_id' => $dateTypeId,
                    'date'        => $value,
                ]);

                if($dateTypeId == 23) {
                    $derivedDate = date("Y-m-d", strtotime($value . "+14 day"));
                    $this->claim->keyDates()->syncWithoutDetaching([
                        24 => ['date' => $derivedDate]
                    ]);

                    $derivedType = KeyDate::find(24);
                    $history->addForClaim($this->claim, 'Key date "' . ($derivedType->display_name ?? 'Unknown') . '" auto-set to ' . $derivedDate, [
                        'key_date_id' => 24,
                        'date'        => $derivedDate,
                        'derived_from_key_date_id' => 23,
                    ]);
                }
            }

            $this->dispatch('toast', message: 'Date updated successfully.', type: 'success');
        } catch (\Exception $e) {
            $this->dispatch('toast', message: 'Failed to update date. Please try again.', type: 'error');
        }
    }

    public function render() {
        return view('components.claim.key-dates-manager', ['keyDates' => KeyDate::get()]);
    }
}