import { ColumnDef } from "@tanstack/react-table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { PcrPrData } from "@/lib/pcr/types"
import { FileIcon, Download } from "lucide-react"
import { downloadFile } from "@/lib/file-download"

export function getPcrDetailColumns(): ColumnDef<PcrPrData>[] {
  return [
    {
      accessorKey: "materialNumber",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="자재번호" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("materialNumber") as string
        return (
          <div className="font-medium">
            {value || "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "materialDetails",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="자재내역" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("materialDetails") as string
        return (
          <div className="max-w-[200px] truncate" title={value}>
            {value || "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "quantityBefore",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="수량(변경전)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("quantityBefore") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? value.toLocaleString() : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "quantityAfter",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="수량(변경후)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("quantityAfter") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? value.toLocaleString() : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "weightBefore",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="중량(변경전)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("weightBefore") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? `${value.toLocaleString()} kg` : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "weightAfter",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="중량(변경후)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("weightAfter") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? `${value.toLocaleString()} kg` : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "subcontractorWeightBefore",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="사급중량(변경전)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("subcontractorWeightBefore") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? `${value.toLocaleString()} kg` : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "subcontractorWeightAfter",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="사급중량(변경후)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("subcontractorWeightAfter") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? `${value.toLocaleString()} kg` : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "supplierWeightBefore",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="도급중량(변경전)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("supplierWeightBefore") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? `${value.toLocaleString()} kg` : "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "supplierWeightAfter",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="도급중량(변경후)" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("supplierWeightAfter") as number
        return (
          <div className="text-right font-mono text-sm">
            {value ? `${value.toLocaleString()} kg` : "-"}
          </div>
        )
      },
    },
    {
      id: "attachments",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="첨부파일" />
      ),
      cell: ({ row }) => {
        const attachments = row.original.attachments || []
        const beforeAttachment = attachments.find(att => att.type === 'BEFORE')
        const afterAttachment = attachments.find(att => att.type === 'AFTER')

        if (!beforeAttachment && !afterAttachment) {
          return (
            <div className="text-center text-muted-foreground">
              <FileIcon className="size-4 mx-auto" />
            </div>
          )
        }

        return (
          <div className="flex gap-1 justify-center">
            {/* 변경전 첨부파일 */}
            {beforeAttachment && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  downloadFile(beforeAttachment.filePath, beforeAttachment.fileName)
                }}
                title={`변경전: ${beforeAttachment.fileName}`}
                className="h-6 w-6 p-0"
              >
                <Download className="size-3" />
              </Button>
            )}

            {/* 변경후 첨부파일 */}
            {afterAttachment && (
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  downloadFile(afterAttachment.filePath, afterAttachment.fileName)
                }}
                title={`변경후: ${afterAttachment.fileName}`}
                className="h-6 w-6 p-0"
              >
                <Download className="size-3" />
              </Button>
            )}
          </div>
        )
      },
    },
    {
      accessorKey: "initialPoContractDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="최초 PO/계약일" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("initialPoContractDate") as Date
        if (!value) return "-"

        return (
          <div className="text-sm">
            {value.toLocaleDateString('ko-KR', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            })}
          </div>
        )
      },
    },
    {
      accessorKey: "specChangeDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="SPEC 변경일" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("specChangeDate") as Date
        if (!value) return "-"

        return (
          <div className="text-sm">
            {value.toLocaleDateString('ko-KR', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            })}
          </div>
        )
      },
    },
    {
      accessorKey: "poContractModifiedDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="PO/계약수정일" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("poContractModifiedDate") as Date
        if (!value) return "-"

        return (
          <div className="text-sm">
            {value.toLocaleDateString('ko-KR', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            })}
          </div>
        )
      },
    },
    {
      accessorKey: "confirmationDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="확인일" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("confirmationDate") as Date
        if (!value) return "-"

        return (
          <div className="text-sm">
            {value.toLocaleDateString('ko-KR', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            })}
          </div>
        )
      },
    },
    {
      accessorKey: "designManager",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="설계담당자" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("designManager") as string
        return (
          <div className="max-w-[120px] truncate" title={value}>
            {value || "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "poContractNumber",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="PO/계약번호" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("poContractNumber") as string
        return (
          <div className="font-medium">
            {value || "-"}
          </div>
        )
      },
    },
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일" />
      ),
      cell: ({ row }) => {
        const value = row.getValue("createdAt") as Date
        if (!value) return "-"

        return (
          <div className="text-sm">
            {value.toLocaleDateString('ko-KR', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit'
            })}
          </div>
        )
      },
    },
  ]
}
