<?php

namespace App\Http\Controllers;

use App\Models\Todo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;

class TodoController extends Controller
{
    public function list()
    {
        $user = Auth::user();
        $user_id = $user->role === 'admin' ? request('user_id', $user->id) : $user->id;

        $filter = request('filter', 'all'); // all, pending, completed, overdue, upcoming

        $query = Todo::where('user_id', $user_id)->with('user');

        switch ($filter) {
            case 'pending':
                $query->pending();
                break;
            case 'completed':
                $query->completed();
                break;
            case 'overdue':
                $query->overdue();
                break;
            case 'upcoming':
                $query->upcoming(24);
                break;
        }

        $todos = $query->orderBy('todo_time', 'asc')->paginate(20);

        // Statistics
        $stats = [
            'total' => Todo::where('user_id', $user_id)->count(),
            'pending' => Todo::where('user_id', $user_id)->pending()->count(),
            'completed' => Todo::where('user_id', $user_id)->completed()->count(),
            'overdue' => Todo::where('user_id', $user_id)->overdue()->count(),
            'upcoming' => Todo::where('user_id', $user_id)->upcoming(24)->count(),
        ];

        return view('todo-list', compact('todos', 'stats', 'filter'));
    }

    public function show($id)
    {
        $user = Auth::user();
        $todo = Todo::findOrFail($id);

        if ($user->role !== 'admin' && $todo->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        return view('todo.show', compact('todo'));
    }

    public function create()
    {
        return view('todo.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'todo_time' => 'required|date|after:now',
            'reminder_before' => 'required|in:60,120,300', // 1hr, 2hr, 5hr
            'priority' => 'nullable|in:low,medium,high',
        ]);

        $user = Auth::user();

        $todo = Todo::create([
            'user_id' => $user->id,
            'title' => $request->title,
            'description' => $request->description,
            'todo_time' => $request->todo_time,
            'reminder_before' => $request->reminder_before,
            'priority' => $request->priority ?? 'medium',
            'status' => 'pending',
        ]);

        return redirect()->route('todo.list')
            ->with('success_alert', __('Todo created successfully. Reminder will be sent ') . $todo->reminder_label);
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|exists:todos,id',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'todo_time' => 'required|date',
            'reminder_before' => 'required|in:60,120,300',
            'priority' => 'nullable|in:low,medium,high',
        ]);

        $user = Auth::user();
        $todo = Todo::findOrFail($request->id);

        if ($user->role !== 'admin' && $todo->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $todo->update([
            'title' => $request->title,
            'description' => $request->description,
            'todo_time' => $request->todo_time,
            'reminder_before' => $request->reminder_before,
            'priority' => $request->priority ?? $todo->priority,
        ]);

        // Reset reminder if time changed
        if ($todo->wasChanged('todo_time') || $todo->wasChanged('reminder_before')) {
            $todo->update([
                'reminder_sent' => false,
                'reminder_sent_at' => null,
            ]);
        }

        return redirect()->back()
            ->with('success_alert', __('Todo updated successfully'));
    }

    public function markCompleted(Request $request)
    {
        $user = Auth::user();
        $todo = Todo::findOrFail($request->id);

        if ($user->role !== 'admin' && $todo->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $todo->markAsCompleted();

        return redirect()->back()
            ->with('success_alert', __('Todo marked as completed'));
    }

    public function toggleStatus(Request $request)
    {
        $user = Auth::user();
        $todo = Todo::findOrFail($request->id);

        if ($user->role !== 'admin' && $todo->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        if ($todo->is_completed) {
            $todo->update([
                'is_completed' => false,
                'status' => 'pending',
                'completed_at' => null,
            ]);
        } else {
            $todo->markAsCompleted();
        }

        return redirect()->back()
            ->with('success_alert', __('Todo status updated'));
    }

    public function destroy(Request $request)
    {
        $user = Auth::user();
        $todo = Todo::findOrFail($request->id);

        if ($user->role !== 'admin' && $todo->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $todo->delete();

        return redirect()->route('todo.list')
            ->with('success_alert', __('Todo deleted successfully'));
    }

    public function calendar()
    {
        $user = Auth::user();
        $user_id = $user->role === 'admin' ? request('user_id', $user->id) : $user->id;

        $todos = Todo::where('user_id', $user_id)
            ->where('todo_time', '>=', now()->startOfMonth())
            ->where('todo_time', '<=', now()->endOfMonth()->addMonth())
            ->get();

        // Format for calendar
        $events = $todos->map(function ($todo) {
            return [
                'id' => $todo->id,
                'title' => $todo->title,
                'start' => $todo->todo_time->format('Y-m-d H:i:s'),
                'className' => $todo->is_completed ? 'completed' : ($todo->priority ?? 'medium'),
                'backgroundColor' => $this->getPriorityColor($todo->priority, $todo->is_completed),
                'borderColor' => $this->getPriorityColor($todo->priority, $todo->is_completed),
            ];
        });

        return view('todo.calendar', compact('events'));
    }

    private function getPriorityColor($priority, $isCompleted)
    {
        if ($isCompleted) return '#28a745';
        
        switch ($priority) {
            case 'high':
                return '#dc3545';
            case 'medium':
                return '#ffc107';
            case 'low':
                return '#17a2b8';
            default:
                return '#6c757d';
        }
    }

    public function upcoming()
    {
        $user = Auth::user();
        
        $todos = Todo::where('user_id', $user->id)
            ->upcoming(24)
            ->orderBy('todo_time', 'asc')
            ->get();

        return response()->json([
            'count' => $todos->count(),
            'todos' => $todos,
        ]);
    }
}
