import React, { useEffect, useState } from 'react';
import { DistortionArea } from '../types/area';
import { DistortionEditorProps } from './types';
import { useDistortionEditor } from './hooks/useDistortionEditor';
import { EditorCanvas } from './components/EditorCanvas';
import { AreaList } from './components/AreaList';
import { ParameterPanel } from './components/ParameterPanel';
import { DEFAULT_AREA } from '../utils/constants';

export const DistortionEditor: React.FC<DistortionEditorProps> = ({
	initialAreas = [],
	imageSrc,
	onAreasChange,
	onSelectedAreaChange,
	width = 800,
	height = 600,
	canvasStyle,
}) => {
	const {
		state,
		selectArea,
		addArea,
		removeArea,
		updateArea,
		updatePoint,
		startDragging,
		stopDragging,
		getSelectedArea,
	} = useDistortionEditor(initialAreas);

	// 에디터 모드 토글 상태
	const [showEditor, setShowEditor] = useState(true);

	// 영역 변경 시 콜백 호출
	useEffect(() => {
		onAreasChange?.(state.areas);
	}, [state.areas, onAreasChange]);

	// 선택된 영역 변경 시 콜백 호출
	useEffect(() => {
		onSelectedAreaChange?.(state.selectedAreaId);
	}, [state.selectedAreaId, onSelectedAreaChange]);

	// 새 영역 추가 핸들러
	const handleAddArea = () => {
		const newArea: DistortionArea = {
			id: `area-${Date.now()}`,
			basePoints: [
				{ x: 0.3, y: 0.3 },
				{ x: 0.7, y: 0.3 },
				{ x: 0.7, y: 0.7 },
				{ x: 0.3, y: 0.7 },
			],
			movement: {
				vectorA: { x: DEFAULT_AREA.VECTOR_A.x, y: DEFAULT_AREA.VECTOR_A.y },
				vectorB: { x: DEFAULT_AREA.VECTOR_B.x, y: DEFAULT_AREA.VECTOR_B.y },
				duration: DEFAULT_AREA.DURATION,
				easing: DEFAULT_AREA.EASING as any,
			},
			distortionStrength: DEFAULT_AREA.DISTORTION_STRENGTH,
			progress: 0,
			dragVector: { x: 0, y: 0 },
		};
		addArea(newArea);
	};

	// 파라미터 업데이트 핸들러
	const handleUpdateArea = (updates: Partial<DistortionArea>) => {
		if (state.selectedAreaId) {
			updateArea(state.selectedAreaId, updates);
		}
	};

	const selectedArea = getSelectedArea();

	return (
		<div className="distortion-editor">
			{/* 에디터 모드 토글 버튼 */}
			<div className="editor-toolbar">
				<button
					className={`editor-toggle-btn ${showEditor ? 'active' : ''}`}
					onClick={() => setShowEditor(!showEditor)}
					title={showEditor ? '에디터 숨기기 (왜곡 효과만 보기)' : '에디터 표시'}
				>
					{showEditor ? '👁️ 에디터 숨기기' : '✏️ 에디터 표시'}
				</button>
			</div>

			<div className="editor-main">
				{/* 왼쪽: 캔버스 */}
				<div className="editor-canvas-container">
					<EditorCanvas
						areas={state.areas}
						selectedAreaId={state.selectedAreaId}
						imageSrc={imageSrc}
						width={width}
						height={height}
						onUpdatePoint={updatePoint}
						onUpdateArea={updateArea}
						draggingPointIndex={state.draggingPointIndex}
						onStartDragging={startDragging}
						onStopDragging={stopDragging}
						style={canvasStyle}
						showEditor={showEditor}
					/>
				</div>

				{/* 오른쪽: 사이드바 */}
				<div className="editor-sidebar">
					{/* 영역 목록 */}
					<AreaList
						areas={state.areas}
						selectedAreaId={state.selectedAreaId}
						onSelectArea={selectArea}
						onRemoveArea={removeArea}
						onAddArea={handleAddArea}
					/>

					{/* 파라미터 패널 */}
					<ParameterPanel area={selectedArea} onUpdateArea={handleUpdateArea} />
				</div>
			</div>
		</div>
	);
};
