"use client"

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

import { formatDateTime } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { 
  FileActionsDropdown, 
  FileNameLink 
} from "@/components/ui/file-actions"

import { basicContractColumnsConfig } from "@/config/basicContractColumnsConfig"
import { BasicContractView } from "@/db/schema"

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

/**
 * 공용 파일 다운로드 유틸리티를 사용하는 간소화된 컬럼 정의
 */
export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<BasicContractView>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<BasicContractView> = {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all"
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
        className="translate-y-0.5"
      />
    ),
    maxSize: 30,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) 파일 다운로드 컬럼 (공용 컴포넌트 사용)
  // ----------------------------------------------------------------
  const downloadColumn: ColumnDef<BasicContractView> = {
    id: "download",
    header: "",
    cell: ({ row }) => {
      const template = row.original;
      
      if (!template.filePath || !template.fileName) {
        return null;
      }
      
      return (
        <FileActionsDropdown
          filePath={template.filePath}
          fileName={template.fileName}
          variant="ghost"
          size="icon"
        />
      );
    },
    maxSize: 30,
    enableSorting: false,
  }

  // ----------------------------------------------------------------
  // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
  // ----------------------------------------------------------------
  const groupMap: Record<string, ColumnDef<BasicContractView>[]> = {}

  basicContractColumnsConfig.forEach((cfg) => {
    const groupName = cfg.group || "_noGroup"

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

    const childCol: ColumnDef<BasicContractView> = {
      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 formatDateTime(dateVal, "KR")
        }
        
        // Status 컬럼에 Badge 적용 (확장)
        if (cfg.id === "status") {
          const status = row.getValue(cfg.id) as string
          
          let variant: "default" | "secondary" | "destructive" | "outline" = "secondary";
          let label = status;
          
          switch (status) {
            case "ACTIVE":
              variant = "default";
              label = "활성";
              break;
            case "INACTIVE":
              variant = "secondary";
              label = "비활성";
              break;
            case "PENDING":
              variant = "outline";
              label = "대기중";
              break;
            case "COMPLETED":
              variant = "default";
              label = "완료";
              break;
            default:
              variant = "secondary";
              label = status;
          }
          
          return <Badge variant={variant}>{label}</Badge>
        }

        // ✅ 파일 이름 컬럼 (공용 컴포넌트 사용)
        if (cfg.id === "fileName") {
          const fileName = cell.getValue() as string;
          const filePath = row.original.filePath;
          
          if (fileName && filePath) {
            return (
              <FileNameLink
                filePath={filePath}
                fileName={fileName}
                maxLength={200}
                showIcon={true}
              />
            );
          }
          return fileName || "";
        }

        // 나머지 컬럼은 그대로 값 표시
        return row.getValue(cfg.id) ?? ""
      },
      minSize: 80,
    }

    groupMap[groupName].push(childCol)
  })

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

  Object.entries(groupMap).forEach(([groupName, colDefs]) => {
    if (groupName === "_noGroup") {
      nestedColumns.push(...colDefs)
    } else {
      nestedColumns.push({
        id: groupName,
        header: groupName,
        columns: colDefs,
      })
    }
  })

  // ----------------------------------------------------------------
  // 5) 최종 컬럼 배열
  // ----------------------------------------------------------------
  return [
    selectColumn,
    downloadColumn, // ✅ 공용 파일 액션 컴포넌트 사용
    ...nestedColumns,
  ]
}
