<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreProjectRequest;
use App\Http\Requests\UpdateProjectRequest;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use App\Models\User;
use App\Services\ActivityLogService;
use App\Services\NotificationService;
use App\Services\ProjectProgressService;
use App\Services\ResourceAccessService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProjectController extends Controller
{
    public function __construct(
        protected ActivityLogService $activityLogService,
        protected NotificationService $notificationService,
        protected ProjectProgressService $projectProgressService,
        protected ResourceAccessService $resourceAccess,
    ) {}

    public function index(Request $request): JsonResponse
    {
        try {
            $query = $this->resourceAccess->projects($request->user())
                ->with(['projectManager', 'creator', 'department']);

            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }
            if ($request->filled('priority')) {
                $query->where('priority', $request->priority);
            }
            if ($request->filled('project_manager_id')) {
                $query->where('project_manager_id', $request->project_manager_id);
            }
            if ($request->filled('risk_level')) {
                $query->where('risk_level', $request->risk_level);
            }
            if ($request->filled('search')) {
                $search = $request->search;
                $query->where('title', 'like', "%{$search}%");
            }

            $perPage = min((int) $request->input('per_page', 15), 100);
            $sortBy = in_array($request->input('sort_by'), ['id', 'title', 'status', 'priority', 'created_at', 'updated_at', 'start_date', 'end_date'], true)
                ? $request->input('sort_by')
                : 'created_at';
            $sortDir = $request->input('sort_dir') === 'asc' ? 'asc' : 'desc';
            $projects = $query->orderBy($sortBy, $sortDir)->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => ProjectResource::collection($projects),
                'meta' => [
                    'current_page' => $projects->currentPage(),
                    'last_page' => $projects->lastPage(),
                    'per_page' => $projects->perPage(),
                    'total' => $projects->total(),
                ],
                'message' => 'لیست پروژه‌ها',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت لیست پروژه‌ها',
            ], 500);
        }
    }

    public function show(Project $project): JsonResponse
    {
        try {
            $project->load(['projectManager', 'creator', 'department', 'members', 'tasks', 'sprints', 'meetings']);

            return response()->json([
                'success' => true,
                'data' => new ProjectResource($project),
                'message' => 'اطلاعات پروژه',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در دریافت اطلاعات پروژه',
            ], 500);
        }
    }

    public function store(StoreProjectRequest $request): JsonResponse
    {
        try {
            $data = $request->validated();
            $data['created_by'] = $request->user()->id;
            $project = Project::create($data);
            $project->load(['projectManager', 'creator', 'department']);

            $this->activityLogService->log(
                $request->user()->id,
                'create_project',
                "پروژه {$project->title} ایجاد شد",
                'project',
                $project->id,
                $project->id,
                null,
                ['project_title' => $project->title]
            );

            return response()->json([
                'success' => true,
                'data' => new ProjectResource($project),
                'message' => 'پروژه با موفقیت ایجاد شد',
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در ایجاد پروژه',
            ], 500);
        }
    }

    public function update(UpdateProjectRequest $request, Project $project): JsonResponse
    {
        try {
            $project->update($request->validated());
            $project->load(['projectManager', 'creator', 'department']);

            $this->activityLogService->log(
                $request->user()->id,
                'update_project',
                "پروژه {$project->title} به‌روزرسانی شد",
                'project',
                $project->id,
                $project->id,
                null,
                ['project_title' => $project->title]
            );

            return response()->json([
                'success' => true,
                'data' => new ProjectResource($project->fresh()),
                'message' => 'پروژه با موفقیت به‌روزرسانی شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی پروژه',
            ], 500);
        }
    }

    public function destroy(Request $request, Project $project): JsonResponse
    {
        try {
            $projectTitle = $project->title;
            $project->delete();

            $this->activityLogService->log(
                $request->user()->id,
                'delete_project',
                "پروژه {$projectTitle} حذف شد",
                'project',
                $project->id,
                $project->id,
                null,
                ['project_title' => $projectTitle]
            );

            return response()->json([
                'success' => true,
                'message' => 'پروژه با موفقیت حذف شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف پروژه',
            ], 500);
        }
    }

    public function archive(Request $request, Project $project): JsonResponse
    {
        try {
            $project->update(['is_archived' => true]);

            return response()->json([
                'success' => true,
                'data' => new ProjectResource($project->fresh()),
                'message' => 'پروژه بایگانی شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در بایگانی پروژه',
            ], 500);
        }
    }

    public function restore(Request $request, Project $project): JsonResponse
    {
        try {
            $project->update(['is_archived' => false]);

            return response()->json([
                'success' => true,
                'data' => new ProjectResource($project->fresh()),
                'message' => 'پروژه از بایگانی خارج شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در بازیابی پروژه',
            ], 500);
        }
    }

    public function addMember(Request $request, Project $project): JsonResponse
    {
        try {
            $request->validate([
                'user_id' => 'required|exists:users,id',
                'role_in_project' => 'nullable|string',
            ]);

            $project->members()->syncWithoutDetaching([
                $request->user_id => [
                    'role_in_project' => $request->role_in_project ?? 'member',
                ],
            ]);

            $this->activityLogService->log(
                $request->user()->id,
                'add_member',
                "عضو جدید به پروژه {$project->title} اضافه شد",
                'project',
                $project->id,
                $project->id,
                null,
                ['user_id' => $request->user_id]
            );

            return response()->json([
                'success' => true,
                'data' => new ProjectResource($project->fresh()->load(['projectManager', 'creator', 'department', 'members'])),
                'message' => 'عضو با موفقیت اضافه شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در اضافه کردن عضو',
            ], 500);
        }
    }

    public function removeMember(Request $request, Project $project, User $user): JsonResponse
    {
        try {
            $project->members()->detach($user->id);

            $this->activityLogService->log(
                $request->user()->id,
                'remove_member',
                "عضو از پروژه {$project->title} حذف شد",
                'project',
                $project->id,
                $project->id,
                null,
                ['user_id' => $user->id]
            );

            return response()->json([
                'success' => true,
                'message' => 'عضو با موفقیت حذف شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در حذف عضو',
            ], 500);
        }
    }

    public function updateProgress(Request $request, Project $project): JsonResponse
    {
        try {
            $progress = $this->projectProgressService->calculateProgress($project->id);

            return response()->json([
                'success' => true,
                'data' => ['progress' => $progress],
                'message' => 'پیشرفت پروژه به‌روزرسانی شد',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'خطا در به‌روزرسانی پیشرفت',
            ], 500);
        }
    }
}
