"use client";

import React, { useCallback, useEffect, useState } from "react";
import { apiClient } from "@/lib/api/client";

/* ------------------------------------------------------------------ */
/* Types                                                               */
/* ------------------------------------------------------------------ */

export interface InspectionItem {
	id: string;
	inspection_item_name: string;
	inspection_standard: string;
	inspection_method: string;
	pass_criteria: string;
	is_required: string;
	/** User-entered measured value */
	measured_value: string;
	/** "pass" | "fail" | null */
	result: "pass" | "fail" | null;
}

export interface InspectionResult {
	items: InspectionItem[];
	goodQty: number;
	badQty: number;
	remark: string;
	completed: boolean;
	inspectionNumber?: string; // 검사 완료 시 채번 받음 (재사용)
}

interface InspectionModalProps {
	open: boolean;
	onClose: () => void;
	onComplete: (result: InspectionResult) => void;
	onCancel?: () => void; // 취소 = 검사 무효화 (완료 → 대기)
	itemCode: string;
	itemName: string;
	totalQty: number;
	initialResult?: InspectionResult | null;
}

/* ------------------------------------------------------------------ */
/* Dummy inspection items (fallback)                                   */
/* ------------------------------------------------------------------ */

const DUMMY_INSPECTION_ITEMS: InspectionItem[] = [
	{
		id: "dummy-1",
		inspection_item_name: "외관 검사",
		inspection_standard: "스크래치, 변색, 찍힘 없음",
		inspection_method: "육안 검사",
		pass_criteria: "이상 없음",
		is_required: "Y",
		measured_value: "",
		result: null,
	},
	{
		id: "dummy-2",
		inspection_item_name: "치수 검사",
		inspection_standard: "규격 +-0.5mm",
		inspection_method: "캘리퍼스 측정",
		pass_criteria: "허용 오차 이내",
		is_required: "Y",
		measured_value: "",
		result: null,
	},
	{
		id: "dummy-3",
		inspection_item_name: "수량 검사",
		inspection_standard: "발주 수량과 일치",
		inspection_method: "전수 검사",
		pass_criteria: "수량 일치",
		is_required: "Y",
		measured_value: "",
		result: null,
	},
	{
		id: "dummy-4",
		inspection_item_name: "포장 상태",
		inspection_standard: "포장 손상 없음",
		inspection_method: "육안 검사",
		pass_criteria: "이상 없음",
		is_required: "",
		measured_value: "",
		result: null,
	},
];

/* ------------------------------------------------------------------ */
/* Component                                                           */
/* ------------------------------------------------------------------ */

export function InspectionModal({
	open,
	onClose,
	onComplete,
	onCancel,
	itemCode,
	itemName,
	totalQty,
	initialResult,
}: InspectionModalProps) {
	const [inspItems, setInspItems] = useState<InspectionItem[]>([]);
	const [loading, setLoading] = useState(false);
	const [goodQty, setGoodQty] = useState(0);
	const [badQty, setBadQty] = useState(0);
	/* NumPad state */
	const [numpadOpen, setNumpadOpen] = useState(false);
	const [numpadTitle, setNumpadTitle] = useState("");
	const [numpadValue, setNumpadValue] = useState("");
	const [numpadMax, setNumpadMax] = useState<number | undefined>(undefined);
	const numpadCallbackRef = React.useRef<((val: string) => void) | null>(null);

	const openNumpad = (
		title: string,
		currentValue: string | number,
		onConfirm: (v: string) => void,
		max?: number,
	) => {
		setNumpadTitle(title);
		setNumpadValue(String(currentValue || ""));
		setNumpadMax(max);
		numpadCallbackRef.current = onConfirm;
		setNumpadOpen(true);
	};
	const [remark, setRemark] = useState("");

	/* Fetch inspection items from DB */
	const fetchInspectionItems = useCallback(async () => {
		setLoading(true);
		try {
			const res = await apiClient.get("/pop/inspection-result/info", {
				params: { itemCode },
			});
			const data = res.data?.data;
			if (Array.isArray(data) && data.length > 0) {
				setInspItems(
					data.map((r: Record<string, unknown>) => ({
						id: String(r.id ?? ""),
						inspection_item_name: String(r.inspection_item_name ?? ""),
						inspection_standard: String(r.inspection_standard ?? ""),
						inspection_method: String(r.inspection_method ?? ""),
						pass_criteria: String(r.pass_criteria ?? ""),
						is_required: String(r.is_required ?? "Y"),
						measured_value: "",
						result: null,
					})),
				);
			} else {
				setInspItems(DUMMY_INSPECTION_ITEMS.map((i) => ({ ...i })));
			}
		} catch {
			setInspItems(DUMMY_INSPECTION_ITEMS.map((i) => ({ ...i })));
		} finally {
			setLoading(false);
		}
	}, [itemCode]);

	/* Init on open */
	useEffect(() => {
		if (!open) return;
		if (initialResult) {
			setInspItems(initialResult.items.map((i) => ({ ...i })));
			setGoodQty(initialResult.goodQty);
			setBadQty(initialResult.badQty);
			setRemark(initialResult.remark);
		} else {
			fetchInspectionItems();
			setGoodQty(totalQty);
			setBadQty(0);
			setRemark("");
		}
	}, [open, initialResult, fetchInspectionItems, totalQty]);

	/* Update item */
	const updateItem = (
		id: string,
		field: "measured_value" | "result",
		value: string,
	) => {
		setInspItems((prev) =>
			prev.map((item) =>
				item.id === id
					? {
							...item,
							[field]:
								field === "result"
									? item.result === value
										? null
										: value
									: value,
						}
					: item,
			),
		);
	};

	/* Handle good/bad qty sync */
	const handleGoodQtyChange = (val: number) => {
		const v = Math.max(0, Math.min(val, totalQty));
		setGoodQty(v);
		setBadQty(totalQty - v);
	};

	const handleBadQtyChange = (val: number) => {
		const v = Math.max(0, Math.min(val, totalQty));
		setBadQty(v);
		setGoodQty(totalQty - v);
	};

	/* 검사 완료 가능 여부: 필수 항목이 모두 pass */
	const canComplete = inspItems
		.filter((it) => it.is_required === "Y")
		.every((it) => it.result === "pass");

	/* Complete */
	const [allocating, setAllocating] = useState(false);
	const handleComplete = async () => {
		if (!canComplete) return;
		setAllocating(true);
		try {
			// 1. 기존 inspectionNumber 있으면 재사용, 없으면 채번 호출
			let inspectionNumber = initialResult?.inspectionNumber;
			if (!inspectionNumber) {
				try {
					const res = await apiClient.post(
						"/pop/inspection-result/allocate-number",
					);
					inspectionNumber = res.data?.data?.inspectionNumber;
				} catch (err) {
					console.error("[검사번호 채번 실패]", err);
				}
			}
			// 2. 결과 전달 (채번 포함)
			onComplete({
				items: inspItems,
				goodQty,
				badQty,
				remark,
				completed: true,
				inspectionNumber,
			});
			onClose();
		} finally {
			setAllocating(false);
		}
	};

	if (!open) return null;

	return (
		<div className="fixed inset-0 z-50" onClick={onClose}>
			{/* Overlay */}
			<div className="absolute inset-0 bg-black/40" />

			{/* Bottom sheet */}
			<div
				className="absolute bottom-0 left-1/2 -translate-x-1/2 w-full max-w-2xl bg-white rounded-t-3xl shadow-2xl flex flex-col z-10"
				style={{ maxHeight: "90vh" }}
				onClick={(e) => e.stopPropagation()}
			>
				{/* Handle bar */}
				<div className="pt-3 pb-2 flex justify-center rounded-t-3xl shrink-0">
					<div className="w-10 h-1 rounded-full bg-gray-300" />
				</div>

				{/* Header */}
				<div className="flex items-center justify-between px-5 pb-3 border-b border-gray-100 shrink-0">
					<h3 className="text-lg font-bold text-gray-900">자주검사</h3>
					<button
						onClick={onClose}
						className="w-9 h-9 rounded-lg flex items-center justify-center text-gray-400 hover:bg-gray-100 transition-colors"
					>
						<svg
							className="w-5 h-5"
							fill="none"
							stroke="currentColor"
							strokeWidth={2}
							viewBox="0 0 24 24"
						>
							<path
								strokeLinecap="round"
								strokeLinejoin="round"
								d="M6 18L18 6M6 6l12 12"
							/>
						</svg>
					</button>
				</div>

				{/* Scrollable body */}
				<div className="flex-1 overflow-y-auto px-5 py-4 bg-gray-50">
					{/* Item summary */}
					<div
						className="flex flex-wrap items-center gap-2 px-3.5 py-2.5 mb-4 rounded-lg border border-sky-200"
						style={{
							background: "linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%)",
						}}
					>
						<span className="text-xs font-semibold text-sky-700 bg-white px-2 py-0.5 rounded shrink-0">
							{itemCode}
						</span>
						<span className="text-sm font-semibold text-gray-900 flex-1 truncate min-w-0">
							{itemName}
						</span>
						<span className="text-sm font-bold text-green-600 shrink-0">
							{totalQty.toLocaleString()} EA
						</span>
					</div>

					{/* Inspection items section */}
					<div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
						<div className="flex items-center justify-between mb-3">
							<h4 className="text-sm font-semibold text-gray-700">검사 항목</h4>
							<span className="text-xs text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full">
								{inspItems.length}개
							</span>
						</div>

						{loading ? (
							<div className="flex items-center justify-center py-8 text-sm text-gray-400">
								<svg
									className="animate-spin w-5 h-5 mr-2 text-blue-500"
									fill="none"
									viewBox="0 0 24 24"
								>
									<circle
										className="opacity-25"
										cx="12"
										cy="12"
										r="10"
										stroke="currentColor"
										strokeWidth="4"
									/>
									<path
										className="opacity-75"
										fill="currentColor"
										d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
									/>
								</svg>
								불러오는 중...
							</div>
						) : inspItems.length === 0 ? (
							<div className="text-center py-6 text-sm text-gray-400">
								등록된 검사 항목이 없습니다
							</div>
						) : (
							<div className="flex flex-col gap-2.5 max-h-[300px] overflow-y-auto">
								{inspItems.map((item) => (
									<div
										key={item.id}
										className={`bg-gray-50 border rounded-lg p-3 ${
											item.is_required === "Y"
												? "border-l-[3px] border-l-red-400 border-gray-200"
												: "border-gray-200"
										}`}
									>
										{/* Item header */}
										<div className="flex items-start justify-between mb-2">
											<span className="text-[13px] font-semibold text-gray-900">
												{item.inspection_item_name}
											</span>
											{item.is_required === "Y" && (
												<span className="text-[10px] px-1.5 py-0.5 rounded bg-red-100 text-red-600 font-semibold shrink-0 ml-2">
													필수
												</span>
											)}
										</div>

										{/* Info grid */}
										<div className="grid grid-cols-[auto_1fr] gap-x-2.5 gap-y-1 text-xs mb-2.5">
											{item.inspection_standard && (
												<>
													<span className="text-gray-400">기준</span>
													<span className="text-gray-700">
														{item.inspection_standard}
													</span>
												</>
											)}
											{item.inspection_method && (
												<>
													<span className="text-gray-400">방법</span>
													<span className="text-gray-700">
														{item.inspection_method}
													</span>
												</>
											)}
											{item.pass_criteria && (
												<>
													<span className="text-gray-400">판정</span>
													<span className="text-gray-700">
														{item.pass_criteria}
													</span>
												</>
											)}
										</div>

										{/* Input + result buttons */}
										<div className="flex items-center gap-2">
											<button
												type="button"
												onClick={() =>
													openNumpad(
														`${item.inspection_item_name} - 측정값`,
														item.measured_value,
														(v) => updateItem(item.id, "measured_value", v),
													)
												}
												className={`flex-1 h-9 px-2.5 text-[13px] border rounded-md text-left transition-all ${
													item.measured_value
														? "bg-blue-50 border-blue-200 text-blue-700 font-semibold"
														: "bg-white border-gray-200 text-gray-400 hover:border-blue-300"
												}`}
											>
												{item.measured_value || "측정값 입력"}
											</button>
											<div className="flex gap-1">
												<button
													onClick={() => updateItem(item.id, "result", "pass")}
													className={`w-9 h-9 rounded-md border text-base flex items-center justify-center transition-all ${
														item.result === "pass"
															? "bg-green-100 border-green-400 text-green-700"
															: "border-gray-200 text-gray-400 hover:bg-green-50 hover:border-green-300"
													}`}
												>
													{"\u2713"}
												</button>
												<button
													onClick={() => updateItem(item.id, "result", "fail")}
													className={`w-9 h-9 rounded-md border text-base flex items-center justify-center transition-all ${
														item.result === "fail"
															? "bg-red-100 border-red-400 text-red-700"
															: "border-gray-200 text-gray-400 hover:bg-red-50 hover:border-red-300"
													}`}
												>
													{"\u2717"}
												</button>
											</div>
											{/* Camera placeholder */}
											<button
												className="w-9 h-9 rounded-md border border-gray-200 text-gray-400 flex items-center justify-center hover:bg-gray-50 transition-colors"
												title="사진 촬영 (준비 중)"
											>
												<svg
													className="w-4 h-4"
													fill="none"
													stroke="currentColor"
													strokeWidth={2}
													viewBox="0 0 24 24"
												>
													<path
														strokeLinecap="round"
														strokeLinejoin="round"
														d="M6.827 6.175A2.31 2.31 0 015.186 7.23c-.38.054-.757.112-1.134.175C2.999 7.58 2.25 8.507 2.25 9.574V18a2.25 2.25 0 002.25 2.25h15A2.25 2.25 0 0021.75 18V9.574c0-1.067-.75-1.994-1.802-2.169a47.865 47.865 0 00-1.134-.175 2.31 2.31 0 01-1.64-1.055l-.822-1.316a2.192 2.192 0 00-1.736-1.039 48.774 48.774 0 00-5.232 0 2.192 2.192 0 00-1.736 1.039l-.821 1.316z"
													/>
													<path
														strokeLinecap="round"
														strokeLinejoin="round"
														d="M16.5 12.75a4.5 4.5 0 11-9 0 4.5 4.5 0 019 0z"
													/>
												</svg>
											</button>
										</div>
									</div>
								))}
							</div>
						)}
					</div>

					{/* Final judgment section */}
					<div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
						<h4 className="text-sm font-semibold text-gray-700 mb-3">
							종합 판정
						</h4>

						{/* Good / Bad qty */}
						<div className="grid grid-cols-2 gap-3 mb-3">
							<div className="flex flex-col gap-1">
								<label className="text-[11px] font-semibold text-green-600">
									양품 수량
								</label>
								<div className="flex items-center gap-1">
									<button
										type="button"
										onClick={() =>
											openNumpad(
												"양품 수량",
												goodQty,
												(v) => handleGoodQtyChange(parseInt(v, 10) || 0),
												totalQty,
											)
										}
										className="flex-1 min-w-0 h-10 px-2 text-center text-sm font-semibold border-2 border-green-400 rounded-lg bg-green-50 text-green-700 hover:bg-green-100 transition-all"
									>
										{goodQty.toLocaleString()}
									</button>
									<span className="text-[11px] text-gray-500 shrink-0">EA</span>
								</div>
							</div>
							<div className="flex flex-col gap-1">
								<label className="text-[11px] font-semibold text-red-600">
									불량 수량
								</label>
								<div className="flex items-center gap-1">
									<button
										type="button"
										onClick={() =>
											openNumpad(
												"불량 수량",
												badQty,
												(v) => handleBadQtyChange(parseInt(v, 10) || 0),
												totalQty,
											)
										}
										className="flex-1 min-w-0 h-10 px-2 text-center text-sm font-semibold border-2 border-red-400 rounded-lg bg-red-50 text-red-700 hover:bg-red-100 transition-all"
									>
										{badQty.toLocaleString()}
									</button>
									<span className="text-[11px] text-gray-500 shrink-0">EA</span>
								</div>
							</div>
						</div>

						{/* Total summary */}
						<div className="flex items-center justify-between px-3 py-2 bg-gray-50 rounded-lg border border-gray-200">
							<span className="text-[13px] text-gray-500">전체 수량</span>
							<span className="text-[15px] font-bold text-gray-900">
								{totalQty.toLocaleString()} EA
							</span>
						</div>
					</div>

					{/* Remark */}
					<div className="bg-white rounded-xl border border-gray-200 p-3.5 mb-4">
						<h4 className="text-sm font-semibold text-gray-700 mb-2">비고</h4>
						<textarea
							value={remark}
							onChange={(e) => setRemark(e.target.value)}
							placeholder="검사 관련 특이사항 입력"
							rows={3}
							className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg outline-none focus:border-blue-400 focus:ring-1 focus:ring-blue-100 resize-none"
						/>
					</div>
				</div>

				{/* Footer */}
				<div className="flex gap-2.5 px-5 py-4 border-t border-gray-200 bg-white shrink-0">
					<button
						onClick={() => {
							if (initialResult?.completed && onCancel) {
								// 이미 완료된 검사 → 무효화 (완료 → 대기로 풀림)
								onCancel();
							}
							onClose();
						}}
						className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-600 hover:bg-gray-50 active:scale-[0.98] transition-all"
					>
						{initialResult?.completed ? "검사 취소" : "취소"}
					</button>
					<button
						className="flex-1 h-12 rounded-xl border border-gray-200 text-sm font-semibold text-gray-500 hover:bg-gray-50 active:scale-[0.98] transition-all"
						title="준비 중"
					>
						성적서 출력
					</button>
					<button
						onClick={handleComplete}
						disabled={!canComplete || allocating}
						className={`flex-[2] h-12 rounded-xl text-sm font-bold text-white transition-all ${
							!canComplete || allocating
								? "opacity-40 cursor-not-allowed"
								: "active:scale-[0.98]"
						}`}
						style={{
							background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
							boxShadow:
								!canComplete || allocating
									? "none"
									: "0 4px 12px rgba(59,130,246,.3)",
						}}
						title={
							!canComplete
								? "필수 검사 항목을 모두 합격(✓)으로 체크해주세요"
								: ""
						}
					>
						{allocating ? "처리 중..." : "검사 완료"}
					</button>
				</div>
			</div>

			{/* ===== NumPad ===== */}
			{numpadOpen && (
				<div
					className="absolute inset-0 z-20 flex items-end justify-center"
					onClick={() => setNumpadOpen(false)}
				>
					<div className="absolute inset-0 bg-black/40" />
					<div
						className="absolute bottom-0 left-1/2 -translate-x-1/2 w-full max-w-md bg-white rounded-t-3xl shadow-2xl flex flex-col z-30"
						onClick={(e) => e.stopPropagation()}
					>
						<div className="pt-3 pb-2 flex justify-center">
							<div className="w-10 h-1 rounded-full bg-gray-300" />
						</div>
						<div className="flex items-center justify-between px-5 pb-3 border-b border-gray-100">
							<h4 className="text-base font-bold text-gray-900">
								{numpadTitle}
							</h4>
							<button
								onClick={() => setNumpadOpen(false)}
								className="w-8 h-8 rounded-lg flex items-center justify-center text-gray-400 hover:bg-gray-100"
							>
								<svg
									className="w-5 h-5"
									fill="none"
									stroke="currentColor"
									strokeWidth={2}
									viewBox="0 0 24 24"
								>
									<path
										strokeLinecap="round"
										strokeLinejoin="round"
										d="M6 18L18 6M6 6l12 12"
									/>
								</svg>
							</button>
						</div>
						<div className="px-5 pt-4 pb-2">
							<div className="h-16 flex items-center justify-end px-4 bg-gray-50 rounded-xl border-2 border-gray-200 mb-3">
								<span
									className="text-3xl font-bold text-gray-900"
									style={{ fontVariantNumeric: "tabular-nums" }}
								>
									{numpadValue || "0"}
								</span>
							</div>
							{numpadMax !== undefined && (
								<p className="text-[11px] text-gray-400 text-right mb-2">
									최대 {numpadMax.toLocaleString()}
								</p>
							)}
						</div>
						<div className="px-5 pb-5">
							<div className="grid grid-cols-3 gap-2 mb-2">
								{["7", "8", "9", "4", "5", "6", "1", "2", "3"].map((k) => (
									<button
										key={k}
										onClick={() =>
											setNumpadValue((v) => (v === "0" || v === "" ? k : v + k))
										}
										className="h-14 rounded-xl bg-gray-100 text-2xl font-bold text-gray-800 active:scale-95 active:bg-gray-200 transition-all"
									>
										{k}
									</button>
								))}
								<button
									onClick={() =>
										setNumpadValue((v) =>
											v.includes(".") ? v : (v || "0") + ".",
										)
									}
									className="h-14 rounded-xl bg-gray-100 text-2xl font-bold text-gray-800 active:scale-95 transition-all"
								>
									.
								</button>
								<button
									onClick={() =>
										setNumpadValue((v) =>
											v === "0" || v === "" ? "0" : v + "0",
										)
									}
									className="h-14 rounded-xl bg-gray-100 text-2xl font-bold text-gray-800 active:scale-95 transition-all"
								>
									0
								</button>
								<button
									onClick={() =>
										setNumpadValue((v) => (v.length <= 1 ? "" : v.slice(0, -1)))
									}
									className="h-14 rounded-xl bg-gray-200 text-base font-bold text-gray-600 active:scale-95 transition-all"
								>
									←
								</button>
							</div>
							<div className="flex gap-2 mb-3">
								<button
									onClick={() => setNumpadValue("")}
									className="flex-1 h-11 rounded-xl bg-gray-100 text-gray-600 text-sm font-bold active:scale-95"
								>
									초기화
								</button>
								{numpadMax !== undefined && (
									<button
										onClick={() => setNumpadValue(String(numpadMax))}
										className="flex-1 h-11 rounded-xl bg-blue-50 text-blue-600 text-sm font-bold active:scale-95"
									>
										최대 ({numpadMax})
									</button>
								)}
							</div>
							<button
								onClick={() => {
									if (numpadCallbackRef.current) {
										let val = numpadValue;
										if (numpadMax !== undefined) {
											const n = parseInt(val, 10) || 0;
											val = String(Math.min(n, numpadMax));
										}
										numpadCallbackRef.current(val);
									}
									setNumpadOpen(false);
								}}
								className="w-full h-12 rounded-xl text-sm font-bold text-white active:scale-95 transition-all"
								style={{
									background: "linear-gradient(to bottom, #60a5fa, #2563eb)",
								}}
							>
								확인
							</button>
						</div>
					</div>
				</div>
			)}
		</div>
	);
}
