"use client";

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

/* ================================================================== */
/* Material Qty Keypad (±20% 범위 안내 포함)                            */
/* ================================================================== */

function MaterialQtyKeypad({
	open,
	onClose,
	onConfirm,
	initialValue,
	unit,
	requiredQty,
	itemName,
}: {
	open: boolean;
	onClose: () => void;
	onConfirm: (val: string) => void;
	initialValue: string;
	unit: string;
	requiredQty: number;
	itemName: string;
}) {
	const [val, setVal] = useState(initialValue || "0");

	useEffect(() => {
		if (open) setVal(initialValue || "0");
	}, [open, initialValue]);

	const press = (k: string) => {
		setVal((prev) => {
			if (k === "backspace") return prev.length <= 1 ? "0" : prev.slice(0, -1);
			if (k === "clear") return "0";
			if (k === "dot") return prev.includes(".") ? prev : prev + ".";
			if (k === "ref") return String(requiredQty);
			if (prev === "0" && k !== ".") return k;
			return prev + k;
		});
	};

	if (!open) return null;
	const numVal = parseFloat(val);
	const lower = requiredQty * 0.8;
	const upper = requiredQty * 1.2;
	const outOfRange = !isNaN(numVal) && (numVal < lower || numVal > upper);

	return (
		<div className="fixed inset-0 z-[60] flex items-center justify-center">
			<div className="absolute inset-0 bg-black/40" onClick={onClose} />
			<div className="relative bg-white rounded-2xl shadow-2xl p-4 w-[320px] z-10">
				<div className="text-center mb-3">
					<p className="text-sm text-gray-500 truncate">{itemName}</p>
					<p className="text-xs text-blue-500 mt-0.5">
						기준 {requiredQty} {unit} (±20%)
					</p>
					<p
						className={`text-3xl font-bold mt-2 ${outOfRange ? "text-amber-600" : "text-gray-900"}`}
						style={{ fontVariantNumeric: "tabular-nums" }}
					>
						{val} <span className="text-base text-gray-400">{unit}</span>
					</p>
				</div>
				<div className="grid grid-cols-3 gap-2 mb-3">
					{["1", "2", "3", "4", "5", "6", "7", "8", "9"].map((k) => (
						<button
							key={k}
							onClick={() => press(k)}
							className="h-14 rounded-xl bg-gray-100 text-xl font-bold text-gray-800 active:scale-95 active:bg-gray-200 transition-all"
						>
							{k}
						</button>
					))}
					<button
						onClick={() => press("dot")}
						className="h-14 rounded-xl bg-gray-100 text-xl font-bold text-gray-800 active:scale-95 transition-all"
					>
						.
					</button>
					<button
						onClick={() => press("0")}
						className="h-14 rounded-xl bg-gray-100 text-xl font-bold text-gray-800 active:scale-95 transition-all"
					>
						0
					</button>
					<button
						onClick={() => press("backspace")}
						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-2">
					<button
						onClick={() => press("clear")}
						className="flex-1 h-10 rounded-xl bg-gray-100 text-gray-600 text-sm font-bold active:scale-95"
					>
						초기화
					</button>
					<button
						onClick={() => press("ref")}
						className="flex-1 h-10 rounded-xl bg-blue-50 text-blue-600 text-sm font-bold active:scale-95"
					>
						기준값 ({requiredQty})
					</button>
				</div>
				<div className="flex gap-2">
					<button
						onClick={onClose}
						className="flex-1 h-12 rounded-xl bg-gray-100 text-gray-700 font-semibold active:scale-95"
					>
						취소
					</button>
					<button
						onClick={() => {
							onConfirm(val);
							onClose();
						}}
						className="flex-1 h-12 rounded-xl text-white font-bold active:scale-95"
						style={{
							background: outOfRange
								? "linear-gradient(135deg, #f59e0b, #d97706)"
								: "linear-gradient(135deg, #3b82f6, #1d4ed8)",
						}}
					>
						{outOfRange ? "확인 (범위 외)" : "확인"}
					</button>
				</div>
			</div>
		</div>
	);
}

/* ================================================================== */
/* Material Qty Input Row (키패드 트리거 버튼)                          */
/* ================================================================== */

function MaterialQtyInputRow({
	material,
	value,
	onChange,
}: {
	material: {
		id: string;
		child_item_name: string;
		required_qty: number;
		unit: string;
	};
	value: string;
	onChange: (v: string) => void;
}) {
	const [open, setOpen] = useState(false);
	return (
		<div className="flex items-center shrink-0">
			<button
				type="button"
				onClick={() => setOpen(true)}
				className="px-8 py-4 rounded-xl border-2 border-blue-300 text-xl font-bold text-blue-700 hover:border-blue-500 active:scale-[0.96] transition-all bg-blue-50 min-w-[120px] text-center"
			>
				{value || <span className="text-blue-300 font-semibold">입력</span>}
			</button>
			<MaterialQtyKeypad
				open={open}
				onClose={() => setOpen(false)}
				onConfirm={onChange}
				initialValue={value}
				unit={material.unit}
				requiredQty={material.required_qty}
				itemName={material.child_item_name}
			/>
		</div>
	);
}

/* ================================================================== */
/* Material Input Section                                              */
/* ================================================================== */

/**
 * Phase B-1: ProcessWork.tsx L2810-2993에서 분리.
 * BOM 자재 조회/투입 — processId 외 props 없음 (원본 시그니처 유지).
 * 원본 동작 그대로: 자체 state + 자체 API 호출, peSettings.materialInput 판별은 상위(ProcessWork)에서 수행.
 *
 * 신 구조: processId = wop_result.id (접수 카드 id).
 * 백엔드 /pop/production/bom-materials/:id, /material-inputs/:id,
 * /material-input (body.work_order_process_id) 모두 wop_result.id 해석.
 */
export function MaterialInputSection({ processId }: { processId: string }) {
	const [bomMaterials, setBomMaterials] = useState<
		Array<{
			id: string;
			child_item_id: string;
			child_item_code: string;
			child_item_name: string;
			bom_qty: number;
			unit: string;
			required_qty: number;
			input_qty: number;
		}>
	>([]);
	const [inputValues, setInputValues] = useState<Record<string, string>>({});
	const [inputted, setInputted] = useState<
		Array<{
			id: string;
			item_code: string;
			item_name: string;
			input_qty: string;
			unit: string;
			recorded_at: string;
		}>
	>([]);
	const [loading, setLoading] = useState(true);
	const [saving, setSaving] = useState(false);
	const [defaultWarehouseCode, setDefaultWarehouseCode] = useState<string>("");

	useEffect(() => {
		const fetchData = async () => {
			setLoading(true);
			try {
				const [bomRes, inputRes, whRes] = await Promise.all([
					apiClient.get(`/pop/production/bom-materials/${processId}`),
					apiClient.get(`/pop/production/material-inputs/${processId}`),
					apiClient.get("/pop/production/warehouses"),
				]);
				setBomMaterials(bomRes.data?.data?.materials || []);
				setInputted(inputRes.data?.data || []);
				const wh = whRes.data?.data?.[0];
				if (wh?.warehouse_code) setDefaultWarehouseCode(wh.warehouse_code);
			} catch {
				/* non-critical */
			}
			setLoading(false);
		};
		fetchData();
	}, [processId]);

	const handleSave = async () => {
		const inputs = bomMaterials
			.filter((m) => {
				const val = parseFloat(inputValues[m.id] || "0");
				return val > 0;
			})
			.map((m) => ({
				child_item_id: m.child_item_id,
				child_item_code: m.child_item_code,
				child_item_name: m.child_item_name,
				input_qty: parseFloat(inputValues[m.id] || "0"),
				unit: m.unit,
				bom_detail_id: m.id,
				required_qty: m.required_qty,
				warehouse_code: defaultWarehouseCode || undefined,
				location_code: defaultWarehouseCode || undefined,
			}));

		if (inputs.length === 0) {
			toast.warning("투입 수량을 입력해주세요.");
			return;
		}

		setSaving(true);
		try {
			const res = await apiClient.post("/pop/production/material-input", {
				work_order_process_id: processId,
				inputs,
			});
			if (res.data?.success) {
				toast.success(res.data.message || "투입 완료");
				setInputValues({});
				const inputRes = await apiClient.get(
					`/pop/production/material-inputs/${processId}`,
				);
				setInputted(inputRes.data?.data || []);
			} else {
				toast.error(res.data?.message || "투입 실패");
			}
		} catch {
			toast.error("투입 중 오류");
		}
		setSaving(false);
	};

	if (loading) {
		return (
			<div className="text-center py-8 text-gray-400">자재 정보 조회중...</div>
		);
	}

	return (
		<div className="space-y-3">
			{/* BOM 기준 자재 목록 — 컴팩트 */}
			<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-3">
				<div className="flex items-center justify-between mb-2">
					<h3 className="text-sm font-bold text-gray-900">BOM 자재 목록</h3>
					<span className="text-xs text-gray-400">{bomMaterials.length}건</span>
				</div>
				{bomMaterials.length === 0 ? (
					<p className="text-sm text-gray-400 py-4 text-center">
						BOM 자재 정보가 없습니다
					</p>
				) : (
					<div>
						<div className="divide-y divide-gray-200">
							{bomMaterials.map((m) => (
								<div key={m.id} className="flex items-center gap-2 py-3">
									<div className="flex-1 min-w-0">
										<span className="text-base font-bold text-gray-900">
											{m.child_item_name}
										</span>
										<span className="text-sm text-gray-400 ml-1">
											({m.child_item_code})
										</span>
										<span className="text-base font-bold text-blue-600 ml-3">
											소요 {m.required_qty}
										</span>
									</div>
									<MaterialQtyInputRow
										material={m}
										value={inputValues[m.id] || ""}
										onChange={(v) =>
											setInputValues((prev) => ({ ...prev, [m.id]: v }))
										}
									/>
									<span className="text-base font-semibold text-gray-500 shrink-0 w-8">
										{m.unit}
									</span>
								</div>
							))}
						</div>
						<button
							onClick={handleSave}
							disabled={saving}
							className="w-full mt-4 py-4 rounded-xl text-lg font-bold text-white active:scale-[0.98] transition-all disabled:opacity-40"
							style={{
								background: "linear-gradient(135deg, #3b82f6, #1d4ed8)",
							}}
						>
							{saving ? "저장중..." : "자재 투입 확정"}
						</button>
					</div>
				)}
			</div>

			{/* 투입 이력 */}
			{inputted.length > 0 && (
				<div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-4">
					<h3 className="text-base font-bold text-gray-900 mb-3">투입 이력</h3>
					{inputted.map((item) => (
						<div
							key={item.id}
							className="flex items-center justify-between py-2 border-b border-gray-100 last:border-0"
						>
							<div>
								<p className="text-sm font-semibold text-gray-900">
									{item.item_name}
								</p>
								<p className="text-xs text-gray-400">{item.item_code}</p>
							</div>
							<p className="text-base font-bold text-green-600">
								{item.input_qty} {item.unit}
							</p>
						</div>
					))}
				</div>
			)}
		</div>
	);
}
