"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { Ellipsis, Eye } from "lucide-react"
import type { AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime"

import { formatDate } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
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"
import { type GtcDocumentWithRelations } from "@/db/schema/gtc"

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<GtcDocumentWithRelations> | null>>
  router: AppRouterInstance
}

/** GTC Documents 테이블 컬럼 정의 (그룹 헤더 제거) */
export function getColumns({ setRowAction, router }: GetColumnsProps): ColumnDef<GtcDocumentWithRelations>[] {
  const selectColumn: ColumnDef<GtcDocumentWithRelations> = {
    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,
  }

  const basicInfoColumns: ColumnDef<GtcDocumentWithRelations>[] = [
    {
      accessorKey: "type",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="구분" />,
      cell: ({ row }) => {
        const type = row.getValue("type") as string
        return (
          <Badge variant={type === "standard" ? "default" : "secondary"}>
            {type === "standard" ? "표준" : "프로젝트"}
          </Badge>
        )
      },
      size: 100,
      enableResizing: true,
      meta: { excelHeader: "구분" },
    },
    {
      accessorKey: "projectName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="프로젝트" />,
      cell: ({ row }) => {
        const projectName = row.original.projectName
        const projectCode = row.original.projectCode
        if (!projectName) return <span className="text-muted-foreground">-</span>
        return (
          <div className="flex flex-col min-w-0">
            <span className="font-medium truncate">{projectName}</span>
            <span className="text-xs text-muted-foreground">{projectCode}</span>
          </div>
        )
      },
      size: 200,
      enableResizing: true,
      meta: { excelHeader: "프로젝트" },
    },
    {
      accessorKey: "title",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="GTC 제목" />,
      cell: ({ row }) => {
        const title = row.original.title
        if (!title) return <span className="text-muted-foreground">-</span>
        return (
          <div className="flex flex-col min-w-0">
            <span className="font-medium truncate">{title}</span>
          </div>
        )
      },
      size: 200,
      enableResizing: true,
      meta: { excelHeader: "GTC 제목" },
    },
    {
      accessorKey: "revision",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Rev." />,
      cell: ({ row }) => {
        const revision = row.getValue("revision") as number
        return <span className="font-mono text-sm">v{revision}</span>
      },
      size: 80,
      enableResizing: true,
      meta: { excelHeader: "Rev." },
    },
  ]

  const auditColumns: ColumnDef<GtcDocumentWithRelations>[] = [
    {
      accessorKey: "createdAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최초등록일" />,
      cell: ({ row }) => {
        const date = row.getValue("createdAt") as Date
        return date ? formatDate(date, "KR") : "-"
      },
      size: 120,
      enableResizing: true,
      meta: { excelHeader: "최초등록일" },
    },
    {
      accessorKey: "createdByName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최초등록자" />,
      cell: ({ row }) => {
        const createdByName = row.original.createdByName
        return createdByName ? <span className="text-sm">{createdByName}</span> : <span className="text-muted-foreground">-</span>
      },
      size: 120,
      enableResizing: true,
      meta: { excelHeader: "최초등록자" },
    },
    {
      accessorKey: "updatedAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최종수정일" />,
      cell: ({ row }) => {
        const date = row.getValue("updatedAt") as Date
        return date ? formatDate(date, "KR") : "-"
      },
      size: 120,
      enableResizing: true,
      meta: { excelHeader: "최종수정일" },
    },
    {
      accessorKey: "updatedByName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최종수정자" />,
      cell: ({ row }) => {
        const updatedByName = row.original.updatedByName
        return updatedByName ? <span className="text-sm">{updatedByName}</span> : <span className="text-muted-foreground">-</span>
      },
      size: 120,
      enableResizing: true,
      meta: { excelHeader: "최종수정자" },
    },
    {
      accessorKey: "editReason",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="최종 편집사유" />,
      cell: ({ row }) => {
        const reason = row.getValue("editReason") as string
        return reason ? (
          <span className="text-sm" title={reason}>
            {reason.length > 30 ? `${reason.substring(0, 30)}...` : reason}
          </span>
        ) : (
          <span className="text-muted-foreground">-</span>
        )
      },
      size: 200,
      enableResizing: true,
      meta: { excelHeader: "최종 편집사유" },
    },
  ]

  const actionsColumn: ColumnDef<GtcDocumentWithRelations> = {
    id: "actions",
    enableHiding: false,
    cell: ({ row }) => {
      const gtcDocument = row.original

      const handleViewDetails = () => {
        router.push(`/evcp/gtc/${gtcDocument.id}`)
      }

      const handleCreateNewRevision = () => {
        setRowAction({ row, type: "createRevision" })
      }

      const handleClone = () => {
        setRowAction({ row, type: "clone" })
      }

      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 />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-44">
            <DropdownMenuItem onSelect={handleViewDetails}>
              {/* <Eye className="mr-2 h-4 w-4" /> */}
              상세보기
            </DropdownMenuItem>

            <DropdownMenuSeparator />

            <DropdownMenuItem onSelect={() => setRowAction({ row, type: "update" })}>
              수정하기
            </DropdownMenuItem>

            <DropdownMenuItem onSelect={handleCreateNewRevision}>
              리비전 생성하기
            </DropdownMenuItem>

            <DropdownMenuItem onSelect={handleClone}>
              복제하기
            </DropdownMenuItem>

            <DropdownMenuSeparator />
            <DropdownMenuItem onSelect={() => setRowAction({ row, type: "delete" })}>
              삭제하기
              {/* <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut> */}
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 40,
  }

  // 그룹 없이 평평한 배열 반환
  return [
    selectColumn,
    ...basicInfoColumns,
    ...auditColumns,
    actionsColumn,
  ]
}