"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, Check, X } from "lucide-react";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";
import { EvaluationTargetWithDepartments } from "@/db/schema";
import type { DataTableRowAction } from "@/types/table";
import { formatDate } from "@/lib/utils";

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 getStatusText = (status: string) => {
  const statusMap = {
    PENDING: "검토 중",
    CONFIRMED: "확정",
    EXCLUDED: "제외"
  };
  return statusMap[status] || status;
};

const getConsensusBadge = (consensusStatus: boolean | null) => {
  if (consensusStatus === null) {
    return <Badge variant="outline">검토 중</Badge>;
  }
  if (consensusStatus === true) {
    return <Badge variant="success">의견 일치</Badge>;
  }
  return <Badge variant="destructive">의견 불일치</Badge>;
};

const getDivisionBadge = (division: string) => {
  return (
    <Badge variant={division === "OCEAN" ? "default" : "secondary"}>
      {division === "OCEAN" ? "해양" : "조선"}
    </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 getEvaluationTargetBadge = (isTarget: boolean | null) => {
  if (isTarget === null) {
    return <Badge variant="outline">미정</Badge>;
  }
  return isTarget ? (
    <Badge variant="default" className="bg-blue-600">
      <Check className="size-3 mr-1" />
      평가 대상
    </Badge>
  ) : (
    <Badge variant="secondary">
      <X className="size-3 mr-1" />
      평가 제외
    </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");
        return (
          <Badge variant={getStatusBadgeVariant(status)}>
            {getStatusText(status)}
          </Badge>
        );
      },
      size: 100,
    },
    {
      accessorKey: "consensusStatus",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="의견 일치" />,
      cell: ({ row }) => getConsensusBadge(row.getValue("consensusStatus")),
      size: 100,
    },

    // ✅ 벤더 정보 그룹
    {
      id: "vendorInfo",
      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,
        },
      ]
    },

    // ✅ 발주 담당자
    {
      id: "orderReviewer",
      header: "발주 담당자",
      columns: [
        {
          accessorKey: "orderReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자명" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("orderReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[120px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "orderIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가 대상" />,
          cell: ({ row }) => {
            const isApproved = row.getValue<boolean>("orderIsApproved");
            return getEvaluationTargetBadge(isApproved);
          },
          size: 120,
        },
      ]
    },

    // ✅ 조달 담당자
    {
      id: "procurementReviewer",
      header: "조달 담당자",
      columns: [
        {
          accessorKey: "procurementReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자명" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("procurementReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[120px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "procurementIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가 대상" />,
          cell: ({ row }) => {
            const isApproved = row.getValue<boolean>("procurementIsApproved");
            return getEvaluationTargetBadge(isApproved);
          },
          size: 120,
        },
      ]
    },

    // ✅ 품질 담당자
    {
      id: "qualityReviewer",
      header: "품질 담당자",
      columns: [
        {
          accessorKey: "qualityReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자명" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("qualityReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[120px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "qualityIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가 대상" />,
          cell: ({ row }) => {
            const isApproved = row.getValue<boolean>("qualityIsApproved");
            return getEvaluationTargetBadge(isApproved);
          },
          size: 120,
        },
      ]
    },

    // ✅ 설계 담당자
    {
      id: "designReviewer",
      header: "설계 담당자",
      columns: [
        {
          accessorKey: "designReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자명" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("designReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[120px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "designIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가 대상" />,
          cell: ({ row }) => {
            const isApproved = row.getValue<boolean>("designIsApproved");
            return getEvaluationTargetBadge(isApproved);
          },
          size: 120,
        },
      ]
    },

    // ✅ CS 담당자
    {
      id: "csReviewer",
      header: "CS 담당자",
      columns: [
        {
          accessorKey: "csReviewerName",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="담당자명" />,
          cell: ({ row }) => {
            const reviewerName = row.getValue<string>("csReviewerName");
            return reviewerName ? (
              <div className="truncate max-w-[120px]" title={reviewerName}>
                {reviewerName}
              </div>
            ) : (
              <span className="text-muted-foreground">-</span>
            );
          },
          size: 120,
        },
        {
          accessorKey: "csIsApproved",
          header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="평가 대상" />,
          cell: ({ row }) => {
            const isApproved = row.getValue<boolean>("csIsApproved");
            return getEvaluationTargetBadge(isApproved);
          },
          size: 120,
        },
      ]
    },

    // ✅ 의견 및 결과
    {
      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 <span className="text-sm">{ confirmedAt ? formatDate(confirmedAt, "KR") :'-'}</span>;
      },
      size: 100,
    },
    {
      accessorKey: "createdAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="생성일" />,
      cell: ({ row }) => {
        const createdAt = row.getValue<Date>("createdAt");
        return <span className="text-sm">{formatDate(createdAt, "KR")}</span>;
      },
      size: 100,
    },

    // ✅ Actions - 가장 안전하게 처리
    {
      id: "actions",
      enableHiding: false,
      size: 40,
      minSize: 40,
      cell: ({ row }) => {
        // ✅ 함수를 직접 정의해서 매번 새로 생성되지 않도록 처리
        const handleEdit = () => {
          setRowAction({ row, type: "update" });
        };

        return (
          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="icon"
              className="size-8"
              onClick={handleEdit}
              aria-label="수정"
              title="수정"
            >
              <Pencil className="size-4" />
            </Button>
          </div>
        );
      },
    },
  ];
}