"use client";
import * as React from "react";
import { type ColumnDef } from "@tanstack/react-table";
import { Checkbox } from "@/components/ui/checkbox";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Pencil, Eye, MessageSquare, Check, X } from "lucide-react";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import { EvaluationTargetWithDepartments } from "@/db/schema";
import { EditEvaluationTargetSheet } from "./update-evaluation-target";

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<EvaluationTargetWithDepartments> | null>>;
}

// 상태별 색상 매핑
const getStatusBadgeVariant = (status: string) => {
  switch (status) {
    case "PENDING":
      return "secondary";
    case "CONFIRMED":
      return "default";
    case "EXCLUDED":
      return "destructive";
    default:
      return "outline";
  }
};

// 의견 일치 여부 배지
const getConsensusBadge = (consensusStatus: boolean | null) => {
  if (consensusStatus === null) {
    return <Badge variant="outline">검토 중</Badge>;
  }
  if (consensusStatus === true) {
    return <Badge variant="default" className="bg-green-600">의견 일치</Badge>;
  }
  return <Badge variant="destructive">의견 불일치</Badge>;
};

// 구분 배지
const getDivisionBadge = (division: string) => {
  return (
    <Badge variant={division === "PLANT" ? "default" : "secondary"}>
      {division === "PLANT" ? "해양" : "조선"}
    </Badge>
  );
};

// 자재구분 배지  
const getMaterialTypeBadge = (materialType: string) => {
  const typeMap = {
    EQUIPMENT: "기자재",
    BULK: "벌크",
    EQUIPMENT_BULK: "기자재/벌크"
  };
  return <Badge variant="outline">{typeMap[materialType] || materialType}</Badge>;
};

// 내외자 배지
const getDomesticForeignBadge = (domesticForeign: string) => {
  return (
    <Badge variant={domesticForeign === "DOMESTIC" ? "default" : "secondary"}>
      {domesticForeign === "DOMESTIC" ? "내자" : "외자"}
    </Badge>
  );
};

// 평가 상태 배지
const getApprovalBadge = (isApproved: boolean | null) => {
  if (isApproved === null) {
    return <Badge variant="outline" className="text-xs">대기중</Badge>;
  }
  if (isApproved === true) {
    return <Badge variant="default" className="bg-green-600 text-xs">승인</Badge>;
  }
  return <Badge variant="destructive" className="text-xs">거부</Badge>;
};

export function getEvaluationTargetsColumns({setRowAction}:GetColumnsProps): ColumnDef<EvaluationTargetWithDepartments>[] {
  return [
    // ═══════════════════════════════════════════════════════════════
    // 기본 정보
    // ═══════════════════════════════════════════════════════════════

    // Checkbox 
    {
      id: "select",
      header: ({ table }) => (
        <Checkbox
          checked={table.getIsAllPageRowsSelected() || (table.getIsSomePageRowsSelected() && "indeterminate")}
          onCheckedChange={(v) => table.toggleAllPageRowsSelected(!!v)}
          aria-label="select all"
          className="translate-y-0.5"
        />
      ),
      cell: ({ row }) => (
        <Checkbox
          checked={row.getIsSelected()}
          onCheckedChange={(v) => row.toggleSelected(!!v)}
          aria-label="select row"
          className="translate-y-0.5"
        />
      ),
      size: 40,
      enableSorting: false,
      enableHiding: false,
    },

    // ░░░ 평가년도 ░░░
    {
      accessorKey: "evaluationYear",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가년도" />,
      cell: ({ row }) => <span className="font-medium">{row.getValue("evaluationYear")}</span>,
      size: 100,
    },

    // ░░░ 구분 ░░░
    {
      accessorKey: "division",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="구분" />,
      cell: ({ row }) => getDivisionBadge(row.getValue("division")),
      size: 80,
    },
    {
      accessorKey: "status",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="상태" />,
      cell: ({ row }) => {
        const status = row.getValue<string>("status");
        const statusMap = {
          PENDING: "검토 중",
          CONFIRMED: "확정",
          EXCLUDED: "제외"
        };
        return (
          <Badge variant={getStatusBadgeVariant(status)}>
            {statusMap[status] || status}
          </Badge>
        );
      },
      size: 100,
    },

    // ░░░ 벤더 코드 ░░░

    {
      header: "협력업체 정보",
      columns: [
        {
          accessorKey: "vendorCode",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="벤더 코드" />,
          cell: ({ row }) => (
            <span className="font-mono text-sm">{row.getValue("vendorCode")}</span>
          ),
          size: 120,
        },

        // ░░░ 벤더명 ░░░
        {
          accessorKey: "vendorName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="벤더명" />,
          cell: ({ row }) => (
            <div className="truncate max-w-[200px]" title={row.getValue<string>("vendorName")!}>
              {row.getValue("vendorName") as string}
            </div>
          ),
          size: 200,
        },

        // ░░░ 내외자 ░░░
        {
          accessorKey: "domesticForeign",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="내외자" />,
          cell: ({ row }) => getDomesticForeignBadge(row.getValue("domesticForeign")),
          size: 80,
        },

      ]
    },

    // ░░░ 자재구분 ░░░
    {
      accessorKey: "materialType",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="자재구분" />,
      cell: ({ row }) => getMaterialTypeBadge(row.getValue("materialType")),
      size: 120,
    },

    // ░░░ 상태 ░░░


    // ░░░ 의견 일치 여부 ░░░
    {
      accessorKey: "consensusStatus",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="의견 일치" />,
      cell: ({ row }) => getConsensusBadge(row.getValue("consensusStatus")),
      size: 100,
    },

    // ═══════════════════════════════════════════════════════════════
    // 주문 부서 그룹
    // ═══════════════════════════════════════════════════════════════
    {
      header: "발주 평가 담당자",
      columns: [
        {
          accessorKey: "orderDepartmentName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="부서명" />,
          cell: ({ row }) => {
            const departmentName = row.getValue<string>("orderDepartmentName");
            return departmentName ? (
              <div className="truncate max-w-[120px]" title={departmentName}>
                {departmentName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "orderReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("orderReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[100px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },
        {
          accessorKey: "orderIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가" />,
          cell: ({ row }) => getApprovalBadge(row.getValue("orderIsApproved")),
          size: 80,
        },
      ],
    },

    // ═══════════════════════════════════════════════════════════════
    // 조달 부서 그룹
    // ═══════════════════════════════════════════════════════════════
    {
      header: "조달 평가 담당자",
      columns: [
        {
          accessorKey: "procurementDepartmentName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="부서명" />,
          cell: ({ row }) => {
            const departmentName = row.getValue<string>("procurementDepartmentName");
            return departmentName ? (
              <div className="truncate max-w-[120px]" title={departmentName}>
                {departmentName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "procurementReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("procurementReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[100px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },
        {
          accessorKey: "procurementIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가" />,
          cell: ({ row }) => getApprovalBadge(row.getValue("procurementIsApproved")),
          size: 80,
        },
      ],
    },

    // ═══════════════════════════════════════════════════════════════
    // 품질 부서 그룹
    // ═══════════════════════════════════════════════════════════════
    {
      header: "품질 평가 담당자",
      columns: [
        {
          accessorKey: "qualityDepartmentName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="부서명" />,
          cell: ({ row }) => {
            const departmentName = row.getValue<string>("qualityDepartmentName");
            return departmentName ? (
              <div className="truncate max-w-[120px]" title={departmentName}>
                {departmentName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "qualityReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("qualityReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[100px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },
        {
          accessorKey: "qualityIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가" />,
          cell: ({ row }) => getApprovalBadge(row.getValue("qualityIsApproved")),
          size: 80,
        },
      ],
    },

    // ═══════════════════════════════════════════════════════════════
    // 설계 부서 그룹
    // ═══════════════════════════════════════════════════════════════
    {
      header: "설계 평가 담당자",
      columns: [
        {
          accessorKey: "designDepartmentName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="부서명" />,
          cell: ({ row }) => {
            const departmentName = row.getValue<string>("designDepartmentName");
            return departmentName ? (
              <div className="truncate max-w-[120px]" title={departmentName}>
                {departmentName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "designReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("designReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[100px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },
        {
          accessorKey: "designIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가" />,
          cell: ({ row }) => getApprovalBadge(row.getValue("designIsApproved")),
          size: 80,
        },
      ],
    },

    // ═══════════════════════════════════════════════════════════════
    // CS 부서 그룹
    // ═══════════════════════════════════════════════════════════════
    {
      header: "CS 평가 담당자",
      columns: [
        {
          accessorKey: "csDepartmentName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="부서명" />,
          cell: ({ row }) => {
            const departmentName = row.getValue<string>("csDepartmentName");
            return departmentName ? (
              <div className="truncate max-w-[120px]" title={departmentName}>
                {departmentName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "csReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("csReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[100px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },
        {
          accessorKey: "csIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가" />,
          cell: ({ row }) => getApprovalBadge(row.getValue("csIsApproved")),
          size: 80,
        },
      ],
    },

    // ═══════════════════════════════════════════════════════════════
    // 관리 정보
    // ═══════════════════════════════════════════════════════════════

    // ░░░ 관리자 의견 ░░░
    {
      accessorKey: "adminComment",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="관리자 의견" />,
      cell: ({ row }) => {
        const comment = row.getValue<string>("adminComment");
        return comment ? (
          <div className="truncate max-w-[150px]" title={comment}>
            {comment}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 150,
    },

    // ░░░ 종합 의견 ░░░
    {
      accessorKey: "consolidatedComment",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="종합 의견" />,
      cell: ({ row }) => {
        const comment = row.getValue<string>("consolidatedComment");
        return comment ? (
          <div className="truncate max-w-[150px]" title={comment}>
            {comment}
          </div>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 150,
    },

    // ░░░ 확정일 ░░░
    {
      accessorKey: "confirmedAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="확정일" />,
      cell: ({ row }) => {
        const confirmedAt = row.getValue<Date>("confirmedAt");
        return confirmedAt ? (
          <span className="text-sm">
            {new Intl.DateTimeFormat("ko-KR", {
              year: "numeric",
              month: "2-digit",
              day: "2-digit",
            }).format(new Date(confirmedAt))}
          </span>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 100,
    },

    // ░░░ 생성일 ░░░
    {
      accessorKey: "createdAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="생성일" />,
      cell: ({ row }) => {
        const createdAt = row.getValue<Date>("createdAt");
        return createdAt ? (
          <span className="text-sm">
            {new Intl.DateTimeFormat("ko-KR", {
              year: "numeric",
              month: "2-digit",
              day: "2-digit",
            }).format(new Date(createdAt))}
          </span>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 100,
    },

    // ░░░ Actions ░░░
    {
      id: "actions",
      enableHiding: false,
      size: 40,
      minSize: 40,
      cell: ({ row }) => {
             return (
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="icon"
              className="size-8"
              onClick={() => setRowAction({ row, type: "update" })}
              aria-label="수정"
              title="수정"
            >
              <Pencil className="size-4" />
            </Button>

          </div>
        );
      },
    },
  ];
}