<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\Workshop;
use App\Models\Video;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $user = auth()->user();

        if (!$user) {
            return response()->json([
                'message' => 'Utilizador não autenticado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        $role = $user->role_id;

        if ($role === 1) {
            $search = trim((string) $request->query('search', ''));
            $filter = $request->query('filter', 'all');
            $usersQuery = User::query();

            if ($search !== '') {
                $usersQuery->where(function ($q) use ($search) {
                    $q->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                });
            }

            if ($filter === 'admin') {
                $usersQuery->where('role_id', 1);
            } elseif ($filter === 'user') {
                $usersQuery->where('role_id', 2);
            }

            $users = $usersQuery->paginate(10)->appends(['filter' => $filter, 'search' => $search]);

            return response()->json([
                'message' => 'Utilizadores obtidos com sucesso',
                'data' => $users,
                'role' => $role,
                'errors' => null,
            ], 200);
        } else {
            return response()->json([
                'message' => 'Não foi possível obter os utilizadores',
                'data' => null,
                'errors' => null,
            ], 500);
        }
    }

    public function getUser($id)
    {

        $user = User::find($id);

        if (!$user) {
            return response()->json([
                'message' => 'Utilizador não encontrado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        $sectorName = $user->sector?->name;
        $userSector = $user->sector_id;
        $role = $user->role_id;

        $videosWatched = Video::select('id')
            ->whereHas('views', function ($query) use ($user) {
                $query->where('user_id', $user->id);
            })
            ->when($role !== 1, fn($q) => $q->whereHas('sectors', function ($s) use ($userSector) {
                $s->where('sectors.id', $userSector)
                  ->orWhere('sectors.slug', "global");
            }))
            ->count();

        $videosCount = Video::select('id')
            ->when($role !== 1, fn($q) => $q->where('is_active', true))
            ->whereHas('sectors', function ($s) use ($userSector) {
                $s->where('sectors.id', $userSector)
                  ->orWhere('sectors.slug', "global");
            })
            ->count();

        $workshopsCount = Workshop::select('id')->where('status', 'pending')->count();

        $workshopsInscribed = Workshop::select('id')
            ->where('status', 'pending')
            ->whereHas('users', function ($query) use ($user) {
                $query->where('users.id', $user->id);
            })->count();

        $nextWorkshops = Workshop::select('id', 'title', 'image', 'date', 'time_start', 'time_end', 'status')->with('users:id')->where('status', 'pending')->orderBy('date', 'asc')->orderBy('time_start', 'asc')->limit(3)->get();

        $workshopsParticipated = Workshop::select('id', 'title', 'image', 'date', 'time_start', 'time_end', 'status')->with('users:id')->whereHas('users', function ($query) use ($user) {
            $query->where('users.id', $user->id);
        })->get();

        return response()->json([
            'message' => 'Utilizador obtido com sucesso',
            'data' => $user,
            'sectorName' => $sectorName,
            'errors' => null,
            'videosWatched' => $videosWatched,
            'videosCount' => $videosCount,
            'workshopsInscribed' => $workshopsInscribed,
            'nextWorkshops' => $nextWorkshops,
            'workshopsCount' => $workshopsCount,
            'workshopsParticipated' => $workshopsParticipated,
        ], 200);
    }

    public function profile()
    {
        $user = auth()->user();

        if (!$user) {
            return response()->json([
                'message' => 'Utilizador não autenticado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        $role = $user->role_id;
        $userId = $user->id;
        $userSector = $user->sector_id;

        if ($role === 1) {
            $nextWorkshops = Workshop::select('id', 'title', 'image', 'date', 'time_start', 'time_end', 'status')->where('status', 'pending')->orderBy('date', 'asc')->orderBy('time_start', 'asc')->limit(3)->get();
            $workshopsCount = Workshop::select('id')->where('status', 'pending')->count();

            $videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order')->where('is_active', true)->orderBy('order', 'asc')->limit(3)->get()->map(function ($video) {
                return [
                    'id' => $video->id,
                    'title' => $video->title,
                    'thumbnail' => $video->thumbnail,
                    'is_active' => $video->is_active,
                    'order' => $video->order,
                ];
            });

            $videosCount = Video::select('id')->where('is_active', true)->count();
        } else {
            $videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order')
                ->where('is_active', true)
                ->whereDoesntHave('views', function ($q) use ($user) {
                    $q->where('user_id', $user->id);
                })
                ->when($role !== 1, fn($q) => $q->whereHas('sectors', function ($s) use ($userSector) {
                    $s->where('sectors.id', $userSector)
                      ->orWhere('sectors.slug', "global");
                }))
                ->orderBy('order', 'asc')
                ->limit(3)
                ->get()
                ->map(function ($video) {
                    return [
                        'id' => $video->id,
                        'title' => $video->title,
                        'thumbnail' => $video->thumbnail,
                        'is_active' => $video->is_active,
                        'watched' => false,
                    ];
                });

            $videosCount = Video::select('id')->where('is_active', true)->when($role !== 1, fn($q) => $q->whereHas('sectors', function ($s) use ($userSector) {
                $s->where('sectors.id', $userSector)
                  ->orWhere('sectors.slug', "global");
            }))->count();

            $videosWatched = Video::select('id')
                ->where('is_active', true)
                ->whereHas('views', function ($query) use ($user) {
                    $query->where('user_id', $user->id);
                })->when($role !== 1, fn($q) => $q->whereHas('sectors', function ($s) use ($userSector) {
                    $s->where('sectors.id', $userSector)
                      ->orWhere('sectors.slug', "global");
                }))->count();

            $workshopsInscribed = Workshop::select('id', 'title', 'image', 'date', 'time_start', 'time_end', 'status')->with('users:id')->where('status', 'pending')->whereHas('users', function ($query) use ($user) {
                $query->where('users.id', $user->id);
            })
                ->orderBy('date', 'asc')
                ->orderBy('time_start', 'asc')
                ->get();

            $workshopsCount = Workshop::select('id')->where('status', 'pending')->count();
        }

        return response()->json([
            'message' => 'Utilizador obtido com sucesso',
            'data' => $user,
            'videos' => $videos,
            'videosCount' => $videosCount ?? 0,
            'videosWatched' => $videosWatched ?? 0,
            'workshopsInscribed' => $workshopsInscribed ?? [],
            'workshopsCount' => $workshopsCount ?? 0,
            'nextWorkshops' => $nextWorkshops ?? [],
            'userId' => $userId,
            'role' => $role,
            'errors' => null,
        ], 200);
    }

    public function create(CreateUserRequest $request)
    {
        $validated = $request->validated();

        try {
            $user = User::create([
                'name' => $validated['name'],
                'email' => $validated['email'],
                'password' => Hash::make($validated['password']),
                'role_id' => $validated['role_id'],
                'sector_id' => $validated['sector_id'],
            ]);

            return response()->json([
                'message' => 'Utilizador criado com sucesso',
                'data' => $user,
                'errors' => null,
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json([
                'message' => 'Erro ao criar o utilizador',
                'data' => null,
                'errors' => $e->errors(),
            ], 422);
        } catch (\Throwable $th) {
            return response()->json([
                'message' => 'Não foi possível criar o utilizador',
                'data' => null,
                'errors' => null,
            ], 500);
        }
    }

    public function update(UpdateUserRequest $request, $id)
    {
        $user = auth()->user();

        if (!$user) {
            return response()->json([
                'message' => null,
                'data' => null,
                'errors' => [
                    'message' => "Utilizador não autenticado",
                ],
            ], 404);
        }

        $userToUpdate = User::find($id);

        if (!$userToUpdate) {
            return response()->json([
                'message' => 'Utilizador não encontrado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        $request = request();

        try {
            $data = [
                'name'    => $request->name ?: $userToUpdate->name,
                'email'   => $request->email ?: $userToUpdate->email,
                'role_id' => $request->role_id ?: $userToUpdate->role_id,
                'sector_id' => $request->sector_id ?: $userToUpdate->sector_id,
            ];

            if ($request->filled('novaPassword')) {
                if (! Hash::check($request->passwordAtual, $userToUpdate->password)) {
                    return response()->json([
                        'message' => 'Password atual incorreta',
                        'data' => null,
                        'errors' => [
                            'message' => 'A password atual não está correta',
                        ],
                    ], 422);
                }

                if ($request->novaPassword !== $request->confirmarPassword) {
                    return response()->json([
                        'message' => 'As passwords não coincidem',
                        'data' => null,
                        'errors' => [
                            'message' => 'A nova password e a confirmação devem coincidir',
                        ],
                    ], 422);
                }

                $data['password'] = Hash::make($request->novaPassword);
            }

            $userToUpdate->update($data);

            $userUpdated = User::find($id);

            return response()->json([
                'message' => 'Dados atualizados com sucesso',
                'data' => $userUpdated,
                'errors' => null,
            ], 201);
        } catch (\Throwable $th) {
            return response()->json([
                'message' => 'Não foi possível atualizar o utilizador',
                'data' => null,
                'errors' => null,
            ], 500);
        }
    }

    public function destroy($id)
    {
        $user = auth()->user();

        if (!$user) {
            return response()->json([
                'message' => 'Utilizador não autenticado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        if ($user->role_id !== 1) {
            return response()->json([
                'message' => 'Utilizador não autorizado',
                'data' => null,
                'errors' => null,
            ], 403);
        }

        if ($user->id === (int) $id) {
            return response()->json([
                'message' => 'Não pode apagar a sua própria conta de administrador',
                'data' => null,
                'errors' => null,
            ], 403);
        }

        $userToDelete = User::find($id);

        if (!$userToDelete) {
            return response()->json([
                'message' => 'Utilizador não encontrado',
                'data' => null,
                'errors' => null,
            ], 404);
        }

        try {
            $userToDelete->delete();

            return response()->json([
                'message' => 'Utilizador apagado com sucesso',
                'data' => null,
                'errors' => null,
            ], 200);
        } catch (\Throwable $th) {
            return response()->json([
                'message' => 'Não foi possível apagar o utilizador',
                'data' => null,
                'errors' => null,
            ], 500);
        }
    }
}
