"use client"

import { type ColumnDef } from "@tanstack/react-table"
import { Checkbox } from "@/components/ui/checkbox"
import { Badge } from "@/components/ui/badge"
import { format } from "date-fns"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import type { VendorRegularRegistration } from "@/config/vendorRegularRegistrationsColumnsConfig"
import { DocumentStatusDialog } from "@/components/vendor-regular-registrations/document-status-dialog"
import { Button } from "@/components/ui/button"
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"
import { Eye, FileText, Ellipsis } from "lucide-react"
import { toast } from "sonner"
import { useState } from "react"

const statusLabels = {
  audit_pass: "실사통과",
  cp_submitted: "CP등록",
  cp_review: "CP검토",
  cp_finished: "CP완료",
  approval_ready: "조건충족",
  in_review: "정규등록검토",
  pending_approval: "장기미등록",
}

const statusColors = {
  audit_pass: "bg-blue-100 text-blue-800",
  cp_submitted: "bg-green-100 text-green-800",
  cp_review: "bg-yellow-100 text-yellow-800",
  cp_finished: "bg-purple-100 text-purple-800",
  approval_ready: "bg-emerald-100 text-emerald-800",
  in_review: "bg-orange-100 text-orange-800",
  pending_approval: "bg-red-100 text-red-800",
}

export function getColumns(): ColumnDef<VendorRegularRegistration>[] {

  return [
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && "indeterminate")
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="Select all"
          className="translate-y-[2px]"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="Select row"
          className="translate-y-[2px]"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: "status",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="Status" />
      ),
      cell: ({ row }) => {
        const status = row.getValue("status") as string
        return (
          <Badge
            variant="secondary"
            className={statusColors[status as keyof typeof statusColors]}
          >
            {statusLabels[status as keyof typeof statusLabels] || status}
          </Badge>
        )
      },
      filterFn: (row, id, value) => {
        return Array.isArray(value) && value.includes(row.getValue(id))
      },
    },
    {
      accessorKey: "potentialCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="잠재코드" />
      ),
      cell: ({ row }) => row.getValue("potentialCode") || "-",
    },
    {
      accessorKey: "businessNumber",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="사업자번호" />
      ),
    },
    {
      accessorKey: "companyName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="업체명" />
      ),
    },
    {
      accessorKey: "majorItems",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="주요품목" />
      ),
      cell: ({ row }) => {
        const majorItems = row.getValue("majorItems") as string
        try {
          const items = majorItems ? JSON.parse(majorItems) : []
          if (items.length === 0) return "-"
          
          // 첫 번째 아이템을 itemCode-itemName 형태로 표시
          const firstItem = items[0]
          let displayText = ""
          
          if (typeof firstItem === 'string') {
            displayText = firstItem
          } else if (typeof firstItem === 'object') {
            const code = firstItem.itemCode || firstItem.code || ""
            const name = firstItem.itemName || firstItem.name || firstItem.materialGroupName || ""
            if (code && name) {
              displayText = `${code}-${name}`
            } else {
              displayText = name || code || String(firstItem)
            }
          } else {
            displayText = String(firstItem)
          }
          
          // 나머지 개수 표시
          if (items.length > 1) {
            displayText += ` 외 ${items.length - 1}개`
          }
          
          return displayText
        } catch {
          return majorItems || "-"
        }
      },
    },
    {
      accessorKey: "establishmentDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="설립일자" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("establishmentDate") as string
        return date ? format(new Date(date), "yyyy.MM.dd") : "-"
      },
    },
    {
      accessorKey: "representative",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="대표자명" />
      ),
      cell: ({ row }) => row.getValue("representative") || "-",
    },
    {
      id: "documentStatus", 
      header: "문서/자료 접수 현황",
      cell: ({ row }) => {
        const DocumentStatusCell = () => {
          const [documentDialogOpen, setDocumentDialogOpen] = useState(false)
          const registration = row.original

          return (
            <>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => setDocumentDialogOpen(true)}
              >
                <Eye className="w-4 h-4" />
                현황보기
              </Button>
              <DocumentStatusDialog
                open={documentDialogOpen}
                onOpenChange={setDocumentDialogOpen}
                registration={registration}
              />
            </>
          )
        }
        
        return <DocumentStatusCell />
      },
    },
    {
      accessorKey: "registrationRequestDate",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="등록요청일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("registrationRequestDate") as string
        return date ? format(new Date(date), "yyyy.MM.dd") : "-"
      },
    },
    {
      accessorKey: "assignedDepartment",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="담당부서" />
      ),
      cell: ({ row }) => row.getValue("assignedDepartment") || "-",
    },
    {
      accessorKey: "assignedUser",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="담당자" />
      ),
      cell: ({ row }) => row.getValue("assignedUser") || "-",
    },
    {
      accessorKey: "remarks",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="비고" />
      ),
      cell: ({ row }) => row.getValue("remarks") || "-",
    },
    {
      id: "actions",
      cell: ({ row }) => {
        const ActionsDropdownCell = () => {
          const [documentDialogOpen, setDocumentDialogOpen] = useState(false)
          const registration = row.original

          return (
            <>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    aria-label="Open menu"
                    variant="ghost"
                    className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
                  >
                    <Ellipsis className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-[160px]">
                  <DropdownMenuItem
                    onClick={() => setDocumentDialogOpen(true)}
                  >
                    <Eye className="mr-2 h-4 w-4" />
                    현황보기
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    onClick={() => {
                      toast.info("정규업체 등록 요청 기능은 준비 중입니다.")
                    }}
                  >
                    <FileText className="mr-2 h-4 w-4" />
                    등록요청
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
              <DocumentStatusDialog
                open={documentDialogOpen}
                onOpenChange={setDocumentDialogOpen}
                registration={registration}
              />
            </>
          )
        }

        return <ActionsDropdownCell />
      },
    },
  ]
}
