"use client";

import React from "react";
import type { ComponentRendererProps } from "@/types/component";
import { filterDOMProps } from "@/lib/utils/domPropsFilter";
import { useTableRows } from "../_shared/use-table-rows";
import type { CardListConfig, CardListLayout, CardListMetric } from "./types";

/**
 * CardList — canonical 카드 리스트 컴포넌트 (Phase G.3.1)
 *
 * 테이블 row 들을 반복 카드로 출력. titleField / subtitleFields / metricFields 를
 * 자유 조합. 디자인 모드 / dataSource 미완성: 정적 preview 4 장.
 */

const VALID_LAYOUTS: CardListLayout[] = ["list", "grid"];

export interface CardListComponentProps extends ComponentRendererProps {
  config?: CardListConfig;
}

const cellToText = (v: unknown): string => {
  if (v === null || v === undefined || v === "") return "—";
  if (typeof v === "number") return v.toLocaleString();
  if (typeof v === "boolean") return v ? "✓" : "✗";
  if (v instanceof Date) return v.toLocaleString();
  return String(v);
};

export const CardListComponent: React.FC<CardListComponentProps> = ({
  component,
  isDesignMode = false,
  isSelected = false,
  onClick,
  onDragStart,
  onDragEnd,
  config,
  className,
  style,
  ...props
}) => {
  const p = props as any;
  const fromProps: Partial<CardListConfig> = {};
  if (typeof p.title === "string") fromProps.title = p.title;
  if (typeof p.layout === "string" && (VALID_LAYOUTS as string[]).includes(p.layout))
    fromProps.layout = p.layout as CardListLayout;
  if (typeof p.columns === "number") fromProps.columns = p.columns;
  if (p.dataSource && typeof p.dataSource === "object") fromProps.dataSource = p.dataSource;
  if (typeof p.titleField === "string") fromProps.titleField = p.titleField;
  if (Array.isArray(p.subtitleFields)) fromProps.subtitleFields = p.subtitleFields;
  if (Array.isArray(p.metricFields)) fromProps.metricFields = p.metricFields;
  if (typeof p.emptyText === "string") fromProps.emptyText = p.emptyText;

  const componentConfig = {
    ...config,
    ...((component as any).config ?? {}),
    ...((component as any).componentConfig ?? {}),
    ...fromProps,
  } as CardListConfig;

  const layout: CardListLayout = (VALID_LAYOUTS as string[]).includes(
    componentConfig.layout as string,
  )
    ? (componentConfig.layout as CardListLayout)
    : "list";
  const columns = componentConfig.columns;
  const title = componentConfig.title;
  const titleField = componentConfig.titleField;
  const subtitleFields = componentConfig.subtitleFields ?? [];
  const metricFields: CardListMetric[] = componentConfig.metricFields ?? [];
  const emptyText = componentConfig.emptyText ?? "데이터 없음";
  const previewTitleField = titleField ?? "title";
  const previewSubtitleField = subtitleFields[0];
  const previewMetricField = metricFields[0]?.column;

  const userContext = React.useMemo(
    () => ({
      companyCode: (p.companyCode as string) || undefined,
      userId: (p.userId as string) || undefined,
      deptCode: (p.deptCode as string) || undefined,
      userName: (p.userName as string) || undefined,
    }),
    [p.companyCode, p.userId, p.deptCode, p.userName],
  );

  const previewBuilder = React.useCallback(
    (i: number) => ({
      __preview: true,
      [previewTitleField]: `샘플 카드 ${i + 1}`,
      ...(previewSubtitleField ? { [previewSubtitleField]: `부제 ${i + 1}` } : {}),
      ...(previewMetricField
        ? { [previewMetricField]: (i + 1) * 7 }
        : { count: (i + 1) * 7 }),
    }),
    [previewMetricField, previewSubtitleField, previewTitleField],
  );

  const { rows, loading, error, isPreview } = useTableRows(componentConfig.dataSource, {
    isDesignMode,
    formData: (p.formData as Record<string, unknown>) || undefined,
    userContext,
    refreshKey: (p.refreshKey as number | string | undefined) || undefined,
    previewCount: 4,
    previewBuilder,
  });

  const containerStyle: React.CSSProperties = {
    width: "100%",
    height: "100%",
    display: "flex",
    flexDirection: "column",
    boxSizing: "border-box",
    background: "hsl(var(--card))",
    border: "1px solid hsl(var(--border))",
    borderRadius: 8,
    padding: 12,
    minHeight: 160,
    ...((component as any).style ?? {}),
    ...style,
  };

  if (isDesignMode && isSelected) {
    containerStyle.outline = "2px solid hsl(var(--primary))";
    containerStyle.outlineOffset = "2px";
  }

  const handleClick = (e: React.MouseEvent) => {
    e.stopPropagation();
    onClick?.();
  };

  /* eslint-disable @typescript-eslint/no-unused-vars */
  const {
    selectedScreen: _1, onZoneComponentDrop: _2, onZoneClick: _3,
    componentConfig: _4, component: _5, isSelected: _6,
    onClick: _7, onDragStart: _8, onDragEnd: _9,
    size: _10, position: _11, style: _12,
    screenId: _13, tableName: _14, onRefresh: _15, onClose: _16,
    web_type: _17, autoGeneration: _18, isInteractive: _19,
    formData: _20, onFormDataChange: _21,
    menuId: _22, menuObjid: _23, onSave: _24,
    userId: _25, userName: _26, companyCode: _27, deptCode: _27b,
    isInModal: _28, readonly: _29, originalData: _30,
    selectedRows: _36, selectedRowsData: _37, onSelectedRowsChange: _38,
    sortBy: _39, sortOrder: _40, tableDisplayData: _41,
    flowSelectedData: _42, flowSelectedStepId: _43, onFlowSelectedDataChange: _44,
    onConfigChange: _45, refreshKey: _46, flowRefreshKey: _47, onFlowRefresh: _48,
    isPreview: _49, groupedData: _50,
    title: _51, layout: _52, columns: _53, dataSource: _54,
    titleField: _55, subtitleFields: _56, metricFields: _57, emptyText: _58,
    disabled: _59, required: _60,
    ...domProps
  } = props as any;
  /* eslint-enable @typescript-eslint/no-unused-vars */

  const listContainerStyle: React.CSSProperties =
    layout === "grid"
      ? {
          display: "grid",
          gap: 8,
          gridTemplateColumns: columns
            ? `repeat(auto-fit, minmax(max(200px, calc((100% - ${
                (columns - 1) * 8
              }px) / ${columns})), 1fr))`
            : "repeat(auto-fit, minmax(200px, 1fr))",
          flex: 1,
          minHeight: 0,
          overflow: "auto",
        }
      : {
          display: "flex",
          flexDirection: "column",
          gap: 6,
          flex: 1,
          minHeight: 0,
          overflow: "auto",
        };

  const renderCard = (row: Record<string, any>, idx: number) => {
    const titleText = titleField ? cellToText(row[titleField]) : `행 ${idx + 1}`;
    return (
      <div
        key={idx}
        style={{
          padding: "8px 10px",
          border: "1px solid hsl(var(--border))",
          borderRadius: 6,
          background: "hsl(var(--card))",
          display: "flex",
          flexDirection: layout === "grid" ? "column" : "row",
          alignItems: layout === "grid" ? "stretch" : "center",
          gap: 8,
          minWidth: 0,
        }}
      >
        <div style={{ flex: 1, minWidth: 0 }}>
          <div
            style={{
              fontSize: 13,
              fontWeight: 700,
              color: "hsl(var(--foreground))",
              whiteSpace: "nowrap",
              overflow: "hidden",
              textOverflow: "ellipsis",
            }}
          >
            {titleText}
          </div>
          {subtitleFields.map((col, sIdx) => (
            <div
              key={sIdx}
              style={{
                fontSize: 11,
                color: "hsl(var(--muted-foreground))",
                marginTop: 2,
                whiteSpace: "nowrap",
                overflow: "hidden",
                textOverflow: "ellipsis",
              }}
            >
              {cellToText(row[col])}
            </div>
          ))}
        </div>
        {metricFields.length > 0 && (
          <div
            style={{
              display: "flex",
              gap: 6,
              flexShrink: 0,
              flexWrap: "wrap",
              justifyContent: layout === "grid" ? "flex-start" : "flex-end",
            }}
          >
            {metricFields.map((m, mIdx) => {
              const v = cellToText(row[m.column]);
              return (
                <div
                  key={mIdx}
                  style={{
                    display: "inline-flex",
                    flexDirection: "column",
                    alignItems: "flex-end",
                    padding: "3px 8px",
                    borderRadius: 4,
                    background: m.emphasis
                      ? "rgba(var(--v5-primary-rgb), 0.12)"
                      : "hsl(var(--muted))",
                    border: "1px solid hsl(var(--border))",
                  }}
                >
                  {m.label && (
                    <span
                      style={{ fontSize: 9, color: "hsl(var(--muted-foreground))" }}
                    >
                      {m.label}
                    </span>
                  )}
                  <span
                    style={{
                      fontSize: 12,
                      fontWeight: 700,
                      color: m.emphasis
                        ? "var(--v5-primary, hsl(var(--primary)))"
                        : "hsl(var(--foreground))",
                    }}
                  >
                    {v}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </div>
    );
  };

  return (
    <div
      style={containerStyle}
      className={className}
      onClick={handleClick}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      {...filterDOMProps(domProps)}
    >
      {(title || isPreview || loading) && (
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: 12,
            fontWeight: 700,
            color: "hsl(var(--foreground))",
            marginBottom: 6,
            flexShrink: 0,
          }}
        >
          <span>{title || (isPreview ? "카드 리스트 (미리보기)" : "")}</span>
          {loading && (
            <span style={{ fontSize: 10, color: "hsl(var(--muted-foreground))", fontWeight: 500 }}>
              로딩…
            </span>
          )}
        </div>
      )}
      <div style={listContainerStyle}>
        {error ? (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flex: 1,
              fontSize: 12,
              color: "hsl(var(--muted-foreground))",
            }}
          >
            데이터 로드 실패: {error}
          </div>
        ) : rows.length === 0 ? (
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flex: 1,
              fontSize: 12,
              color: "hsl(var(--muted-foreground))",
            }}
          >
            {emptyText}
          </div>
        ) : (
          rows.map((row, idx) => renderCard(row, idx))
        )}
      </div>
    </div>
  );
};

export const CardListWrapper: React.FC<CardListComponentProps> = (props) => {
  return <CardListComponent {...props} />;
};
