<?php

declare(strict_types=1);

namespace App\Http\Controllers\Studio;

use App\Http\Controllers\Controller;
use App\Http\Requests\Groups\AttachArtworkToGroupProjectRequest;
use App\Http\Requests\Groups\AttachAssetToGroupProjectRequest;
use App\Http\Requests\Groups\StoreGroupMilestoneRequest;
use App\Http\Requests\Groups\StoreGroupProjectRequest;
use App\Http\Requests\Groups\UpdateGroupMilestoneRequest;
use App\Http\Requests\Groups\UpdateGroupProjectRequest;
use App\Http\Requests\Groups\UpdateGroupProjectStatusRequest;
use App\Models\Artwork;
use App\Models\Group;
use App\Models\GroupAsset;
use App\Models\GroupPost;
use App\Models\GroupProject;
use App\Models\GroupProjectMilestone;
use App\Services\GroupProjectService;
use App\Services\GroupService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class GroupProjectStudioController extends Controller
{
    public function __construct(
        private readonly GroupService $groups,
        private readonly GroupProjectService $projects,
    ) {
    }

    public function index(Request $request, Group $group): Response
    {
        $this->authorize('manageProjects', $group);

        return Inertia::render('Studio/StudioGroupProjects', [
            'title' => $group->name . ' Projects',
            'description' => 'Manage structured group releases, collaboration hubs, and showcase pages.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'listing' => $this->projects->studioListing($group, $request->only(['bucket', 'page', 'per_page'])),
            'recentHistory' => $this->groups->recentHistory($group),
            'createUrl' => route('studio.groups.projects.create', ['group' => $group]),
        ]);
    }

    public function create(Request $request, Group $group): Response
    {
        $this->authorize('manageProjects', $group);

        return Inertia::render('Studio/StudioGroupProjectEditor', [
            'title' => 'Create project',
            'description' => 'Set up a project page that can collect artworks, assets, notes, and release state.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'project' => null,
            'statusOptions' => collect((array) config('groups.projects.statuses', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucfirst($value)])->values()->all(),
            'visibilityOptions' => collect((array) config('groups.projects.visibility_options', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucfirst($value)])->values()->all(),
            'memberOptions' => $this->projects->memberOptions($group->loadMissing('owner.profile')),
            'collectionOptions' => $group->collections()->orderBy('title')->get(['id', 'title'])->map(fn ($collection): array => ['id' => (int) $collection->id, 'title' => $collection->title])->values()->all(),
            'artworkOptions' => $group->artworks()->whereNull('deleted_at')->latest('updated_at')->limit(30)->get(['id', 'title'])->map(fn ($artwork): array => ['id' => (int) $artwork->id, 'title' => $artwork->title])->values()->all(),
            'postOptions' => $group->posts()->latest('updated_at')->limit(20)->get(['id', 'title'])->map(fn (GroupPost $post): array => ['id' => (int) $post->id, 'title' => $post->title])->values()->all(),
            'storeUrl' => route('studio.groups.projects.store', ['group' => $group]),
        ]);
    }

    public function store(StoreGroupProjectRequest $request, Group $group): RedirectResponse
    {
        $this->authorize('manageProjects', $group);

        $project = $this->projects->create($group, $request->user(), $request->validated());

        return redirect()->route('studio.groups.projects.edit', ['group' => $group, 'project' => $project])
            ->with('success', 'Project created.');
    }

    public function edit(Request $request, Group $group, GroupProject $project): Response
    {
        $this->authorize('manageProjects', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);

        return Inertia::render('Studio/StudioGroupProjectEditor', [
            'title' => 'Edit project',
            'description' => 'Update status, attachments, and project presentation.',
            'studioGroup' => $this->groups->mapGroupDetail($group, $request->user()),
            'project' => $this->projects->detailPayload($project, $request->user()),
            'statusOptions' => collect((array) config('groups.projects.statuses', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucfirst($value)])->values()->all(),
            'visibilityOptions' => collect((array) config('groups.projects.visibility_options', []))->map(fn (string $value): array => ['value' => $value, 'label' => ucfirst($value)])->values()->all(),
            'memberOptions' => $this->projects->memberOptions($group->loadMissing('owner.profile')),
            'collectionOptions' => $group->collections()->orderBy('title')->get(['id', 'title'])->map(fn ($collection): array => ['id' => (int) $collection->id, 'title' => $collection->title])->values()->all(),
            'artworkOptions' => $group->artworks()->whereNull('deleted_at')->latest('updated_at')->limit(30)->get(['id', 'title'])->map(fn ($artwork): array => ['id' => (int) $artwork->id, 'title' => $artwork->title])->values()->all(),
            'assetOptions' => $group->assets()->latest('updated_at')->limit(30)->get(['id', 'title'])->map(fn (GroupAsset $asset): array => ['id' => (int) $asset->id, 'title' => $asset->title])->values()->all(),
            'postOptions' => $group->posts()->latest('updated_at')->limit(20)->get(['id', 'title'])->map(fn (GroupPost $post): array => ['id' => (int) $post->id, 'title' => $post->title])->values()->all(),
            'updateUrl' => route('studio.groups.projects.update', ['group' => $group, 'project' => $project]),
            'statusUrl' => route('studio.groups.projects.status', ['group' => $group, 'project' => $project]),
            'attachArtworkUrl' => route('studio.groups.projects.attach-artwork', ['group' => $group, 'project' => $project]),
            'attachAssetUrl' => route('studio.groups.projects.attach-asset', ['group' => $group, 'project' => $project]),
            'storeMilestoneUrl' => route('studio.groups.projects.milestones.store', ['group' => $group, 'project' => $project]),
            'updateMilestonePattern' => route('studio.groups.projects.milestones.update', ['group' => $group, 'project' => $project, 'milestone' => '__MILESTONE__']),
        ]);
    }

    public function update(UpdateGroupProjectRequest $request, Group $group, GroupProject $project): RedirectResponse
    {
        $this->authorize('manageProjects', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);

        $this->projects->update($project, $request->user(), $request->validated());

        return back()->with('success', 'Project updated.');
    }

    public function attachArtwork(AttachArtworkToGroupProjectRequest $request, Group $group, GroupProject $project): RedirectResponse
    {
        $this->authorize('manageProjects', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);

        $artwork = Artwork::query()->findOrFail((int) $request->validated('artwork_id'));
        $this->projects->attachArtwork($project, $artwork, $request->user());

        return back()->with('success', 'Artwork attached to project.');
    }

    public function attachAsset(AttachAssetToGroupProjectRequest $request, Group $group, GroupProject $project): RedirectResponse
    {
        $this->authorize('attachAssetsToProjects', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);

        $asset = GroupAsset::query()->findOrFail((int) $request->validated('asset_id'));
        $this->projects->attachAsset($project, $asset, $request->user());

        return back()->with('success', 'Asset attached to project.');
    }

    public function status(UpdateGroupProjectStatusRequest $request, Group $group, GroupProject $project): RedirectResponse
    {
        $this->authorize('manageProjects', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);

        $this->projects->updateStatus($project, $request->user(), (string) $request->validated('status'));

        return back()->with('success', 'Project status updated.');
    }

    public function storeMilestone(StoreGroupMilestoneRequest $request, Group $group, GroupProject $project): RedirectResponse
    {
        $this->authorize('manageMilestones', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);

        $this->projects->createMilestone($project, $request->user(), $request->validated());

        return back()->with('success', 'Project milestone created.');
    }

    public function updateMilestone(UpdateGroupMilestoneRequest $request, Group $group, GroupProject $project, GroupProjectMilestone $milestone): RedirectResponse
    {
        $this->authorize('manageMilestones', $group);
        abort_unless((int) $project->group_id === (int) $group->id, 404);
        abort_unless((int) $milestone->group_project_id === (int) $project->id, 404);

        $this->projects->updateMilestone($milestone, $request->user(), $request->validated());

        return back()->with('success', 'Project milestone updated.');
    }
}