"use client"

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

import { formatDate } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuShortcut,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

import { ContactPossibleItemDetail } from "../service"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"


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

/**
 * tanstack table 컬럼 정의 (중첩 헤더 버전)
 */
export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<ContactPossibleItemDetail>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<ContactPossibleItemDetail> = {
    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"
      />
    ),
    size: 40,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) actions 컬럼 (Dropdown 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<ContactPossibleItemDetail> = {
    id: "actions",
    enableHiding: false,
    cell: function Cell({ row }) {
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              aria-label="Open menu"
              variant="ghost"
              className="flex size-8 p-0 data-[state=open]:bg-muted"
            >
              <Ellipsis className="size-4" aria-hidden="true" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-40">
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "delete" })}
            >
              삭제
              <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 40,
  }

  // ----------------------------------------------------------------
  // 3) 일반 컬럼들을 "그룹"별로 묶어 중첩 columns 생성
  // ----------------------------------------------------------------
  const baseColumns: ColumnDef<ContactPossibleItemDetail>[] = [
    // 벤더 정보
    {
      id: "vendorInfo",
      header: "벤더 정보",
      columns: [
        {
          accessorKey: "vendorCode",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="벤더 코드" />
          ),
          cell: ({ row }) => row.original.vendorCode ?? "",
        },
        {
          accessorKey: "vendorName",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="벤더명" />
          ),
          cell: ({ row }) => row.original.vendorName ?? "",
        },
        {
          accessorKey: "vendorCountry",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="벤더 국가" />
          ),
          cell: ({ row }) => {
            const country = row.original.vendorCountry
            return country || <span className="text-muted-foreground">-</span>
          },
        },
        {
          accessorKey: "techVendorType",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="벤더 타입" />
          ),
          cell: ({ row }) => {
            const type = row.original.techVendorType
            return type || <span className="text-muted-foreground">-</span>
          },
        },
      ]
    },
    // 담당자 정보
    {
      id: "contactInfo",
      header: "담당자 정보",
      columns: [
        {
          accessorKey: "contactName",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="담당자명" />
          ),
          cell: ({ row }) => {
            const contactName = row.original.contactName
            return contactName || <span className="text-muted-foreground">-</span>
          },
        },
        {
          accessorKey: "contactPosition",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="직책" />
          ),
          cell: ({ row }) => {
            const position = row.original.contactPosition
            return position || <span className="text-muted-foreground">-</span>
          },
        },
        {
          accessorKey: "contactEmail",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="담당자 이메일" />
          ),
          cell: ({ row }) => {
            const contactEmail = row.original.contactEmail
            return contactEmail || <span className="text-muted-foreground">-</span>
          },
        },
        {
          accessorKey: "contactPhone",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="담당자 전화번호" />
          ),
          cell: ({ row }) => {
            const contactPhone = row.original.contactPhone
            return contactPhone || <span className="text-muted-foreground">-</span>
          },
        },
        {
          accessorKey: "contactCountry",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="담당자 국가" />
          ),
          cell: ({ row }) => {
            const contactCountry = row.original.contactCountry
            return contactCountry || <span className="text-muted-foreground">-</span>
          },
        },
        {
          accessorKey: "isPrimary",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="주담당자" />
          ),
          cell: ({ row }) => {
            const isPrimary = row.original.isPrimary
            return isPrimary ? "예" : "아니오"
          },
        },
      ]
    },
    // 아이템 정보
    {
      id: "itemInfo",
      header: "아이템 정보",
      columns: [
        {
          accessorKey: "itemCode",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="아이템 코드" />
          ),
          cell: ({ row }) => row.original.itemCode ?? "",
        },
        {
          accessorKey: "itemList",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="아이템 리스트" />
          ),
          cell: ({ row }) => row.original.itemList ?? "",
        },
        {
          accessorKey: "workType",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="공종" />
          ),
          cell: ({ row }) => row.original.workType ?? "",
        },
        {
          accessorKey: "shipTypes",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="선종" />
          ),
          cell: ({ row }) => row.original.shipTypes ?? "",
        },
        {
          accessorKey: "subItemList",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="서브아이템 리스트" />
          ),
          cell: ({ row }) => row.original.subItemList ?? "",
        },
      ]
    },
    
    // 시스템 정보
    {
      id: "systemInfo",
      header: "시스템 정보",
      columns: [
        {
          accessorKey: "createdAt",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="생성일" />
          ),
          cell: ({ row }) => {
            const dateVal = row.getValue("createdAt") as Date
            return formatDate(dateVal)
          },
        },
        {
          accessorKey: "updatedAt",
          enableResizing: true,
          header: ({ column }) => (
            <DataTableColumnHeaderSimple column={column} title="수정일" />
          ),
          cell: ({ row }) => {
            const dateVal = row.getValue("updatedAt") as Date
            return formatDate(dateVal)
          },
        },
      ]
    },
  ]

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