"use client";

import React, { useMemo, useState } from "react";
import { ChevronRight, ChevronDown } from "lucide-react";
import type { TableConfig, TableColumn } from "../types";

export interface GroupedViewProps {
  config: TableConfig;
  columns: TableColumn[];
  data: any[];
  rowHeightPx?: string;
  isDesignMode?: boolean;
  onRowClick?: (row: any) => void;
}

/**
 * GroupedView — displayMode="grouped"
 *
 * config.groupBy 컬럼 기준으로 데이터를 그룹화해 펼침/접힘 단위로 렌더.
 * 그룹 헤더에 그룹 키 + 행 개수 표시. 클릭 시 펼침 토글.
 */
export function GroupedView({
  config,
  columns,
  data,
  rowHeightPx = "36px",
  isDesignMode = false,
  onRowClick,
}: GroupedViewProps) {
  const groupBy = config.groupBy;

  const groups = useMemo<Array<{ key: string; rows: any[] }>>(() => {
    if (!groupBy) return [{ key: "(전체)", rows: data }];
    const map = new Map<string, any[]>();
    for (const row of data) {
      const raw = row?.[groupBy];
      const key = raw === null || raw === undefined || raw === "" ? "(빈 값)" : String(raw);
      const list = map.get(key);
      if (list) list.push(row);
      else map.set(key, [row]);
    }
    return Array.from(map.entries()).map(([key, rows]) => ({ key, rows }));
  }, [data, groupBy]);

  const [collapsedKeys, setCollapsedKeys] = useState<Set<string>>(new Set());
  const toggle = (key: string) => {
    setCollapsedKeys((prev) => {
      const next = new Set(prev);
      if (next.has(key)) next.delete(key);
      else next.add(key);
      return next;
    });
  };

  if (!groupBy) {
    return (
      <div style={emptyStyle}>
        그룹화할 컬럼이 설정되지 않았습니다 (config.groupBy)
      </div>
    );
  }

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

  return (
    <div style={{ overflow: "auto", flex: 1 }}>
      <table style={tableStyle}>
        <thead>
          <tr>
            <th style={{ ...thStyle, width: 28 }}></th>
            {columns.map((col) => (
              <th
                key={col.key}
                style={{
                  ...thStyle,
                  width: col.width,
                  textAlign: col.align || "left",
                }}
              >
                {col.label || col.key}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {groups.map(({ key, rows }) => {
            const collapsed = collapsedKeys.has(key);
            return (
              <React.Fragment key={key}>
                <tr style={groupHeaderRowStyle} onClick={() => toggle(key)}>
                  <td style={{ ...tdStyle, width: 28, cursor: "pointer" }}>
                    {collapsed ? (
                      <ChevronRight size={12} />
                    ) : (
                      <ChevronDown size={12} />
                    )}
                  </td>
                  <td
                    style={{ ...tdStyle, fontWeight: 600 }}
                    colSpan={columns.length}
                  >
                    {key}{" "}
                    <span style={{ color: "hsl(var(--muted-foreground))", fontSize: 11 }}>
                      ({rows.length}건)
                    </span>
                  </td>
                </tr>
                {!collapsed &&
                  rows.map((row, idx) => (
                    <tr
                      key={`${key}-${idx}`}
                      style={{ height: rowHeightPx, cursor: onRowClick ? "pointer" : "default" }}
                      onClick={() => onRowClick?.(row)}
                    >
                      <td style={tdStyle}></td>
                      {columns.map((col) => (
                        <td
                          key={col.key}
                          style={{ ...tdStyle, textAlign: col.align || "left" }}
                        >
                          {formatCell(row?.[col.key], col.format)}
                        </td>
                      ))}
                    </tr>
                  ))}
              </React.Fragment>
            );
          })}
        </tbody>
      </table>
      {isDesignMode && (
        <div style={{ padding: "6px 10px", fontSize: 10.5, color: "hsl(var(--muted-foreground))" }}>
          [디자인 모드] {groups.length}개 그룹
        </div>
      )}
    </div>
  );
}

function formatCell(value: any, _format?: string): React.ReactNode {
  if (value === null || value === undefined) return "-";
  if (typeof value === "boolean") return value ? "✓" : "✗";
  if (typeof value === "object") return JSON.stringify(value);
  return String(value);
}

const tableStyle: React.CSSProperties = {
  width: "100%",
  borderCollapse: "collapse",
  fontSize: 12,
};

const thStyle: React.CSSProperties = {
  padding: "8px 10px",
  fontSize: 11,
  fontWeight: 700,
  color: "hsl(var(--foreground))",
  textTransform: "uppercase",
  letterSpacing: "0.03em",
  borderBottom: "1px solid hsl(var(--border))",
  textAlign: "left",
  whiteSpace: "nowrap",
  background: "hsl(var(--muted))",
  position: "sticky",
  top: 0,
};

const tdStyle: React.CSSProperties = {
  padding: "6px 10px",
  fontSize: 12,
  color: "hsl(var(--foreground))",
  borderBottom: "1px solid hsl(var(--border) / 0.5)",
};

const groupHeaderRowStyle: React.CSSProperties = {
  background: "hsl(var(--muted) / 0.5)",
  cursor: "pointer",
};

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