<?php

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

use App\Http\Controllers\Controller;
use App\Http\Requests\ProjectManagement\BulkActionRequest;
use App\Http\Requests\ProjectManagement\StoreIssueRequest;
use App\Http\Requests\ProjectManagement\UpdateIssueRequest;
use App\Models\Admin\AdminPmIssue;
use App\Services\ProjectManagement\IssueService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class IssueController extends Controller
{
    public function __construct(
        private readonly IssueService $issueService
    ) {}

    /**
     * 이슈 목록 (HTMX용)
     */
    public function index(Request $request): View|JsonResponse
    {
        $filters = $request->only([
            'project_id', 'task_id', 'search', 'type',
            'status', 'open_only', 'trashed', 'sort_by', 'sort_direction',
        ]);
        $issues = $this->issueService->getIssues($filters, 15);
        $types = AdminPmIssue::getTypes();
        $statuses = AdminPmIssue::getStatuses();

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

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

    /**
     * 프로젝트별 이슈 목록
     */
    public function byProject(int $projectId, Request $request): JsonResponse
    {
        $issues = $this->issueService->getIssuesByProject($projectId);

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

    /**
     * 작업별 이슈 목록
     */
    public function byTask(int $taskId, Request $request): View|JsonResponse
    {
        $issues = $this->issueService->getIssuesByTask($taskId);
        $types = AdminPmIssue::getTypes();
        $statuses = AdminPmIssue::getStatuses();

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

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

    /**
     * 열린 이슈 목록 (대시보드용)
     */
    public function open(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');
        $limit = $request->input('limit', 10);
        $issues = $this->issueService->getOpenIssues($projectId, $limit);

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

    /**
     * 이슈 통계
     */
    public function stats(Request $request): JsonResponse
    {
        $projectId = $request->input('project_id');

        if ($projectId) {
            $stats = $this->issueService->getIssueStatsByProject($projectId);
        } else {
            $stats = $this->issueService->getIssueStats();
        }

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

    /**
     * 이슈 상세 조회
     */
    public function show(int $id): JsonResponse
    {
        $issue = $this->issueService->getIssueById($id, true);

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

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

    /**
     * 이슈 생성
     */
    public function store(StoreIssueRequest $request): JsonResponse
    {
        $issue = $this->issueService->createIssue($request->validated());

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

    /**
     * 이슈 수정
     */
    public function update(UpdateIssueRequest $request, int $id): JsonResponse
    {
        $this->issueService->updateIssue($id, $request->validated());

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

    /**
     * 이슈 삭제 (Soft Delete)
     */
    public function destroy(int $id): JsonResponse
    {
        $this->issueService->deleteIssue($id);

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

    /**
     * 이슈 복원
     */
    public function restore(int $id): JsonResponse
    {
        $this->issueService->restoreIssue($id);

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

    /**
     * 이슈 영구 삭제
     */
    public function forceDestroy(int $id): JsonResponse
    {
        $this->issueService->forceDeleteIssue($id);

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

    /**
     * 이슈 상태 변경
     */
    public function changeStatus(Request $request, int $id): JsonResponse
    {
        $validated = $request->validate([
            'status' => 'required|in:open,in_progress,resolved,closed',
        ]);

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

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

    /**
     * 이슈 긴급 토글
     */
    public function toggleUrgent(int $id): JsonResponse
    {
        $issue = $this->issueService->toggleUrgent($id);

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

    /**
     * 이슈 일괄 처리
     */
    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->issueService->bulkChangeStatus($ids, $value),
            'change_type' => $this->issueService->bulkChangeType($ids, $value),
            'link_task' => $this->issueService->bulkLinkToTask($ids, $value),
            'delete' => $this->issueService->bulkDelete($ids),
            'restore' => $this->issueService->bulkRestore($ids),
            default => 0,
        };

        $messages = [
            'change_status' => '상태가 변경되었습니다.',
            'change_type' => '타입이 변경되었습니다.',
            'link_task' => '작업 연결이 변경되었습니다.',
            'delete' => '삭제되었습니다.',
            'restore' => '복원되었습니다.',
        ];

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