// ================================================================
// 1. PERIODIC EVALUATIONS COLUMNS
// ================================================================

"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, Clock, FileText, Circle } from "lucide-react";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import { PeriodicEvaluationView } from "@/db/schema";
import { DataTableRowAction } from "@/types/table";
import { vendortypeMap } from "@/types/evaluation";



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

// 상태별 색상 매핑
const getStatusBadgeVariant = (status: string) => {
  switch (status) {
    case "PENDING_SUBMISSION":
      return "outline";
    case "SUBMITTED":
      return "secondary";
    case "IN_REVIEW":
      return "default";
    case "REVIEW_COMPLETED":
      return "default";
    case "FINALIZED":
      return "default";
    default:
      return "outline";
  }
};

const getStatusLabel = (status: string) => {
  const statusMap = {
    PENDING_SUBMISSION: "제출대기",
    SUBMITTED: "제출완료",
    IN_REVIEW: "검토중",
    REVIEW_COMPLETED: "검토완료",
    FINALIZED: "최종확정"
  };
  return statusMap[status] || status;
};

// 부서별 상태 배지 함수
const getDepartmentStatusBadge = (status: string | null) => {
  if (!status) return (
    <div className="flex items-center gap-1">
      {/* <Circle className="w-4 h-4 fill-gray-300 text-gray-300" /> */}
      <span className="text-xs text-gray-500">-</span>
    </div>
  );
  
  switch (status) {
    case "NOT_ASSIGNED":
      return (
        <div className="flex items-center gap-1">
          {/* <Circle className="w-4 h-4 fill-gray-400 text-gray-400" /> */}
          <span className="text-xs text-gray-600">미지정</span>
        </div>
      );
    case "NOT_STARTED":
      return (
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 rounded-full bg-red-500 shadow-sm" />

          {/* <span className="text-xs text-red-600">시작전</span> */}
        </div>
      );
    case "IN_PROGRESS":
      return (
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 rounded-full bg-yellow-500 shadow-sm" />
          {/* <span className="text-xs text-yellow-600">진행중</span> */}
        </div>
      );
    case "COMPLETED":
      return (
        <div className="flex items-center gap-1">
          <div className="w-4 h-4 rounded-full bg-green-500 shadow-sm" />
          {/* <span className="text-xs text-green-600">완료</span> */}
        </div>
      );
    default:
      return (
        <div className="flex items-center gap-1">
          {/* <Circle className="w-4 h-4 fill-gray-300 text-gray-300" /> */}
          <span className="text-xs text-gray-500">-</span>
        </div>
      );
  }
};
// 부서명 라벨
const DEPARTMENT_LABELS = {
  ORDER_EVAL: "발주",
  PROCUREMENT_EVAL: "조달", 
  QUALITY_EVAL: "품질",
  DESIGN_EVAL: "설계",
  CS_EVAL: "CS"
} as const;

// 등급별 색상
const getGradeBadgeVariant = (grade: string | null) => {
  if (!grade) return "outline";
  switch (grade) {
    case "S":
      return "default";
    case "A":
      return "secondary";
    case "B":
      return "outline";
    case "C":
      return "destructive";
    case "D":
      return "destructive";
    default:
      return "outline";
  }
};

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

// 자재구분 배지  
const getMaterialTypeBadge = (materialType: string) => {

  return <Badge variant="outline">{vendortypeMap[materialType] || materialType}</Badge>;
};

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

// 진행률 배지
const getProgressBadge = (completed: number, total: number) => {
  if (total === 0) return <Badge variant="outline">-</Badge>;
  
  const percentage = Math.round((completed / total) * 100);
  const variant = percentage === 100 ? "default" : percentage >= 50 ? "secondary" : "destructive";
  
  return <Badge variant={variant}>{completed}/{total} ({percentage}%)</Badge>;
};

export function getPeriodicEvaluationsColumns({setRowAction}: GetColumnsProps): ColumnDef<PeriodicEvaluationView>[] {
  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.original.evaluationYear}</span>,
      size: 100,
    },

    // ░░░ 평가기간 ░░░
    // {
    //   accessorKey: "evaluationPeriod",
    //   header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가기간" />,
    //   cell: ({ row }) => (
    //     <Badge variant="outline">{row.getValue("evaluationPeriod")}</Badge>
    //   ),
    //   size: 100,
    // },

    // ░░░ 구분 ░░░
    {
      accessorKey: "division",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="구분" />,
      cell: ({ row }) => getDivisionBadge(row.original.division || ""),
      size: 80,
    },

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

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

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

        {
          accessorKey: "materialType",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="자재구분" />,
          cell: ({ row }) => getMaterialTypeBadge(row.original.materialType || ""),
          size: 120,
        },
      ]
    },
        
    {
      accessorKey: "finalScore",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="확정점수" />,
      cell: ({ row }) => {
        const finalScore = row.getValue<number>("finalScore");
        return finalScore ? (
          <span className="font-bold text-green-600">{finalScore.toFixed(1)}</span>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 90,
    },

    {
      accessorKey: "finalGrade",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="확정등급" />,
      cell: ({ row }) => {
        const finalGrade = row.getValue<string>("finalGrade");
        return finalGrade ? (
          <Badge variant={getGradeBadgeVariant(finalGrade)} className="bg-green-600">
            {finalGrade}
          </Badge>
        ) : (
          <span className="text-muted-foreground">-</span>
        );
      },
      size: 90,
    },

        // ═══════════════════════════════════════════════════════════════
    // 진행 현황
    // ═══════════════════════════════════════════════════════════════
    {
      header: "부서별 평가 현황",
      columns: [
        {
          accessorKey: "orderEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="발주" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("orderEvalStatus")),
          size: 60,
        },
        
        {
          accessorKey: "procurementEvalStatus", 
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="조달" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("procurementEvalStatus")),
          size: 70,
        },
        
        {
          accessorKey: "qualityEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="품질" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("qualityEvalStatus")),
          size: 70,
        },
        
        {
          accessorKey: "designEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="설계" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("designEvalStatus")),
          size: 70,
        },
        
        {
          accessorKey: "csEvalStatus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="CS" />,
          cell: ({ row }) => getDepartmentStatusBadge(row.getValue("csEvalStatus")),
          size: 70,
        },
      ]
    },
    // ═══════════════════════════════════════════════════════════════
    // 제출 현황
    // ═══════════════════════════════════════════════════════════════
    {
      header: "협력업체 제출 현황",
      columns: [
        {
          accessorKey: "documentsSubmitted",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="문서제출" />,
          cell: ({ row }) => {
            const submitted = row.getValue<boolean>("documentsSubmitted");
            return (
              <Badge variant={submitted ? "default" : "destructive"}>
                {submitted ? "제출완료" : "미제출"}
              </Badge>
            );
          },
          size: 120,
        },

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

        {
          accessorKey: "submissionDeadline",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="마감일" />,
          cell: ({ row }) => {
            const deadline = row.getValue<Date>("submissionDeadline");
            if (!deadline) return <span className="text-muted-foreground">-</span>;
            
            const now = new Date();
            const isOverdue = now > deadline;
            
            return (
              <span className={`text-sm ${isOverdue ? "text-red-600" : ""}`}>
                {new Intl.DateTimeFormat("ko-KR", {
                  month: "2-digit",
                  day: "2-digit",
                }).format(new Date(deadline))}
              </span>
            );
          },
          size: 80,
        },
      ]
    },



    // ═══════════════════════════════════════════════════════════════
    // 평가 점수
    // ═══════════════════════════════════════════════════════════════
    {
      header: "평가 점수",
      columns: [
        {
          accessorKey: "processScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="공정" />,
          cell: ({ row }) => {
            const score = row.getValue("processScore");
            return score ? (
              <span className="font-medium">{Number(score).toFixed(1)}</span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
        },

        {
          accessorKey: "priceScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="가격" />,
          cell: ({ row }) => {
            const score = row.getValue("priceScore");
            return score ? (
              <span className="font-medium">{Number(score).toFixed(1)}</span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
        },
        
        {
          accessorKey: "deliveryScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="납기" />,
          cell: ({ row }) => {
            const score = row.getValue("deliveryScore");
            return score ? (
              <span className="font-medium">{Number(score).toFixed(1)}</span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
        },       
        
        {
          accessorKey: "selfEvaluationScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="자율평가" />,
          cell: ({ row }) => {
            const score = row.getValue("selfEvaluationScore");
            return score ? (
              <span className="font-medium">{Number(score).toFixed(1)}</span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
        },

        // ✅ 합계 - 4개 점수의 합으로 계산
        {
          id: "totalScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="합계" />,
          cell: ({ row }) => {
            const processScore = Number(row.getValue("processScore") || 0);
            const priceScore = Number(row.getValue("priceScore") || 0);
            const deliveryScore = Number(row.getValue("deliveryScore") || 0);
            const selfEvaluationScore = Number(row.getValue("selfEvaluationScore") || 0);
            
            const total = processScore + priceScore + deliveryScore + selfEvaluationScore;
            
            return total > 0 ? (
              <span className="font-medium bg-blue-50 px-2 py-1 rounded">
                {total.toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 80,
        },

        {
          accessorKey: "participationBonus",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="참여도(가점)" />,
          cell: ({ row }) => {
            const score = row.getValue("participationBonus");
            return score ? (
              <span className="font-medium text-green-600">+{Number(score).toFixed(1)}</span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },

        {
          accessorKey: "qualityDeduction",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="품질(감점)" />,
          cell: ({ row }) => {
            const score = row.getValue("qualityDeduction");
            return score ? (
              <span className="font-medium text-red-600">-{Number(score).toFixed(1)}</span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 100,
        },

        // ✅ 새로운 평가점수 컬럼 추가
        {
          id: "evaluationScore",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가점수" />,
          cell: ({ row }) => {
            const processScore = Number(row.getValue("processScore") || 0);
            const priceScore = Number(row.getValue("priceScore") || 0);
            const deliveryScore = Number(row.getValue("deliveryScore") || 0);
            const selfEvaluationScore = Number(row.getValue("selfEvaluationScore") || 0);
            const participationBonus = Number(row.getValue("participationBonus") || 0);
            const qualityDeduction = Number(row.getValue("qualityDeduction") || 0);
            
            const totalScore = processScore + priceScore + deliveryScore + selfEvaluationScore;
            const evaluationScore = totalScore + participationBonus - qualityDeduction;
            
            return totalScore > 0 ? (
              <span className="font-bold text-blue-600 bg-blue-50 px-2 py-1 rounded">
                {evaluationScore.toFixed(1)}
              </span>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 90,
        },

        {
          accessorKey: "evaluationGrade",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가등급" />,
          cell: ({ row }) => {
            const grade = row.getValue<string>("evaluationGrade");
            return grade ? (
              <Badge variant={getGradeBadgeVariant(grade)}>{grade}</Badge>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          minSize: 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: "view" })}
              aria-label="상세보기"
              title="상세보기"
            >
              <Eye className="size-4" />
            </Button>

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