"use client";

import React from "react";
import { Eye, Pencil, Trash2 } from "lucide-react";
import type { TableConfig, TableCardStyleConfig } from "../types";

export interface CardViewProps {
  config: TableConfig;
  data: any[];
  isDesignMode?: boolean;
  onCardClick?: (row: any) => void;
  onView?: (row: any) => void;
  onEdit?: (row: any) => void;
  onDelete?: (row: any) => void;
}

const DEFAULT_STYLE: Required<TableCardStyleConfig> = {
  showTitle: true,
  showSubtitle: true,
  showDescription: true,
  showImage: true,
  maxDescriptionLength: 120,
  imagePosition: "top",
  imageSize: "medium",
  showActions: false,
  showViewButton: false,
  showEditButton: false,
  showDeleteButton: false,
};

const IMAGE_SIZE_PX: Record<NonNullable<TableCardStyleConfig["imageSize"]>, number> = {
  small: 80,
  medium: 140,
  large: 200,
};

/**
 * CardView — displayMode="card"
 *
 * 데이터 행을 카드 그리드로 렌더. config.cardColumnMapping 으로 데이터 컬럼을
 * 카드 영역 (title/subtitle/description/image) 에 매핑.
 */
export function CardView({
  config,
  data,
  isDesignMode = false,
  onCardClick,
  onView,
  onEdit,
  onDelete,
}: CardViewProps) {
  const cardsPerRow = config.cardsPerRow ?? 3;
  const cardSpacing = config.cardSpacing ?? 12;
  const style: Required<TableCardStyleConfig> = {
    ...DEFAULT_STYLE,
    ...(config.cardStyle ?? {}),
  };
  const mapping = config.cardColumnMapping ?? {};

  if (data.length === 0) {
    return <div style={emptyStyle}>{config.emptyMessage || "데이터 없음"}</div>;
  }

  const gridStyle: React.CSSProperties = {
    display: "grid",
    gridTemplateColumns: `repeat(${cardsPerRow}, minmax(0, 1fr))`,
    gap: cardSpacing,
    padding: 12,
    overflow: "auto",
    flex: 1,
  };

  return (
    <div style={gridStyle}>
      {data.map((row, idx) => (
        <CardItem
          key={idx}
          row={row}
          mapping={mapping}
          style={style}
          onClick={onCardClick ? () => onCardClick(row) : undefined}
          onView={style.showActions && style.showViewButton ? () => onView?.(row) : undefined}
          onEdit={style.showActions && style.showEditButton ? () => onEdit?.(row) : undefined}
          onDelete={style.showActions && style.showDeleteButton ? () => onDelete?.(row) : undefined}
          isDesignMode={isDesignMode}
        />
      ))}
    </div>
  );
}

interface CardItemProps {
  row: any;
  mapping: NonNullable<TableConfig["cardColumnMapping"]>;
  style: Required<TableCardStyleConfig>;
  isDesignMode: boolean;
  onClick?: () => void;
  onView?: () => void;
  onEdit?: () => void;
  onDelete?: () => void;
}

function CardItem({ row, mapping, style, isDesignMode, onClick, onView, onEdit, onDelete }: CardItemProps) {
  const title = mapping.titleColumn ? row?.[mapping.titleColumn] : undefined;
  const subtitle = mapping.subtitleColumn ? row?.[mapping.subtitleColumn] : undefined;
  const descriptionRaw = mapping.descriptionColumn ? row?.[mapping.descriptionColumn] : undefined;
  const image = mapping.imageColumn ? row?.[mapping.imageColumn] : undefined;
  const description =
    typeof descriptionRaw === "string" && descriptionRaw.length > style.maxDescriptionLength
      ? `${descriptionRaw.slice(0, style.maxDescriptionLength)}…`
      : descriptionRaw;

  const imagePx = IMAGE_SIZE_PX[style.imageSize];
  const isHorizontal = style.imagePosition === "left" || style.imagePosition === "right";

  const cardStyle: React.CSSProperties = {
    border: "1px solid hsl(var(--border))",
    borderRadius: 8,
    background: "hsl(var(--card))",
    overflow: "hidden",
    cursor: onClick ? "pointer" : "default",
    display: isHorizontal ? "flex" : "block",
    flexDirection: style.imagePosition === "right" ? "row-reverse" : "row",
  };

  return (
    <div style={cardStyle} onClick={onClick}>
      {style.showImage && image && (
        <div
          style={{
            width: isHorizontal ? imagePx : "100%",
            height: imagePx,
            background: "hsl(var(--muted))",
            flexShrink: 0,
            backgroundImage: `url(${image})`,
            backgroundSize: "cover",
            backgroundPosition: "center",
          }}
        />
      )}
      <div style={{ padding: 12, flex: 1, minWidth: 0 }}>
        {style.showTitle && title !== undefined && title !== null && title !== "" && (
          <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 4 }}>{String(title)}</div>
        )}
        {style.showSubtitle && subtitle !== undefined && subtitle !== null && subtitle !== "" && (
          <div style={{ fontSize: 11, color: "hsl(var(--muted-foreground))", marginBottom: 6 }}>
            {String(subtitle)}
          </div>
        )}
        {style.showDescription && description !== undefined && description !== null && description !== "" && (
          <div style={{ fontSize: 12, lineHeight: 1.5, marginBottom: style.showActions ? 8 : 0 }}>
            {String(description)}
          </div>
        )}
        {(mapping.displayColumns?.length ?? 0) > 0 && (
          <div style={{ marginTop: 6, fontSize: 11, color: "hsl(var(--muted-foreground))" }}>
            {mapping.displayColumns!.map((col) => (
              <div key={col} style={{ display: "flex", gap: 6 }}>
                <span style={{ fontWeight: 500 }}>{col}:</span>
                <span>{row?.[col] !== undefined && row?.[col] !== null ? String(row[col]) : "-"}</span>
              </div>
            ))}
          </div>
        )}
        {style.showActions && (onView || onEdit || onDelete) && (
          <div style={{ display: "flex", gap: 6, marginTop: 8 }}>
            {onView && (
              <ActionButton onClick={onView} icon={<Eye size={12} />} label="보기" />
            )}
            {onEdit && (
              <ActionButton onClick={onEdit} icon={<Pencil size={12} />} label="편집" />
            )}
            {onDelete && (
              <ActionButton onClick={onDelete} icon={<Trash2 size={12} />} label="삭제" />
            )}
          </div>
        )}
        {isDesignMode && Object.keys(mapping).length === 0 && (
          <div style={{ fontSize: 10.5, color: "hsl(var(--muted-foreground))" }}>
            [디자인 모드] 컬럼 매핑이 비어있어 빈 카드만 표시됩니다.
          </div>
        )}
      </div>
    </div>
  );
}

function ActionButton({
  onClick,
  icon,
  label,
}: {
  onClick: () => void;
  icon: React.ReactNode;
  label: string;
}) {
  return (
    <button
      type="button"
      onClick={(e) => {
        e.stopPropagation();
        onClick();
      }}
      style={{
        display: "inline-flex",
        alignItems: "center",
        gap: 4,
        padding: "3px 8px",
        fontSize: 10.5,
        background: "hsl(var(--muted))",
        border: "1px solid hsl(var(--border))",
        borderRadius: 4,
        cursor: "pointer",
        color: "hsl(var(--foreground))",
      }}
    >
      {icon}
      <span>{label}</span>
    </button>
  );
}

const emptyStyle: React.CSSProperties = {
  padding: 24,
  textAlign: "center",
  fontSize: 12,
  color: "hsl(var(--muted-foreground))",
};
