<?php

namespace App\Livewire\Contacts;

use App\Models\Activity;
use App\Models\Contact;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use WithPagination;

    public string $search     = '';
    public string $filterType = '';

    // Slide-in Panel
    public bool    $panelOpen   = false;
    public ?string $editId      = null;

    // Formularfelder
    public string  $name     = '';
    public string  $email    = '';
    public string  $phone    = '';
    public string  $type     = '';
    public string  $notes    = '';
    public string  $birthday = '';

    public function updatedSearch(): void     { $this->resetPage(); }
    public function updatedFilterType(): void { $this->resetPage(); }

    // ── Panel ─────────────────────────────────────────────────────────────

    public function openCreate(): void
    {
        $this->reset(['editId', 'name', 'email', 'phone', 'notes', 'birthday']);
        $this->type      = '';
        $this->panelOpen = true;
    }

    public function openEdit(string $id): void
    {
        $contact = Contact::forUser(auth()->id())->findOrFail($id);

        $this->editId   = $id;
        $this->name     = $contact->name;
        $this->email    = $contact->email    ?? '';
        $this->phone    = $contact->phone    ?? '';
        $this->type     = $contact->type     ?? '';
        $this->notes    = $contact->notes    ?? '';
        $this->birthday = $contact->birthday?->format('Y-m-d') ?? '';

        $this->panelOpen = true;
    }

    public function closePanel(): void
    {
        $this->reset(['panelOpen', 'editId', 'name', 'email', 'phone', 'type', 'notes', 'birthday']);
    }

    // ── Speichern ─────────────────────────────────────────────────────────

    public function save(): void
    {
        $this->validate([
            'name'     => ['required', 'string', 'max:255'],
            'email'    => ['nullable', 'email', 'max:255'],
            'phone'    => ['nullable', 'string', 'max:50'],
            'type'     => ['nullable', 'in:' . implode(',', Contact::TYPES)],
            'notes'    => ['nullable', 'string', 'max:2000'],
            'birthday' => ['nullable', 'date'],
        ]);

        $data = [
            'name'     => $this->name,
            'email'    => $this->email    ?: null,
            'phone'    => $this->phone    ?: null,
            'type'     => $this->type     ?: null,
            'notes'    => $this->notes    ?: null,
            'birthday' => $this->birthday ?: null,
        ];

        if ($this->editId) {
            Contact::forUser(auth()->id())->where('id', $this->editId)->update($data);

            Activity::log(
                auth()->id(),
                Activity::TYPE_CONTACT_UPDATED,
                Activity::localizedTitle('contact_updated', auth()->user()->locale ?? 'de'),
                $this->name,
            );

            $this->dispatch('notify', ['type' => 'success', 'message' => 'Kontakt gespeichert']);
        } else {
            Contact::create(array_merge($data, ['user_id' => auth()->id()]));

            Activity::log(
                auth()->id(),
                Activity::TYPE_CONTACT_CREATED,
                Activity::localizedTitle('contact_created', auth()->user()->locale ?? 'de'),
                $this->name,
            );

            $this->dispatch('notify', ['type' => 'success', 'message' => 'Kontakt erstellt']);
        }

        $this->closePanel();
    }

    // ── Löschen ───────────────────────────────────────────────────────────

    public function delete(string $id): void
    {
        $contact = Contact::forUser(auth()->id())->findOrFail($id);
        $name    = $contact->name;
        $contact->delete();

        Activity::log(auth()->id(), Activity::TYPE_CONTACT_UPDATED, Activity::localizedTitle('contact_deleted', auth()->user()->locale ?? 'de'), $name);
    }

    // ── Render ────────────────────────────────────────────────────────────

    public function render()
    {
        $userId = auth()->id();

        $query = Contact::forUser($userId)->orderBy('name');

        if ($this->search !== '') {
            $query->search($this->search);
        }

        if ($this->filterType !== '') {
            $query->where('type', $this->filterType);
        }

        $contacts = $query->paginate(20);

        $stats = Contact::forUser($userId)
            ->selectRaw("
                count(*) as total,
                sum(case when type = 'privat'    then 1 else 0 end) as privat,
                sum(case when type = 'arbeit'    then 1 else 0 end) as arbeit,
                sum(case when type = 'kunde'     then 1 else 0 end) as kunde,
                sum(case when type = 'sonstiges' then 1 else 0 end) as sonstiges
            ")
            ->first();

        return view('livewire.contacts.index', [
            'contacts' => $contacts,
            'stats'    => $stats,
        ])->layout('layouts.app');
    }
}
