<?php

namespace App\Http\Controllers\Api\Admin;

use App\Enums\InspectionCycle;
use App\Http\Controllers\Controller;
use App\Services\EquipmentInspectionService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class EquipmentInspectionController extends Controller
{
    public function __construct(
        private EquipmentInspectionService $inspectionService
    ) {}

    public function index(Request $request)
    {
        $cycle = $request->input('cycle', InspectionCycle::DAILY);
        $period = $request->input('period') ?? $request->input('year_month', now()->format('Y-m'));

        // daily가 아닌 주기에서 period가 없으면 현재 연도
        if ($cycle !== InspectionCycle::DAILY && ! $request->input('period')) {
            $period = now()->format('Y');
        }

        $productionLine = $request->input('production_line');
        $equipmentId = $request->input('equipment_id');

        $inspections = $this->inspectionService->getInspections(
            $cycle,
            $period,
            $productionLine,
            $equipmentId ? (int) $equipmentId : null
        );

        if ($request->header('HX-Request')) {
            $holidayDates = InspectionCycle::getHolidayDates($cycle, $period);

            return view('equipment.partials.inspection-grid', [
                'inspections' => $inspections,
                'cycle' => $cycle,
                'period' => $period,
                'holidayDates' => $holidayDates,
            ]);
        }

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

    public function toggleDetail(Request $request): JsonResponse
    {
        $request->validate([
            'equipment_id' => 'required|integer',
            'template_item_id' => 'required|integer',
            'check_date' => 'required|date',
            'cycle' => 'nullable|string',
        ]);

        try {
            $result = $this->inspectionService->toggleDetail(
                $request->input('equipment_id'),
                $request->input('template_item_id'),
                $request->input('check_date'),
                $request->input('cycle', InspectionCycle::DAILY)
            );

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            $status = $e->getMessage() === '점검 권한이 없습니다.' ? 403 : 400;

            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], $status);
        }
    }

    public function setResult(Request $request): JsonResponse
    {
        $request->validate([
            'equipment_id' => 'required|integer',
            'template_item_id' => 'required|integer',
            'check_date' => 'required|date',
            'cycle' => 'nullable|string',
            'result' => 'nullable|in:good,bad,repaired',
        ]);

        try {
            $result = $this->inspectionService->setResult(
                $request->input('equipment_id'),
                $request->input('template_item_id'),
                $request->input('check_date'),
                $request->input('cycle', InspectionCycle::DAILY),
                $request->input('result')
            );

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            $status = $e->getMessage() === '점검 권한이 없습니다.' ? 403 : 400;

            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], $status);
        }
    }

    public function updateNotes(Request $request): JsonResponse
    {
        $request->validate([
            'equipment_id' => 'required|integer',
            'year_month' => 'required|string',
            'cycle' => 'nullable|string',
            'overall_judgment' => 'nullable|in:OK,NG',
            'repair_note' => 'nullable|string',
            'issue_note' => 'nullable|string',
            'inspector_id' => 'nullable|integer',
        ]);

        try {
            $inspection = $this->inspectionService->updateInspectionNotes(
                $request->input('equipment_id'),
                $request->input('year_month'),
                $request->only(['overall_judgment', 'repair_note', 'issue_note', 'inspector_id']),
                $request->input('cycle', InspectionCycle::DAILY)
            );

            return response()->json([
                'success' => true,
                'message' => '점검 정보가 저장되었습니다.',
                'data' => $inspection,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function resetInspection(Request $request): JsonResponse
    {
        $request->validate([
            'equipment_id' => 'required|integer',
            'cycle' => 'required|string',
            'period' => 'required|string',
        ]);

        try {
            $deleted = $this->inspectionService->resetEquipmentInspection(
                $request->input('equipment_id'),
                $request->input('cycle'),
                $request->input('period')
            );

            return response()->json([
                'success' => true,
                'message' => "점검 데이터 {$deleted}건이 초기화되었습니다.",
                'data' => ['deleted' => $deleted],
            ]);
        } catch (\Exception $e) {
            $status = $e->getMessage() === '점검 권한이 없습니다.' ? 403 : 400;

            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], $status);
        }
    }

    public function resetAllInspections(Request $request): JsonResponse
    {
        $request->validate([
            'cycle' => 'required|string',
            'period' => 'required|string',
        ]);

        try {
            $deleted = $this->inspectionService->resetAllInspections(
                $request->input('cycle'),
                $request->input('period')
            );

            return response()->json([
                'success' => true,
                'message' => "전체 점검 데이터 {$deleted}건이 초기화되었습니다.",
                'data' => ['deleted' => $deleted],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function storeTemplate(Request $request, int $equipmentId): JsonResponse
    {
        $request->validate([
            'item_no' => 'required|integer',
            'inspection_cycle' => 'nullable|string',
            'check_point' => 'required|string|max:50',
            'check_item' => 'required|string|max:100',
            'check_timing' => 'nullable|in:operating,stopped',
            'check_frequency' => 'nullable|string|max:50',
            'check_method' => 'nullable|string',
            'sort_order' => 'nullable|integer',
        ]);

        try {
            $data = $request->all();
            if (empty($data['inspection_cycle'])) {
                $data['inspection_cycle'] = InspectionCycle::DAILY;
            }

            $template = $this->inspectionService->saveTemplate($equipmentId, $data);

            return response()->json([
                'success' => true,
                'message' => '점검항목이 추가되었습니다.',
                'data' => $template,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function updateTemplate(Request $request, int $templateId): JsonResponse
    {
        try {
            $template = $this->inspectionService->updateTemplate($templateId, $request->all());

            return response()->json([
                'success' => true,
                'message' => '점검항목이 수정되었습니다.',
                'data' => $template,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function copyTemplates(Request $request, int $equipmentId): JsonResponse
    {
        $request->validate([
            'source_cycle' => 'required|string',
            'target_cycles' => 'required|array|min:1',
            'target_cycles.*' => 'required|string',
        ]);

        try {
            $result = $this->inspectionService->copyTemplatesToCycles(
                $equipmentId,
                $request->input('source_cycle'),
                $request->input('target_cycles')
            );

            return response()->json([
                'success' => true,
                'message' => "{$result['copied']}개 항목이 복사되었습니다.".($result['skipped'] > 0 ? " (중복 {$result['skipped']}개 건너뜀)" : ''),
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function deleteTemplate(int $templateId): JsonResponse
    {
        try {
            $this->inspectionService->deleteTemplate($templateId);

            return response()->json([
                'success' => true,
                'message' => '점검항목이 삭제되었습니다.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }
}
