"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,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"

// 테이블 표시에 필요한 데이터 타입 정의
interface ShipbuildingTableItem {
  id: number;
  itemId: number;
  workType: "기장" | "전장" | "선실" | "배관" | "철의";
  shipTypes: string;
  itemCode: string;
  itemName: string;
  description: string | null;
  createdAt: Date;
  updatedAt: Date;
}

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

/**
 * 조선 아이템 테이블 컬럼 정의
 */
export function getShipbuildingColumns({ setRowAction }: GetColumnsProps): ColumnDef<ShipbuildingTableItem>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<ShipbuildingTableItem> = {
    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<ShipbuildingTableItem> = {
    id: "actions",
    cell: ({ row }) => (
      <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: "update" })}
          >
            수정
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            onSelect={() => setRowAction({ row, type: "delete" })}
            className="text-destructive"
          >
            삭제
            <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    ),
    size: 40,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 3) 데이터 컬럼들을 그룹별로 구성
  // ----------------------------------------------------------------
  
  // 3-1) 기본 정보 그룹 컬럼
  const basicInfoColumns: ColumnDef<ShipbuildingTableItem>[] = [
    {
      accessorKey: "itemCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Material Group" />
      ),
      cell: ({ row }) => <div>{row.original.itemCode}</div>,
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "Material Group",
        group: "기본 정보",
      },
    },
    {
      accessorKey: "itemName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Description" />
      ),
      cell: ({ row }) => <div>{row.original.itemName}</div>,
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "Description",
        group: "기본 정보",
      },
    },
    {
      accessorKey: "workType",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="기능(공종)" />
      ),
      cell: ({ row }) => <div>{row.original.workType}</div>,
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "기능(공종)",
        group: "기본 정보",
      },
    },
    {
      accessorKey: "description",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Size/Dimension" />
      ),
      cell: ({ row }) => <div>{row.original.description || "-"}</div>,
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "Size/Dimension",
        group: "기본 정보",
      },
    },
  ]
  
  // 3-2) 선종 정보 그룹 컬럼
  const shipTypesColumns: ColumnDef<ShipbuildingTableItem>[] = [
    {
      accessorKey: "shipTypes",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선종" />
      ),
      cell: ({ row }) => <div>{row.original.shipTypes}</div>,
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "선종",
        group: "선종",
      },
    },
  ]
  
  // 3-3) 메타데이터 그룹 컬럼
  const metadataColumns: ColumnDef<ShipbuildingTableItem>[] = [
    
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일" />
      ),
      cell: ({ row }) => formatDate(row.original.createdAt),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "생성일",
        group: "Metadata",
      },
    },
    {
      accessorKey: "updatedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="수정일" />
      ),
      cell: ({ row }) => formatDate(row.original.updatedAt),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: "수정일",
        group: "Metadata",
      },
    }
  ]
  
  // 3-4) 그룹별 컬럼 구성
  const groupedColumns: ColumnDef<ShipbuildingTableItem>[] = [
    {
      id: "기본 정보",
      header: "기본 정보",
      columns: basicInfoColumns,
    },
    {
      id: "선종",
      header: "선종",
      columns: shipTypesColumns,
    },
    {
      id: "Metadata",
      header: "Metadata",
      columns: metadataColumns,
    }
  ]

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