"use client";

import type { Block, FormInputBlockProps } from "@/features/editor/state/editorStore";
import { ColorPickerField, TEXT_COLOR_PALETTE } from "@/features/editor/components/ColorPickerField";
import { NumericPropertyControl } from "@/features/editor/components/NumericPropertyControl";

interface FormInputPropertiesPanelProps {
	block: Block;
	selectedBlockId: string | null;
	updateBlock: (id: string, partial: any) => void;
}

export function FormInputPropertiesPanel({ block, selectedBlockId, updateBlock }: FormInputPropertiesPanelProps) {
	if (!selectedBlockId || block.id !== selectedBlockId || block.type !== "formInput") return null;

	const inputProps = block.props as FormInputBlockProps;
	const labelDisplay = inputProps.labelDisplay ?? "visible";

	return (
		<div className="space-y-3 text-xs">
			<h3 className="text-[11px] font-semibold text-slate-200">입력 필드</h3>
			<label className="flex flex-col gap-1">
				<span className="text-slate-400">라벨 타입</span>
				<select
					className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] outline-none focus:border-sky-500"
					value={inputProps.labelMode ?? "text"}
					onChange={(e) =>
						updateBlock(selectedBlockId, {
							labelMode: e.target.value,
						} as any)
					}
				>
					<option value="text">텍스트</option>
					<option value="image">이미지</option>
				</select>
			</label>
			<label className="flex flex-col gap-1">
				<span className="text-slate-400">필드 라벨</span>
				<input
					className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-xs outline-none focus:border-sky-500"
					value={inputProps.label ?? ""}
					onChange={(e) =>
						updateBlock(selectedBlockId, {
							label: e.target.value,
						} as any)
					}
				/>
			</label>
			<label className="flex flex-col gap-1">
				<span className="text-slate-400">라벨 표시 방식</span>
				<select
					className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] outline-none focus:border-sky-500"
					value={labelDisplay}
					onChange={(e) =>
						updateBlock(selectedBlockId, {
							labelDisplay: e.target.value,
						} as any)
					}
				>
					<option value="visible">표시 (기본)</option>
					<option value="hidden">숨김</option>
					<option value="floating">플로팅 라벨</option>
				</select>
			</label>
			{labelDisplay === "visible" && (
				<label className="flex flex-col gap-1 text-[11px] text-slate-400">
					<span>레이아웃</span>
					<select
						className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] outline-none focus:border-sky-500"
						value={inputProps.labelLayout ?? "stacked"}
						onChange={(e) =>
							updateBlock(selectedBlockId, {
								labelLayout: e.target.value,
							} as any)
						}
					>
						<option value="stacked">세로 (기본)</option>
						<option value="inline">가로 (인라인)</option>
					</select>
				</label>
			)}
			{labelDisplay === "visible" && (inputProps.labelLayout ?? "stacked") === "inline" && (
				<NumericPropertyControl
					label="라벨/필드 간격 (px)"
					unitLabel="(px)"
					value={typeof inputProps.labelGapPx === "number" ? inputProps.labelGapPx : 8}
					min={0}
					max={80}
					step={2}
					presets={[
						{ id: "tight", label: "타이트", value: 4 },
						{ id: "normal", label: "보통", value: 8 },
						{ id: "relaxed", label: "느슨", value: 12 },
						{ id: "extra", label: "넓게", value: 16 },
					]}
					onChangeValue={(v) =>
						updateBlock(selectedBlockId, {
							labelGapPx: v,
						} as any)
					}
				/>
			)}
			{inputProps.labelMode === "image" && (
				<>
					<label className="flex flex-col gap-1">
						<span className="text-slate-400">라벨 이미지 URL</span>
						<input
							className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-xs outline-none focus:border-sky-500"
							value={inputProps.labelImageUrl ?? ""}
							onChange={(e) =>
								updateBlock(selectedBlockId, {
									labelImageUrl: e.target.value,
								} as any)
							}
						/>
					</label>
					<label className="flex flex-col gap-1">
						<span className="text-slate-400">라벨 이미지 대체 텍스트</span>
						<input
							className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-xs outline-none focus:border-sky-500"
							value={inputProps.labelImageAlt ?? ""}
							onChange={(e) =>
								updateBlock(selectedBlockId, {
									labelImageAlt: e.target.value,
								} as any)
							}
						/>
					</label>
				</>
			)}
			<label className="flex flex-col gap-1">
				<span className="text-slate-400">전송 키</span>
				<input
					className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-xs outline-none focus:border-sky-500"
					value={inputProps.formFieldName ?? ""}
					onChange={(e) =>
						updateBlock(selectedBlockId, {
							formFieldName: e.target.value,
						} as any)
					}
				/>
			</label>
			<label className="flex flex-col gap-1">
				<span className="text-slate-400">필드 타입</span>
				<select
					className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] outline-none focus:border-sky-500"
					aria-label="필드 타입"
					value={inputProps.inputType ?? "text"}
					onChange={(e) =>
						updateBlock(selectedBlockId, {
							inputType: e.target.value,
						} as any)
					}
				>
					<option value="text">텍스트</option>
					<option value="email">이메일</option>
					<option value="textarea">긴 텍스트</option>
				</select>
			</label>
			<label className="flex flex-col gap-1">
				<span className="text-slate-400">Placeholder</span>
				<input
					className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-xs outline-none focus:border-sky-500"
					aria-label="Placeholder"
					value={inputProps.placeholder ?? ""}
					onChange={(e) =>
						updateBlock(selectedBlockId, {
							placeholder: e.target.value,
						} as any)
					}
				/>
			</label>
			<label className="inline-flex items-center gap-2">
				<span className="text-slate-500">필수 여부는 폼 컨트롤러에서 설정합니다.</span>
			</label>
			<div className="mt-3 space-y-2 border-t border-slate-800 pt-3">
				<h4 className="text-[11px] font-semibold text-slate-200">필드 스타일</h4>
				<NumericPropertyControl
					label="필드 텍스트 크기 (px)"
					unitLabel="(px)"
					value={(() => {
						const raw = inputProps.fontSizeCustom ?? "";
						const match = raw.match(/([0-9]+(?:\.[0-9]+)?)/);
						if (match) return Number(match[1]);
						return 14;
					})()}
					min={8}
					max={40}
					step={1}
					presets={[
						{ id: "xs", label: "XS", value: 12 },
						{ id: "sm", label: "S", value: 14 },
						{ id: "md", label: "M", value: 16 },
						{ id: "lg", label: "L", value: 18 },
						{ id: "xl", label: "XL", value: 20 },
					]}
					onChangeValue={(v) => {
						updateBlock(selectedBlockId, {
							fontSizeCustom: `${v}px`,
						} as any);
					}}
				/>
				{/* 줄간격 px 입력을 노출하여 preview em 변환의 근거를 제공 */}
				<NumericPropertyControl
					label="필드 줄간격 (px)"
					unitLabel="(px)"
					value={(() => {
						const raw = inputProps.lineHeightCustom ?? "";
						const match = raw.match(/([0-9]+(?:\.[0-9]+)?)/);
						if (match) return Number(match[1]);
						return 20;
					})()}
					min={8}
					max={60}
					step={1}
					presets={[
						{ id: "tight", label: "타이트", value: 18 },
						{ id: "normal", label: "보통", value: 24 },
						{ id: "loose", label: "루즈", value: 32 },
					]}
					onChangeValue={(v) => {
						updateBlock(selectedBlockId, {
							lineHeightCustom: `${v}px`,
						} as any);
					}}
				/>
				{/* 자간 px 입력으로 폼 입력 타이포를 세밀하게 조정 */}
				<NumericPropertyControl
					label="필드 자간 (px)"
					unitLabel="(px)"
					value={(() => {
						const raw = inputProps.letterSpacingCustom ?? "";
						const match = raw.match(/(-?[0-9]+(?:\.[0-9]+)?)/);
						if (match) return Number(match[1]);
						return 0;
					})()}
					min={-10}
					max={20}
					step={0.5}
					presets={[
						{ id: "tight", label: "좁게", value: -1 },
						{ id: "normal", label: "보통", value: 0 },
						{ id: "wide", label: "넓게", value: 2 },
					]}
					onChangeValue={(v) => {
						updateBlock(selectedBlockId, {
							letterSpacingCustom: `${v}px`,
						} as any);
					}}
				/>
				<label className="flex flex-col gap-1 text-[11px] text-slate-400">
					<span>텍스트 정렬</span>
					<select
						className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] outline-none focus:border-sky-500"
						value={inputProps.align ?? "left"}
						onChange={(e) =>
							updateBlock(selectedBlockId, {
								align: e.target.value,
							} as any)
						}
					>
						<option value="left">왼쪽</option>
						<option value="center">가운데</option>
						<option value="right">오른쪽</option>
					</select>
				</label>
				<label className="flex flex-col gap-1 text-[11px] text-slate-400">
					<span>너비</span>
					<select
						className="w-full rounded border border-slate-700 bg-slate-950 px-2 py-1 text-[11px] outline-none focus:border-sky-500"
						value={inputProps.widthMode ?? "full"}
						onChange={(e) =>
							updateBlock(selectedBlockId, {
								widthMode: e.target.value,
							} as any)
						}
					>
						<option value="auto">자동</option>
						<option value="full">전체 폭</option>
						<option value="fixed">고정 값</option>
					</select>
				</label>
				<NumericPropertyControl
					label="필드 고정 너비"
					unitLabel="(px)"
					value={inputProps.widthPx ?? 240}
					min={80}
					max={800}
					step={10}
					presets={[
						{ id: "sm", label: "작게", value: 200 },
						{ id: "md", label: "보통", value: 280 },
						{ id: "lg", label: "넓게", value: 360 },
					]}
					onChangeValue={(v) => {
						updateBlock(selectedBlockId, {
							widthPx: v,
						} as any);
					}}
				/>
				<NumericPropertyControl
					label="필드 가로 패딩 (px)"
					unitLabel="(px)"
					value={typeof inputProps.paddingX === "number" ? inputProps.paddingX : 12}
					min={0}
					max={60}
					step={2}
					presets={[
						{ id: "xs", label: "아주 얇게", value: 6 },
						{ id: "sm", label: "얇게", value: 10 },
						{ id: "md", label: "보통", value: 12 },
						{ id: "lg", label: "넓게", value: 16 },
						{ id: "xl", label: "아주 넓게", value: 20 },
					]}
					onChangeValue={(v) => {
						updateBlock(selectedBlockId, {
							paddingX: v,
						} as any);
					}}
				/>
				<NumericPropertyControl
					label="필드 세로 패딩 (px)"
					unitLabel="(px)"
					value={typeof inputProps.paddingY === "number" ? inputProps.paddingY : 10}
					min={0}
					max={40}
					step={1}
					presets={[
						{ id: "xs", label: "아주 얇게", value: 6 },
						{ id: "sm", label: "얇게", value: 8 },
						{ id: "md", label: "보통", value: 10 },
						{ id: "lg", label: "넓게", value: 12 },
						{ id: "xl", label: "아주 넓게", value: 16 },
					]}
					onChangeValue={(v) => {
						updateBlock(selectedBlockId, {
							paddingY: v,
						} as any);
					}}
				/>
				<ColorPickerField
					label="필드 텍스트 색상"
					ariaLabelColorInput="필드 텍스트 색상 피커"
					ariaLabelHexInput="필드 텍스트 색상 HEX"
					value={
						inputProps.textColorCustom && inputProps.textColorCustom.trim() !== ""
							? inputProps.textColorCustom
							: "#f9fafb"
					}
					onChange={(hex) => {
						updateBlock(selectedBlockId, {
							textColorCustom: hex,
						} as any);
					}}
					palette={TEXT_COLOR_PALETTE}
					onPaletteSelect={(item) => {
						updateBlock(selectedBlockId, {
							textColorCustom: item.color,
						} as any);
					}}
				/>
				<ColorPickerField
					label="필드 채움 색상"
					ariaLabelColorInput="필드 채움 색상 피커"
					ariaLabelHexInput="필드 채움 색상 HEX"
					value={
						inputProps.fillColorCustom && inputProps.fillColorCustom.trim() !== ""
							? inputProps.fillColorCustom
							: TEXT_COLOR_PALETTE[0]?.color ?? "#0ea5e9"
					}
					onChange={(hex) => {
						updateBlock(selectedBlockId, {
							fillColorCustom: hex,
						} as any);
					}}
					palette={TEXT_COLOR_PALETTE}
					onPaletteSelect={(item) => {
						updateBlock(selectedBlockId, {
							fillColorCustom: item.color,
						} as any);
					}}
				/>
				<ColorPickerField
					label="필드 테두리 색상"
					ariaLabelColorInput="필드 테두리 색상 피커"
					ariaLabelHexInput="필드 테두리 색상 HEX"
					value={
						inputProps.strokeColorCustom && inputProps.strokeColorCustom.trim() !== ""
							? inputProps.strokeColorCustom
							: TEXT_COLOR_PALETTE[0]?.color ?? "#0ea5e9"
					}
					onChange={(hex) => {
						updateBlock(selectedBlockId, {
							strokeColorCustom: hex,
						} as any);
					}}
					palette={TEXT_COLOR_PALETTE}
					onPaletteSelect={(item) => {
						updateBlock(selectedBlockId, {
							strokeColorCustom: item.color,
						} as any);
					}}
				/>
				<NumericPropertyControl
					label="필드 모서리 둥글기"
					value={(() => {
						const r = inputProps.borderRadius ?? "md";
						return r === "none" ? 0 : r === "sm" ? 2 : r === "lg" ? 6 : r === "full" ? 8 : 4;
					})()}
					min={0}
					max={8}
					step={1}
					presets={[
						{ id: "none", label: "없음", value: 0 },
						{ id: "sm", label: "작게", value: 2 },
						{ id: "md", label: "보통", value: 4 },
						{ id: "lg", label: "크게", value: 6 },
						{ id: "full", label: "완전 둥글게", value: 8 },
					]}
					onChangeValue={(v) => {
						const next =
							v <= 0 ? "none" : v <= 2 ? "sm" : v <= 5 ? "md" : v <= 7 ? "lg" : "full";
						updateBlock(selectedBlockId, {
							borderRadius: next,
						} as any);
					}}
				/>
			</div>
		</div>
	);
}
