<?php

namespace App\Livewire\Tasks;

use App\Models\Activity;
use App\Models\Task;
use Livewire\Component;

class Index extends Component
{
    public string $search       = '';
    public string $filterStatus = '';  // '' | pending | in_progress | done | today

    // Formular
    public bool    $showForm    = false;
    public ?string $editId      = null;
    public string  $taskTitle   = '';
    public string  $description = '';
    public string  $priority    = 'medium';
    public string  $due_at      = '';
    public string  $reminderAt  = '';

    public function updatedSearch(): void { }
    public function updatedFilterStatus(): void { }

    // ── Formular ──────────────────────────────────────────────────────────

    public function openCreate(): void
    {
        $this->reset(['editId', 'taskTitle', 'description', 'due_at', 'reminderAt']);
        $this->priority = 'medium';
        $this->showForm = true;
    }

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

        $tz = auth()->user()->timezone ?? 'Europe/Vienna';

        $this->editId      = $id;
        $this->taskTitle   = $task->title;
        $this->description = $task->description ?? '';
        $this->priority    = $task->priority;
        $this->due_at      = $task->due_at ? $task->due_at->format('Y-m-d') : '';
        $this->reminderAt  = $task->reminder_at
            ? $task->reminder_at->setTimezone($tz)->format('Y-m-d\TH:i')
            : '';
        $this->showForm    = true;
    }

    public function save(): void
    {
        $this->validate([
            'taskTitle'   => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:2000'],
            'priority'    => ['required', 'in:low,medium,high'],
            'due_at'      => ['nullable', 'date'],
            'reminderAt'  => ['nullable', 'string'],
        ]);

        if ($this->reminderAt) {
            $isPro = auth()->user()->subscription?->plan?->plan_key !== 'free';

            if (!$isPro) {
                $query = Task::where('user_id', auth()->id())
                    ->whereNotNull('reminder_at')
                    ->where('reminder_at', '>', now())
                    ->where('reminder_sent', false)
                    ->where('status', '!=', 'done');

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

                if ($query->count() >= 3) {
                    $this->addError('reminderAt', 'Limit erreicht: Max. 3 aktive Erinnerungen im Free Plan.');
                    return;
                }
            }
        }

        $tz         = auth()->user()->timezone ?? 'Europe/Vienna';
        $reminderUtc = $this->reminderAt
            ? \Carbon\Carbon::createFromFormat('Y-m-d\TH:i', $this->reminderAt, $tz)->utc()
            : null;

        $data = [
            'title'         => $this->taskTitle,
            'description'   => $this->description ?: null,
            'priority'      => $this->priority,
            'due_at'        => $this->due_at ?: null,
            'reminder_at'   => $reminderUtc,
            'reminder_sent' => false,
        ];

        $isEdit = (bool) $this->editId;

        if ($isEdit) {
            Task::forUser(auth()->id())->where('id', $this->editId)->update($data);
        } else {
            Task::create(array_merge($data, ['user_id' => auth()->id()]));

            Activity::log(
                auth()->id(),
                Activity::TYPE_TASK_CREATED,
                Activity::localizedTitle('task_created', auth()->user()->locale ?? 'de'),
                $this->taskTitle,
                meta: ['priority' => $this->priority, 'due_at' => $this->due_at ?: null]
            );
        }

        $this->closeForm();
        $this->dispatch('notify', ['type' => 'success', 'message' => $isEdit ? 'Aufgabe gespeichert' : 'Aufgabe erstellt']);
    }

    public function closeForm(): void
    {
        $this->reset(['showForm', 'editId', 'taskTitle', 'description', 'due_at', 'reminderAt']);
        $this->priority = 'medium';
    }

    public function setReminderQuick(int $minutes): void
    {
        $tz = auth()->user()->timezone ?? 'Europe/Vienna';
        $this->reminderAt = now($tz)->addMinutes($minutes)->format('Y-m-d\TH:i');
    }

    public function setReminderTomorrow(): void
    {
        $tz = auth()->user()->timezone ?? 'Europe/Vienna';
        $this->reminderAt = now($tz)->addDay()->setHour(8)->setMinute(0)->format('Y-m-d\TH:i');
    }

    public function clearReminder(): void
    {
        $this->reminderAt = '';
    }

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

    public function toggleDone(string $id): void
    {
        $task = Task::forUser(auth()->id())->findOrFail($id);

        if ($task->isDone()) {
            $task->update(['status' => Task::STATUS_PENDING, 'completed_at' => null]);
        } else {
            $task->update(['status' => Task::STATUS_DONE, 'completed_at' => now()]);

            Activity::log(
                auth()->id(),
                Activity::TYPE_TASK_COMPLETED,
                Activity::localizedTitle('task_completed', auth()->user()->locale ?? 'de'),
                $task->title,
            );
        }
    }

    public function setStatus(string $id, string $status): void
    {
        Task::forUser(auth()->id())->where('id', $id)->update(['status' => $status]);
    }

    public function delete(string $id): void
    {
        $task = Task::forUser(auth()->id())->where('id', $id)->first();
        if ($task) {
            Activity::log(auth()->id(), Activity::TYPE_TASK_DELETED, Activity::localizedTitle('task_deleted', auth()->user()->locale ?? 'de'), $task->title);
            $task->delete();
        }
    }

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

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

        $query = Task::forUser($userId)->orderByRaw("FIELD(priority, 'high', 'medium', 'low')")->orderBy('due_at')->orderByDesc('created_at');

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

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

        $tasks = $query->get();
        $openTasks = $tasks->where('status', '!=', 'done')->values();
        $doneTasks = $tasks->where('status', 'done')->values();

        $stats = Task::forUser($userId)
            ->selectRaw("
                count(*) as total,
                sum(case when status != 'done' then 1 else 0 end) as open,
                sum(case when status = 'done' then 1 else 0 end) as done,
                sum(case when DATE(due_at) = CURRENT_DATE and status != 'done' then 1 else 0 end) as today
            ")
            ->first();

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