<?php

namespace App\Http\Controllers\Api\Admin\ProjectManagement;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProjectManagement\BulkActionRequest;
use App\Http\Requests\ProjectManagement\StoreTaskRequest;
use App\Http\Requests\ProjectManagement\UpdateTaskRequest;
use App\Services\ProjectManagement\TaskService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class TaskController extends Controller
{
    public function __construct(
        private readonly TaskService $taskService
    ) {}

    /**
     * 작업 목록 (HTMX용)
     */
    public function index(Request $request): View|JsonResponse
    {
        $filters = $request->only([
            'project_id', 'search', 'status', 'priority',
            'assignee_id', 'due_status', 'trashed', 'sort_by', 'sort_direction',
        ]);
        $tasks = $this->taskService->getTasks($filters, 15);

        // HTMX 요청이면 HTML 파셜 반환
        if ($request->header('HX-Request')) {
            return view('project-management.tasks.partials.table', compact('tasks'));
        }

        return response()->json([
            'success' => true,
            'data' => $tasks,
        ]);
    }

    /**
     * 프로젝트별 작업 목록 (칸반보드용)
     */
    public function byProject(int $projectId, Request $request): JsonResponse
    {
        $tasks = $this->taskService->getTasksByProject($projectId);

        return response()->json([
            'success' => true,
            'data' => $tasks,
        ]);
    }

    /**
     * 마감 임박/지연 작업 목록
     */
    public function urgent(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');
        $urgentTasks = $this->taskService->getUrgentTasks($projectId);

        return response()->json([
            'success' => true,
            'data' => $urgentTasks,
        ]);
    }

    /**
     * 작업 상세 조회
     */
    public function show(int $id): JsonResponse
    {
        $task = $this->taskService->getTaskById($id, true);

        if (! $task) {
            return response()->json([
                'success' => false,
                'message' => '작업을 찾을 수 없습니다.',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $task,
        ]);
    }

    /**
     * 작업 생성
     */
    public function store(StoreTaskRequest $request): JsonResponse
    {
        $task = $this->taskService->createTask($request->validated());

        return response()->json([
            'success' => true,
            'message' => '작업이 생성되었습니다.',
            'data' => $task,
        ]);
    }

    /**
     * 작업 수정
     */
    public function update(UpdateTaskRequest $request, int $id): JsonResponse
    {
        $this->taskService->updateTask($id, $request->validated());

        return response()->json([
            'success' => true,
            'message' => '작업이 수정되었습니다.',
        ]);
    }

    /**
     * 작업 삭제 (Soft Delete)
     */
    public function destroy(int $id): JsonResponse
    {
        $this->taskService->deleteTask($id);

        return response()->json([
            'success' => true,
            'message' => '작업이 삭제되었습니다.',
        ]);
    }

    /**
     * 작업 복원
     */
    public function restore(int $id): JsonResponse
    {
        $this->taskService->restoreTask($id);

        return response()->json([
            'success' => true,
            'message' => '작업이 복원되었습니다.',
        ]);
    }

    /**
     * 작업 영구 삭제
     */
    public function forceDestroy(int $id): JsonResponse
    {
        $this->taskService->forceDeleteTask($id);

        return response()->json([
            'success' => true,
            'message' => '작업이 영구 삭제되었습니다.',
        ]);
    }

    /**
     * 작업 상태 변경
     */
    public function changeStatus(Request $request, int $id): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'required|in:todo,in_progress,done',
        ]);

        $task = $this->taskService->changeStatus($id, $validated['status']);

        return response()->json([
            'success' => true,
            'message' => '작업 상태가 변경되었습니다.',
            'data' => $task,
        ]);
    }

    /**
     * 작업 긴급 토글
     */
    public function toggleUrgent(int $id): JsonResponse
    {
        $task = $this->taskService->toggleUrgent($id);

        return response()->json([
            'success' => true,
            'message' => $task->is_urgent ? '긴급으로 설정되었습니다.' : '긴급 해제되었습니다.',
            'data' => $task,
        ]);
    }

    /**
     * 작업 순서 변경 (드래그앤드롭)
     */
    public function reorder(Request $request, int $projectId): JsonResponse
    {
        $validated = $request->validate([
            'task_ids' => 'required|array',
            'task_ids.*' => 'integer',
        ]);

        $this->taskService->reorderTasks($projectId, $validated['task_ids']);

        return response()->json([
            'success' => true,
            'message' => '작업 순서가 변경되었습니다.',
        ]);
    }

    /**
     * 작업 일괄 처리
     */
    public function bulk(BulkActionRequest $request): JsonResponse
    {
        $data = $request->validated();
        $ids = $data['ids'];
        $action = $data['action'];
        $value = $data['value'] ?? null;

        $count = match ($action) {
            'change_status' => $this->taskService->bulkChangeStatus($ids, $value),
            'change_priority' => $this->taskService->bulkChangePriority($ids, $value),
            'change_assignee' => $this->taskService->bulkChangeAssignee($ids, $value),
            'delete' => $this->taskService->bulkDelete($ids),
            'restore' => $this->taskService->bulkRestore($ids),
            default => 0,
        };

        $messages = [
            'change_status' => '상태가 변경되었습니다.',
            'change_priority' => '우선순위가 변경되었습니다.',
            'change_assignee' => '담당자가 변경되었습니다.',
            'delete' => '삭제되었습니다.',
            'restore' => '복원되었습니다.',
        ];

        return response()->json([
            'success' => true,
            'message' => "{$count}개 작업이 ".$messages[$action],
            'data' => ['affected' => $count],
        ]);
    }

    /**
     * 프로젝트별 작업 통계
     */
    public function stats(int $projectId): JsonResponse
    {
        $stats = $this->taskService->getTaskStatsByProject($projectId);

        return response()->json([
            'success' => true,
            'data' => $stats,
        ]);
    }
}
