"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"

import { formatDate } from "@/lib/utils"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { equipclassColumnsConfig } from "@/config/equipClassColumnsConfig"
import { ExtendedTagClasses } from "../validation"
import { Badge } from "@/components/ui/badge"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<ExtendedTagClasses> | null>>
}

// 서브클래스 배열을 렌더링하는 컴포넌트
const SubclassesCell = ({ subclasses }: { subclasses: {
  id: string;
  desc: string;
}[] }) => {
  if (!subclasses || subclasses.length === 0) {
    return <span className="text-muted-foreground">-</span>
  }

  if (subclasses.length <= 3) {
    return (
      <div className="flex flex-wrap gap-1">
        {subclasses.map((subclass) => (
          <Badge key={subclass.id} variant="secondary" className="text-xs">
            {subclass.desc}
          </Badge>
        ))}
      </div>
    )
  }

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <div className="flex flex-wrap gap-1">
            {subclasses.slice(0, 2).map((subclass) => (
              <Badge key={subclass.id} variant="secondary" className="text-xs">
                {subclass.desc}
              </Badge>
            ))}
            <Badge variant="outline" className="text-xs">
              +{subclasses.length - 2}
            </Badge>
          </div>
        </TooltipTrigger>
        <TooltipContent>
          <div className="max-w-sm">
            <div className="font-semibold mb-2">All Subclasses:</div>
            <div className="flex flex-wrap gap-1">
              {subclasses.map((subclass) => (
                <Badge key={subclass.id} variant="secondary" className="text-xs">
                  {subclass.desc}
                </Badge>
              ))}
            </div>
          </div>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  )
}

// 서브클래스 리마크를 렌더링하는 컴포넌트
const SubclassRemarksCell = ({ remarks }: { remarks: Record<string, string> }) => {
  if (!remarks || Object.keys(remarks).length === 0) {
    return <span className="text-muted-foreground">-</span>
  }

  const entries = Object.entries(remarks)
  
  if (entries.length <= 2) {
    return (
      <div className="space-y-1">
        {entries.map(([key, value]) => (
          <div key={key} className="text-sm">
            <span className="font-medium">{key}:</span>{" "}
            <span className="text-muted-foreground">{value}</span>
          </div>
        ))}
      </div>
    )
  }

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <div className="space-y-1">
            {entries.slice(0, 1).map(([key, value]) => (
              <div key={key} className="text-sm">
                <span className="font-medium">{key}:</span>{" "}
                <span className="text-muted-foreground">{value}</span>
              </div>
            ))}
            <div className="text-xs text-muted-foreground">
              +{entries.length - 1} more...
            </div>
          </div>
        </TooltipTrigger>
        <TooltipContent>
          <div className="max-w-md">
            <div className="font-semibold mb-2">All Remarks:</div>
            <div className="space-y-1">
              {entries.map(([key, value]) => (
                <div key={key} className="text-sm">
                  <span className="font-medium">{key}:</span>{" "}
                  <span className="text-muted-foreground">{value}</span>
                </div>
              ))}
            </div>
          </div>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  )
}

/**
 * tanstack table 컬럼 정의 (중첩 헤더 버전)
 */
export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ExtendedTagClasses>[] {
  // ----------------------------------------------------------------
  // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
  // ----------------------------------------------------------------
  // 3-1) groupMap: { [groupName]: ColumnDef<ExtendedTagClasses>[] }
  const groupMap: Record<string, ColumnDef<ExtendedTagClasses>[]> = {}

  equipclassColumnsConfig.forEach((cfg) => {
    // 만약 group가 없으면 "_noGroup" 처리
    const groupName = cfg.group || "_noGroup"

    if (!groupMap[groupName]) {
      groupMap[groupName] = []
    }

    // child column 정의
    const childCol: ColumnDef<ExtendedTagClasses> = {
      accessorKey: cfg.id,
      enableResizing: true,
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title={cfg.label} />
      ),
      meta: {
        excelHeader: cfg.excelHeader,
        group: cfg.group,
        type: cfg.type,
      },
      cell: ({ row, cell }) => {
        // 날짜 필드 처리
        if (cfg.id === "createdAt" || cfg.id === "updatedAt") {
          const dateVal = cell.getValue() as Date
          return formatDate(dateVal, "KR")
        }

        // 서브클래스 배열 처리
        if (cfg.id === "subclasses") {
          const subclasses = cell.getValue() as {
            id: string;
            desc: string;
          }[]
          return <SubclassesCell subclasses={subclasses} />
        }

        // 서브클래스 리마크 처리
        if (cfg.id === "subclassRemark") {
          const remarks = cell.getValue() as Record<string, string>
          return <SubclassRemarksCell remarks={remarks} />
        }

        return row.getValue(cfg.id) ?? ""
      },
    }

    groupMap[groupName].push(childCol)
  })

  // ----------------------------------------------------------------
  // 3-2) groupMap에서 실제 상위 컬럼(그룹)을 만들기
  // ----------------------------------------------------------------
  const nestedColumns: ColumnDef<ExtendedTagClasses>[] = []

  // 그룹 순서 정의
  const groupOrder = ["Basic Info", "Hierarchy", "Metadata", "_noGroup"]
  
  groupOrder.forEach((groupName) => {
    const colDefs = groupMap[groupName]
    if (!colDefs) return

    if (groupName === "_noGroup") {
      // 그룹 없음 → 그냥 최상위 레벨 컬럼
      nestedColumns.push(...colDefs)
    } else {
      // 상위 컬럼
      nestedColumns.push({
        id: groupName,
        header: groupName, // "Basic Info", "Hierarchy", "Metadata" 등
        columns: colDefs,
      })
    }
  })

  // ----------------------------------------------------------------
  // 4) 최종 컬럼 배열: select, nestedColumns, actions
  // ----------------------------------------------------------------
  return [
    ...nestedColumns,
  ]
}