"use client";

import React, { forwardRef, useState, useCallback, useEffect } from "react";
import { DashboardElement, ElementType, ElementSubtype, DragData } from "./types";
import { CanvasElement } from "./CanvasElement";
import { GRID_CONFIG, snapToGrid } from "./gridUtils";

interface DashboardCanvasProps {
  elements: DashboardElement[];
  selectedElement: string | null;
  onCreateElement: (type: ElementType, subtype: ElementSubtype, x: number, y: number) => void;
  onUpdateElement: (id: string, updates: Partial<DashboardElement>) => void;
  onRemoveElement: (id: string) => void;
  onSelectElement: (id: string | null) => void;
  onConfigureElement?: (element: DashboardElement) => void;
  backgroundColor?: string;
}

/**
 * 대시보드 캔버스 컴포넌트
 * - 드래그 앤 드롭 영역
 * - 12 컬럼 그리드 배경
 * - 스냅 기능
 * - 요소 배치 및 관리
 */
export const DashboardCanvas = forwardRef<HTMLDivElement, DashboardCanvasProps>(
  (
    {
      elements,
      selectedElement,
      onCreateElement,
      onUpdateElement,
      onRemoveElement,
      onSelectElement,
      onConfigureElement,
      backgroundColor = '#f9fafb',
    },
    ref,
  ) => {
    const [isDragOver, setIsDragOver] = useState(false);

    // 드래그 오버 처리
    const handleDragOver = useCallback((e: React.DragEvent) => {
      e.preventDefault();
      e.dataTransfer.dropEffect = "copy";
      setIsDragOver(true);
    }, []);

    // 드래그 리브 처리
    const handleDragLeave = useCallback((e: React.DragEvent) => {
      if (e.currentTarget === e.target) {
        setIsDragOver(false);
      }
    }, []);

    // 드롭 처리 (그리드 스냅 적용)
    const handleDrop = useCallback(
      (e: React.DragEvent) => {
        e.preventDefault();
        setIsDragOver(false);

        try {
          const dragData: DragData = JSON.parse(e.dataTransfer.getData("application/json"));

          if (!ref || typeof ref === "function") return;

          const rect = ref.current?.getBoundingClientRect();
          if (!rect) return;

          // 캔버스 스크롤을 고려한 정확한 위치 계산
          const rawX = e.clientX - rect.left + (ref.current?.scrollLeft || 0);
          const rawY = e.clientY - rect.top + (ref.current?.scrollTop || 0);

          // 그리드에 스냅 (고정 셀 크기 사용)
          const snappedX = snapToGrid(rawX, GRID_CONFIG.CELL_SIZE);
          const snappedY = snapToGrid(rawY, GRID_CONFIG.CELL_SIZE);

          onCreateElement(dragData.type, dragData.subtype, snappedX, snappedY);
        } catch (error) {
          // console.error('드롭 데이터 파싱 오류:', error);
        }
      },
      [ref, onCreateElement],
    );

    // 캔버스 클릭 시 선택 해제
    const handleCanvasClick = useCallback(
      (e: React.MouseEvent) => {
        if (e.target === e.currentTarget) {
          onSelectElement(null);
        }
      },
      [onSelectElement],
    );

    // 고정 그리드 크기
    const cellWithGap = GRID_CONFIG.CELL_SIZE + GRID_CONFIG.GAP;
    const gridSize = `${cellWithGap}px ${cellWithGap}px`;

    // 캔버스 높이를 요소들의 최대 y + height 기준으로 계산 (최소 화면 높이 보장)
    const minCanvasHeight = Math.max(
      typeof window !== "undefined" ? window.innerHeight : 800,
      ...elements.map((el) => el.position.y + el.size.height + 100), // 하단 여백 100px
    );

    return (
      <div
        ref={ref}
        className={`relative rounded-lg shadow-inner ${isDragOver ? "bg-blue-50/50" : ""} `}
        style={{
          backgroundColor,
          width: `${GRID_CONFIG.CANVAS_WIDTH}px`,
          minHeight: `${minCanvasHeight}px`,
          // 12 컬럼 그리드 배경
          backgroundImage: `
            linear-gradient(rgba(59, 130, 246, 0.15) 1px, transparent 1px),
            linear-gradient(90deg, rgba(59, 130, 246, 0.15) 1px, transparent 1px)
          `,
          backgroundSize: gridSize,
          backgroundPosition: "0 0",
          backgroundRepeat: "repeat",
        }}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={handleCanvasClick}
      >
        {/* 배치된 요소들 렌더링 */}
        {elements.map((element) => (
          <CanvasElement
            key={element.id}
            element={element}
            isSelected={selectedElement === element.id}
            cellSize={GRID_CONFIG.CELL_SIZE}
            onUpdate={onUpdateElement}
            onRemove={onRemoveElement}
            onSelect={onSelectElement}
            onConfigure={onConfigureElement}
          />
        ))}
      </div>
    );
  },
);

DashboardCanvas.displayName = "DashboardCanvas";
