<?php

namespace App\Http\Controllers\Api\Admin;

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)
    {
        $yearMonth = $request->input('year_month', now()->format('Y-m'));
        $productionLine = $request->input('production_line');
        $equipmentId = $request->input('equipment_id');

        $inspections = $this->inspectionService->getMonthlyInspections(
            $yearMonth,
            $productionLine,
            $equipmentId ? (int) $equipmentId : null
        );

        if ($request->header('HX-Request')) {
            return view('equipment.partials.inspection-grid', [
                'inspections' => $inspections,
                'yearMonth' => $yearMonth,
            ]);
        }

        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',
        ]);

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

            return response()->json([
                'success' => true,
                'data' => $result,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ], 400);
        }
    }

    public function updateNotes(Request $request): JsonResponse
    {
        $request->validate([
            'equipment_id' => 'required|integer',
            'year_month' => 'required|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'])
            );

            return response()->json([
                'success' => true,
                'message' => '점검 정보가 저장되었습니다.',
                'data' => $inspection,
            ]);
        } 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',
            '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 {
            $template = $this->inspectionService->saveTemplate($equipmentId, $request->all());

            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 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);
        }
    }
}
