<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;
use App\Models\MariachiGroup;
use App\Models\StaffRole;
use App\Models\User;
use App\Support\OwnerWorkspace;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Spatie\Permission\PermissionRegistrar;

class TeamController extends Controller
{
    private function activeStaffRolesForOrganization(int $organizationId)
    {
        return StaffRole::query()
            ->forOrganization($organizationId)
            ->custom()
            ->where('is_active', true)
            ->orderBy('name')
            ->get();
    }

    private function mariachiGroupsForOrganization(int $organizationId)
    {
        return OwnerWorkspace::groupsForOrganization($organizationId);
    }

    public function index(Request $request)
    {
        $owner = $request->user();
        $organizationId = $owner->organization_id;

        $users = collect();
        if (!empty($organizationId)) {
            $users = User::query()
                ->with('assignedMariachiGroups:id,name')
                ->where('role', User::ROLE_OWNER_STAFF)
                ->where('organization_id', $organizationId)
                ->orderByDesc('id')
                ->get();
            $users->each(fn (User $user) => $user->setAttribute('current_role_name', $user->ownerRoleName((int) $organizationId)));
        }

        $staffRoles = empty($organizationId) ? collect() : $this->activeStaffRolesForOrganization((int) $organizationId);
        $mariachiGroups = empty($organizationId) ? collect() : $this->mariachiGroupsForOrganization((int) $organizationId);

        $stats = [
            'total' => $users->count(),
            'active' => $users->where('is_active', true)->count(),
            'inactive' => $users->where('is_active', false)->count(),
        ];

        return view('content.owner.settings.team.index', [
            'users' => $users,
            'staffRoles' => $staffRoles,
            'mariachiGroups' => $mariachiGroups,
            'stats' => $stats,
            'canManageTeam' => !empty($organizationId),
        ]);
    }

    public function store(Request $request)
    {
        $owner = $request->user();
        $organizationId = $owner->organization_id;

        if (empty($organizationId)) {
            return redirect()->route('owner.settings.team')->withErrors([
                'name' => 'Primero debes tener una organización asignada para crear equipo.',
            ]);
        }

        $staffRoleCodes = $this->activeStaffRolesForOrganization((int) $organizationId)->pluck('code')->all();

        if (empty($staffRoleCodes)) {
            return redirect()->route('owner.settings.team')->withErrors([
                'name' => 'No hay roles disponibles. Pide al administrador crear un rol.',
            ]);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
            'staff_role' => ['required', Rule::in($staffRoleCodes)],
            'is_active' => ['required', 'boolean'],
            'has_all_mariachi_groups' => ['nullable', 'boolean'],
            'mariachi_group_ids' => ['nullable', 'array'],
            'mariachi_group_ids.*' => [
                'integer',
                Rule::exists('mariachi_groups', 'id')->where(
                    fn ($query) => $query->where('organization_id', $organizationId)->where('is_active', true)
                ),
            ],
        ]);

        $staffRoleCode = $validated['staff_role'];
        $hasAllGroups = (bool) ($validated['has_all_mariachi_groups'] ?? true);
        $mariachiGroupIds = collect($validated['mariachi_group_ids'] ?? [])
            ->map(fn ($id) => (int) $id)
            ->filter()
            ->unique()
            ->values()
            ->all();

        if (!$hasAllGroups && empty($mariachiGroupIds)) {
            return redirect()->route('owner.settings.team')->withErrors([
                'mariachi_group_ids' => 'Selecciona al menos un equipo o activa acceso a todos los equipos.',
            ])->withInput();
        }

        unset($validated['staff_role'], $validated['mariachi_group_ids'], $validated['has_all_mariachi_groups']);
        $validated['role'] = User::ROLE_OWNER_STAFF;
        $validated['organization_id'] = $organizationId;
        $validated['has_all_mariachi_groups'] = $hasAllGroups;

        $user = User::create($validated);
        $role = StaffRole::query()
            ->where('organization_id', $organizationId)
            ->where('code', $staffRoleCode)
            ->firstOrFail();

        app(PermissionRegistrar::class)->setPermissionsTeamId($organizationId);
        $user->syncRoles([$role]);
        $user->update(['staff_role' => $role->code]);

        if ($hasAllGroups) {
            $user->assignedMariachiGroups()->detach();
        } else {
            $user->assignedMariachiGroups()->sync($mariachiGroupIds);
        }

        return redirect()->route('owner.settings.team')->with('status', 'Miembro de equipo creado correctamente.');
    }

    public function deactivate(Request $request, User $user)
    {
        $owner = $request->user();

        if (
            $user->role !== User::ROLE_OWNER_STAFF
            || $user->organization_id !== $owner->organization_id
        ) {
            abort(404);
        }

        $user->update(['is_active' => false]);

        return redirect()->route('owner.settings.team')->with('swal_success', 'Miembro desactivado correctamente.');
    }
}
