"use client";

import React from "react";
import { cn } from "@/lib/utils";
import { LayoutRow } from "@/types/grid-system";
import { ComponentData } from "@/types/screen";
import { GAP_PRESETS, buildGridClasses } from "@/lib/constants/columnSpans";
import { RealtimePreviewDynamic } from "./RealtimePreviewDynamic";

interface LayoutRowRendererProps {
  row: LayoutRow;
  components: Map<string, ComponentData>;
  isSelected: boolean;
  selectedComponentId?: string;
  onSelectRow: () => void;
  onSelectComponent: (componentId: string) => void;
  onUpdateRow?: (row: LayoutRow) => void;
}

export const LayoutRowRenderer: React.FC<LayoutRowRendererProps> = ({
  row,
  components,
  isSelected,
  selectedComponentId,
  onSelectRow,
  onSelectComponent,
  onUpdateRow,
}) => {
  // 행 클래스 생성
  const rowClasses = cn(
    // 그리드 기본
    "grid grid-cols-12 w-full relative",

    // Gap (컴포넌트 간격)
    GAP_PRESETS[row.gap].class,

    // Padding
    GAP_PRESETS[row.padding].class.replace("gap-", "p-"),

    // 높이
    row.height === "auto" && "h-auto",
    row.height === "fixed" && row.fixedHeight && `h-[${row.fixedHeight}px]`,
    row.height === "min" && row.minHeight && `min-h-[${row.minHeight}px]`,
    row.height === "max" && row.maxHeight && `max-h-[${row.maxHeight}px]`,

    // 수평 정렬
    row.alignment === "start" && "justify-items-start",
    row.alignment === "center" && "justify-items-center",
    row.alignment === "end" && "justify-items-end",
    row.alignment === "stretch" && "justify-items-stretch",
    row.alignment === "baseline" && "justify-items-baseline",

    // 수직 정렬
    row.verticalAlignment === "top" && "items-start",
    row.verticalAlignment === "middle" && "items-center",
    row.verticalAlignment === "bottom" && "items-end",
    row.verticalAlignment === "stretch" && "items-stretch",

    // 선택 상태
    isSelected && "ring-2 ring-ring ring-inset",

    // 호버 효과
    "hover:bg-muted transition-colors cursor-pointer border-2 border-dashed border-transparent hover:border-input",
  );

  // 배경색 스타일
  const rowStyle: React.CSSProperties = {
    ...(row.backgroundColor && { backgroundColor: row.backgroundColor }),
  };

  return (
    <div className={rowClasses} style={rowStyle} onClick={onSelectRow} data-row-id={row.id}>
      {/* 행 인덱스 표시 */}
      <div className="absolute top-1/2 -left-8 -translate-y-1/2 font-mono text-xs text-muted-foreground/70">
        {row.rowIndex + 1}
      </div>

      {row.components.length === 0 ? (
        // 빈 행
        <div className="col-span-12 flex items-center justify-center rounded-lg border-2 border-dashed border-input bg-muted p-8">
          <div className="text-center">
            <p className="mb-2 text-sm text-muted-foreground/70">컴포넌트를 여기에 드래그하세요</p>
            <div className="flex justify-center gap-2">
              <button className="rounded border bg-white px-2 py-1 text-xs hover:bg-muted">폼 행 추가</button>
              <button className="rounded border bg-white px-2 py-1 text-xs hover:bg-muted">2분할</button>
              <button className="rounded border bg-white px-2 py-1 text-xs hover:bg-muted">전체</button>
            </div>
          </div>
        </div>
      ) : (
        // 컴포넌트 렌더링
        row.components.map((rowComponent) => {
          const component = components.get(rowComponent.componentId);
          if (!component) return null;

          // 그리드 클래스 생성
          const componentClasses = cn(
            // 컬럼 스팬
            buildGridClasses(rowComponent.columnSpan, rowComponent.columnStart),

            // 정렬 순서
            rowComponent.order && `order-${rowComponent.order}`,

            // 선택 상태
            selectedComponentId === component.id && "ring-2 ring-green-500 ring-inset",
          );

          // 오프셋 스타일 (여백)
          const componentStyle: React.CSSProperties = {
            ...(rowComponent.offset && {
              marginLeft: `${(GAP_PRESETS[rowComponent.offset as any]?.value || 0) * 4}px`,
            }),
          };

          return (
            <div
              key={rowComponent.id}
              className={componentClasses}
              style={componentStyle}
              onClick={(e) => {
                e.stopPropagation();
                onSelectComponent(component.id);
              }}
            >
              <RealtimePreviewDynamic
                component={component}
                isSelected={selectedComponentId === component.id}
                isDesignMode={true}
                onClick={(e) => {
                  e?.stopPropagation();
                  onSelectComponent(component.id);
                }}
              />
            </div>
          );
        })
      )}

      {/* 선택 시 행 설정 버튼 */}
      {isSelected && (
        <div className="absolute top-1/2 -right-8 flex -translate-y-1/2 flex-col gap-1">
          <button
            className="rounded border bg-white p-1 shadow-sm hover:bg-muted"
            title="행 설정"
            onClick={(e) => {
              e.stopPropagation();
              // 행 설정 패널 열기
            }}
          >
            <svg className="h-4 w-4 text-muted-foreground" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"
              />
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
          </button>
          <button
            className="rounded border bg-white p-1 shadow-sm hover:bg-destructive/10 hover:text-destructive"
            title="행 삭제"
            onClick={(e) => {
              e.stopPropagation();
              // 행 삭제
            }}
          >
            <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
              />
            </svg>
          </button>
        </div>
      )}
    </div>
  );
};
