"use client";

import React, { useEffect, useState } from "react";
import { getLoadingUnitsByPkg, type LoadingUnitByPkg } from "@/lib/api/packaging";

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

export interface LoadingUnitSelection {
	loading_code: string;
	loading_name: string;
	loading_type: string;
	max_load_qty: number;
}

interface LoadingUnitModalProps {
	open: boolean;
	onClose: () => void;
	onSelect: (lu: LoadingUnitSelection) => void;
	onClear: () => void;
	pkgCodes: string[];
	currentLoading?: { loading_code: string; loading_name: string } | null;
}

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

export function LoadingUnitModal({
	open,
	onClose,
	onSelect,
	onClear,
	pkgCodes,
	currentLoading,
}: LoadingUnitModalProps) {
	const [units, setUnits] = useState<LoadingUnitByPkg[]>([]);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		if (!open || pkgCodes.length === 0) return;
		let cancelled = false;
		setLoading(true);

		const uniqueCodes = [...new Set(pkgCodes)];
		Promise.all(uniqueCodes.map((code) => getLoadingUnitsByPkg(code)))
			.then((results) => {
				if (cancelled) return;
				const merged = new Map<string, LoadingUnitByPkg>();
				results.forEach((res) => {
					res.data.forEach((lu) => {
						if (!merged.has(lu.loading_code)) {
							merged.set(lu.loading_code, lu);
						}
					});
				});
				setUnits(Array.from(merged.values()));
			})
			.catch(() => {
				if (!cancelled) setUnits([]);
			})
			.finally(() => {
				if (!cancelled) setLoading(false);
			});
		return () => {
			cancelled = true;
		};
	}, [open, pkgCodes]);

	if (!open) return null;

	return (
		<div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center">
			<div
				className="absolute inset-0 bg-black/50"
				onClick={onClose}
			/>
			<div className="relative bg-white w-full sm:max-w-md sm:rounded-2xl rounded-t-2xl max-h-[80vh] flex flex-col shadow-2xl z-10 overflow-hidden">
				{/* Header */}
				<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
					<h3 className="text-lg font-bold text-gray-900">
						적재함 선택
					</h3>
					<button
						onClick={onClose}
						className="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-gray-200 transition-colors"
					>
						<svg
							className="w-4 h-4"
							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>

				{/* Body */}
				<div className="flex-1 overflow-y-auto p-4">
					{loading ? (
						<div className="flex items-center justify-center py-8">
							<div className="w-6 h-6 border-2 border-purple-500 border-t-transparent rounded-full animate-spin" />
							<span className="ml-2 text-sm text-gray-500">
								불러오는 중...
							</span>
						</div>
					) : units.length === 0 ? (
						<p className="text-center text-sm text-gray-400 py-8">
							매칭된 적재함이 없습니다
						</p>
					) : (
						<div className="flex flex-col gap-2.5">
							{units.map((lu) => (
								<button
									key={lu.loading_code}
									onClick={() => {
										onSelect({
											loading_code: lu.loading_code,
											loading_name: lu.loading_name,
											loading_type: lu.loading_type,
											max_load_qty: lu.max_load_qty,
										});
										onClose();
									}}
									className={`flex items-center gap-3 p-3 border-2 rounded-xl bg-white text-left active:scale-[0.98] transition-all ${
										currentLoading?.loading_code === lu.loading_code
											? "border-purple-400 bg-purple-50"
											: "border-gray-200 hover:border-purple-400 hover:bg-purple-50"
									}`}
								>
									<span className="text-2xl shrink-0">
										{"\uD83D\uDEA2"}
									</span>
									<div className="flex-1 min-w-0">
										<p className="text-sm font-semibold text-gray-900 truncate">
											{lu.loading_name}
										</p>
										<p className="text-[11px] text-gray-400">
											{lu.loading_code} |{" "}
											{lu.loading_type || "-"}
										</p>
									</div>
									{lu.max_load_qty > 0 && (
										<span className="text-[10px] font-medium text-purple-600 bg-purple-50 px-2 py-1 rounded-full shrink-0">
											최대 {lu.max_load_qty}개
										</span>
									)}
								</button>
							))}
						</div>
					)}
				</div>

				{/* Footer — 해제 버튼 (적재함 이미 선택된 경우) */}
				{currentLoading && (
					<div className="px-4 pb-4">
						<button
							onClick={() => {
								onClear();
								onClose();
							}}
							className="w-full py-3 rounded-xl border-2 border-dashed border-gray-300 text-sm font-medium text-gray-500 hover:border-gray-400 hover:bg-gray-50 active:scale-[0.98] transition-all"
						>
							적재함 해제
						</button>
					</div>
				)}
			</div>
		</div>
	);
}
