import { Checkbox } from "@/components/ui/checkbox"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Eye, History } from "lucide-react"
import { type ColumnDef } from "@tanstack/react-table"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { AvlListItem } from "../types"

interface GetColumnsProps {
  selectedRows?: number[]
  onRowSelect?: (id: number, selected: boolean) => void
}

// 테이블 메타 타입 확장
declare module "@tanstack/react-table" {
  interface TableMeta<TData> {
    onCellUpdate?: (id: string, field: keyof TData, newValue: string | boolean) => Promise<void>
    onCellCancel?: (id: string, field: keyof TData) => void
    onAction?: (action: string, data?: Partial<AvlListItem>) => void
    onSaveEmptyRow?: (tempId: string) => Promise<void>
    onCancelEmptyRow?: (tempId: string) => void
    isEmptyRow?: (id: string) => boolean
  }
}

// 테이블 컬럼 정의 함수
export function getColumns({ selectedRows = [], onRowSelect }: GetColumnsProps): ColumnDef<AvlListItem>[] {
  const columns: ColumnDef<AvlListItem>[] = [
    // select 컬럼
    {
      id: "select",
      header: () => <div className="text-center">선택</div>,
      cell: ({ row }) => (
        <div className="flex justify-center">
          <Checkbox
            checked={selectedRows.includes(row.original.id)}
            onCheckedChange={(checked) => {
              onRowSelect?.(row.original.id, !!checked)
            }}
            aria-label="행 선택"
            className="translate-y-[2px]"
          />
        </div>
      ),
      enableSorting: false,
      enableHiding: false,
      enableResizing: false,
      size: 10,
      minSize: 10,
      maxSize: 10,
    },
    // No 컬럼
    {
      accessorKey: "no",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="No" />
      ),
      cell: ({ getValue }) => <div className="text-center">{getValue() as number}</div>,
      enableResizing: true,
      size: 60,
    },
    // AVL 분류 컬럼
    {
      accessorKey: "isTemplate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="AVL 분류" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as boolean
        return (
          <div className="text-center">
            {value ? "표준 AVL" : "프로젝트 AVL"}
          </div>
        )
      },
      enableResizing: true,
      size: 120,
    },
    // 공사부문 컬럼
    {
      accessorKey: "constructionSector",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="공사부문" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return (
          <div className="text-center">
            {value}
          </div>
        )
      },
      enableResizing: true,
      size: 100,
    },
    // 프로젝트 코드 컬럼
    {
      accessorKey: "projectCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="프로젝트 코드" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return (
          <div className="text-center">
            {value}
          </div>
        )
      },
      enableResizing: true,
      size: 140,
    },
    // 선종 컬럼
    {
      accessorKey: "shipType",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선종" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return (
          <div className="text-center">
            {value}
          </div>
        )
      },
      enableResizing: true,
      size: 100,
    },
    // AVL 종류 컬럼
    {
      accessorKey: "avlKind",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="AVL 종류" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return (
          <div className="text-center">
            {value}
          </div>
        )
      },
      enableResizing: true,
      size: 120,
    },
    // H/T 구분 컬럼
    {
      accessorKey: "htDivision",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="H/T 구분" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return (
          <div className="text-center">
            {value}
          </div>
        )
      },
      enableResizing: true,
      size: 80,
    },
    // Rev 컬럼
    {
      accessorKey: "rev",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Rev" />
      ),
      cell: ({ getValue, row, table }) => {
        const value = getValue() as number
        return (
          <div className="flex items-center gap-1">
            <Badge variant="outline" className="font-mono">
              {value || 1}
            </Badge>
            <Button
              variant="ghost"
              size="sm"
              className="h-6 w-6 p-0"
              onClick={() => table.options.meta?.onAction?.('view-history', row.original)}
              title="리비전 히스토리 보기"
            >
              <History className="h-3 w-3" />
            </Button>
          </div>
        )
      },
      enableResizing: true,
      size: 100,
    },
    // PKG 컬럼
    {
      accessorKey: "PKG",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="PKG" />
      ),
      enableResizing: true,
      size: 80,
    },
    // 자재그룹 컬럼
    {
      accessorKey: "materialGroup",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="자재그룹" />
      ),
      enableResizing: true,
      size: 120,
    },
    // 협력업체 컬럼
    {
      accessorKey: "vendor",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="협력업체" />
      ),
      enableResizing: true,
      size: 150,
    },
    // Tier 컬럼
    {
      accessorKey: "Tier",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Tier" />
      ),
      enableResizing: true,
      size: 60,
    },
    // 선주 제안 컬럼
    {
      accessorKey: "ownerSuggestion",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선주 제안" />
      ),
      enableResizing: true,
      size: 100,
    },
    // SHI 제안 컬럼
    {
      accessorKey: "shiSuggestion",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="SHI 제안" />
      ),
      enableResizing: true,
      size: 100,
    },
    // 등록일 컬럼
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="등록일" />
      ),
      cell: ({ getValue }) => {
        const date = getValue() as string
        return <div className="text-center text-sm">{date}</div>
      },
      enableResizing: true,
      size: 100,
    },
    // 등록자 컬럼
    {
      accessorKey: "createdBy",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="등록자" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return <div className="text-center text-sm">{value}</div>
      },
      enableResizing: true,
      size: 100,
    },
    // 최종변경일 컬럼
    {
      accessorKey: "updatedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="최종변경일" />
      ),
      cell: ({ getValue }) => {
        const date = getValue() as string
        return <div className="text-center text-sm">{date}</div>
      },
      enableResizing: true,
      size: 100,
    },
    // 최종변경자 컬럼
    {
      accessorKey: "updatedBy",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="최종변경자" />
      ),
      cell: ({ getValue }) => {
        const value = getValue() as string
        return <div className="text-center text-sm">{value}</div>
      },
      enableResizing: true,
      size: 100,
    },
    // 액션 컬럼
    {
      id: "actions",
      header: () => <div className="text-center">액션</div>,
      cell: ({ row, table }) => {
        const isEmptyRow = table.options.meta?.isEmptyRow?.(row.id) || false

        if (isEmptyRow) {
          return (
            <div className="flex items-center justify-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => table.options.meta?.onSaveEmptyRow?.(row.id)}
                className="h-8 w-8 p-0"
              >
                저장
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => table.options.meta?.onCancelEmptyRow?.(row.id)}
                className="h-8 w-8 p-0 text-destructive hover:text-destructive"
              >
                취소
              </Button>
            </div>
          )
        }

        return (
          <div className="flex items-center justify-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => table.options.meta?.onAction?.("view-detail", { id: row.original.id })}
              className="h-8 w-8 p-0"
              title="상세보기"
            >
              <Eye className="h-4 w-4" />
            </Button>
          </div>
        )
      },
      enableSorting: false,
      enableHiding: false,
      enableResizing: false,
      size: 120,
      minSize: 120,
      maxSize: 120,
    },
  ]

  return columns
}
