"use client";

import { ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@/components/ui/checkbox";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import Link from "next/link";
// 타입만 import
type TechVendorPossibleItemsData = {
  id: number;
  vendorId: number;
  vendorCode: string | null;
  vendorName: string;
  techVendorType: string;
  vendorStatus: string;
  itemCode: string;
  itemList: string | null;
  workType: string | null;
  shipTypes: string | null;
  subItemList: string | null;
  createdAt: Date;
  updatedAt: Date;
};
import { format } from "date-fns";
import { ko } from "date-fns/locale";
import { Badge } from "@/components/ui/badge";

export function getColumns(): ColumnDef<TechVendorPossibleItemsData>[] {
  return [
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={
            table.getIsAllPageRowsSelected() ||
            (table.getIsSomePageRowsSelected() && "indeterminate")
          }
          onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
          aria-label="모두 선택"
          className="translate-y-[2px]"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(value) => row.toggleSelected(!!value)}
          aria-label="행 선택"
          className="translate-y-[2px]"
        />
      ),
      enableSorting: false,
      enableHiding: false,
    },
    {
      accessorKey: "itemCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="아이템코드" />
      ),
      cell: ({ row }) => {
        const itemCode = row.getValue("itemCode") as string;
        return <div className="font-medium">{itemCode}</div>;
      },
    },
    {
      accessorKey: "itemList",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="아이템리스트" />
      ),
      cell: ({ row }) => {
        const itemList = row.getValue("itemList") as string | null;
        return <div className="max-w-[200px] truncate">{itemList || "-"}</div>;
      },
      filterFn: (row, id, value) => {
        const itemList = row.getValue(id) as string | null;
        if (!value) return true;
        if (!itemList) return false;
        return itemList.toLowerCase().includes(value.toLowerCase());
      },
    },
    {
      accessorKey: "workType",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="공종" />
      ),
      cell: ({ row }) => {
        const workType = row.getValue("workType") as string | null;
        return <div className="font-medium">{workType || "-"}</div>;
      },
      filterFn: (row, id, value) => {
        const workType = row.getValue(id) as string | null;
        if (!value) return true;
        if (!workType) return false;
        return workType.toLowerCase().includes(value.toLowerCase());
      },
    },
    {
      accessorKey: "shipTypes",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="선종" />
      ),
      cell: ({ row }) => {
        const shipTypes = row.getValue("shipTypes") as string | null;
        return <div className="font-medium">{shipTypes || "-"}</div>;
      },
      filterFn: (row, id, value) => {
        const shipTypes = row.getValue(id) as string | null;
        if (!value) return true;
        if (!shipTypes) return false;
        return shipTypes.toLowerCase().includes(value.toLowerCase());
      },
    },
    {
      accessorKey: "subItemList",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="서브아이템리스트" />
      ),
      cell: ({ row }) => {
        const subItemList = row.getValue("subItemList") as string | null;
        return <div className="max-w-[200px] truncate">{subItemList || "-"}</div>;
      },
      filterFn: (row, id, value) => {
        const subItemList = row.getValue(id) as string | null;
        if (!value) return true;
        if (!subItemList) return false;
        return subItemList.toLowerCase().includes(value.toLowerCase());
      },
    },
    {
      accessorKey: "vendorCode",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더코드" />
      ),
      cell: ({ row }) => {
        const vendorCode = row.getValue("vendorCode") as string;
        return <div className="font-medium">{vendorCode || "-"}</div>;
      },
    },
    {
      accessorKey: "vendorName",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더명" />
      ),
      cell: ({ row }) => {
        const vendorName = row.getValue("vendorName") as string;
        const vendorId = row.original.vendorId;
        return (
          <Link 
            href={`/ko/evcp/tech-vendors/${vendorId}/info`}
            className="max-w-[200px] truncate hover:underline"
          >
            {vendorName}
          </Link>
        );
      },
    },
    {
      accessorKey: "techVendorType",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더타입" />
      ),
      cell: ({ row }) => {
        const techVendorType = row.getValue("techVendorType") as string;
        
        // 벤더 타입 파싱 개선
        let types: string[] = [];
        if (!techVendorType) {
          types = [];
        } else if (techVendorType.startsWith('[') && techVendorType.endsWith(']')) {
          // JSON 배열 형태
          try {
            const parsed = JSON.parse(techVendorType);
            types = Array.isArray(parsed) ? parsed.filter(Boolean) : [techVendorType];
          } catch {
            types = [techVendorType];
          }
        } else if (techVendorType.includes(',')) {
          // 콤마로 구분된 문자열
          types = techVendorType.split(',').map(t => t.trim()).filter(Boolean);
        } else {
          // 단일 문자열
          types = [techVendorType.trim()].filter(Boolean);
        }

        return (
          <div className="flex flex-wrap gap-1">
            {types.length > 0 ? types.map((type, index) => (
              <Badge key={`${type}-${index}`} variant="secondary" className="text-xs">
                {type}
              </Badge>
            )) : (
              <span className="text-muted-foreground">-</span>
            )}
          </div>
        );
      },
      filterFn: (row, id, value) => {
        const techVendorType = row.getValue(id) as string;
        if (!techVendorType || !value) return false;
        
        let types: string[] = [];
        if (techVendorType.startsWith('[') && techVendorType.endsWith(']')) {
          try {
            const parsed = JSON.parse(techVendorType);
            types = Array.isArray(parsed) ? parsed : [techVendorType];
          } catch {
            types = [techVendorType];
          }
        } else if (techVendorType.includes(',')) {
          types = techVendorType.split(',').map(t => t.trim());
        } else {
          types = [techVendorType.trim()];
        }
        
        return types.some(type => 
          type.toLowerCase().includes(value.toLowerCase())
        );
      },
    },

    {
      accessorKey: "vendorStatus",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="벤더상태" />
      ),
      cell: ({ row }) => {
        const vendorStatus = row.getValue("vendorStatus") as string;
        const getStatusColor = (status: string) => {
          switch (status) {
            case "ACTIVE": return "bg-green-100 text-green-800";
            case "PENDING_INVITE": return "bg-yellow-100 text-yellow-800";
            case "PENDING_REVIEW": return "bg-blue-100 text-blue-800";
            case "INACTIVE": return "bg-gray-100 text-gray-800";
            default: return "bg-gray-100 text-gray-800";
          }
        };
        return (
          <Badge className={getStatusColor(vendorStatus)}>
            {vendorStatus}
          </Badge>
        );
      },
    },
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일시" />
      ),
      cell: ({ row }) => {
        const createdAt = row.getValue("createdAt") as Date;
        return (
          <div className="text-sm text-muted-foreground">
            {format(createdAt, "yyyy-MM-dd HH:mm", { locale: ko })}
          </div>
        );
      },
    },
  ];
} 