"use client";

import { ColumnDef } from "@tanstack/react-table";
import { DetailDwgReceiptItem } from "../actions";
import { formatDolceDateTime } from "../utils/date-formatter";
import { useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Edit } from "lucide-react";

// Comment Dialog Component
function CommentDialog({ comment }: { comment: string }) {
  const [open, setOpen] = useState(false);

  return (
    <>
      <Button
        variant="ghost"
        className="h-auto py-1 px-2 text-left justify-start font-normal hover:bg-accent"
        onClick={() => setOpen(true)}
      >
        <div className="truncate max-w-[200px]">{comment || "-"}</div>
      </Button>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle>Comment</DialogTitle>
          </DialogHeader>
          <div className="max-h-96 overflow-y-auto">
            <p className="whitespace-pre-wrap text-sm">{comment || "코멘트가 없습니다."}</p>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
}

// 다국어 지원 컬럼 생성 함수
export function createDetailDrawingColumns(
  lng: string,
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  t: any,
  onEdit?: (detailDrawing: DetailDwgReceiptItem) => void
): ColumnDef<DetailDwgReceiptItem>[] {
  return [
    {
      accessorKey: "RegisterSerialNo",
      header: t("detailDrawing.columns.serialNo"),
      minSize: 120,
      cell: ({ row }) => {
        const val = row.getValue("RegisterSerialNo") as number;
        const status = row.getValue("Status") as string;
        if (val === 0 || status === "EVCP Saved") {
            return <div className="text-center">-</div>;
        }
        return <div className="text-center">{val}</div>;
      },
    },
    {
      accessorKey: "DrawingRevNo",
      header: t("detailDrawing.columns.revNo"),
      minSize: 100,
      cell: ({ row }) => {
        return <div className="font-medium">{row.getValue("DrawingRevNo")}</div>;
      },
    },
    {
      accessorKey: "Status",
      header: t("detailDrawing.columns.status"),
      minSize: 120,
      cell: ({ row }) => {
        return <div className="text-center">{row.getValue("Status")}</div>;
      },
    },
    {
      accessorKey: "CategoryENM",
      header: t("detailDrawing.columns.category"),
      minSize: 120,
      cell: ({ row }) => {
        // 항상 CategoryENM 필드를 보여줌
        return <div>{row.getValue("CategoryENM")}</div>;
      },
    },
    // RegisterKind 로 DrawingUsage를 알 수 있으므로 주석 처리
    // {
    //   accessorKey: "DrawingUsage",
    //   header: t("detailDrawing.columns.drawingUsage"),
    //   minSize: 100,
    //   cell: ({ row }) => {
    //     // API 응답의 DrawingUsage는 코드값이므로 직접 매핑하여 번역
    //     const usageCode = row.getValue("DrawingUsage") as string;
    //     const translated = translateDrawingUsage(usageCode, lng);
    //     return <div>{translated}</div>;
    //   },
    // },
    {
      accessorKey: "RegisterKindENM",
      header: t("detailDrawing.columns.registerKind"),
      minSize: 180,
      cell: ({ row }) => {
        // 항상 RegisterKindENM 필드를 보여줌
        return <div>{row.getValue("RegisterKindENM")}</div>;
      },
    },
    {
      accessorKey: "CreateUserNM",
      header: t("detailDrawing.columns.createdBy"),
      minSize: 150,
      cell: ({ row }) => {
        const userENM = row.original.CreateUserENM;
        const userNM = row.getValue("CreateUserNM") as string;
        return <div>{lng === "en" ? (userENM || userNM) : (userNM || userENM)}</div>;
      },
    },
    {
      accessorKey: "CreateDt",
      header: t("detailDrawing.columns.createdAt"),
      minSize: 200,
      cell: ({ row }) => {
        const date = row.getValue("CreateDt") as string;
        return <div className="text-sm text-muted-foreground">{formatDolceDateTime(date)}</div>;
      },
    },
    {
      accessorKey: "RegisterDesc",
      header: "Comment",
      minSize: 200,
      maxSize: 200,
      cell: ({ row }) => {
        const comment = row.getValue("RegisterDesc") as string;
        return <CommentDialog comment={comment} />;
      },
    },
    {
      id: "actions",
      header: t("detailDrawing.columns.actions"),
      minSize: 100,
      maxSize: 100,
      cell: ({ row }) => {
        const status = row.getValue("Status") as string;
        const isEditable = status === "Submitted";
        
        return (
          <div
            className="flex items-center justify-center"
            onClick={(e) => e.stopPropagation()}
          >
            <Button
              variant="ghost"
              size="sm"
              disabled={!isEditable || !onEdit}
              onClick={(e) => {
                e.stopPropagation();
                if (onEdit) onEdit(row.original);
              }}
              title={!isEditable ? t("editDetailDialog.statusSubmittedOnly") : t("editDetailDialog.editButton")}
            >
              <Edit className="h-4 w-4" />
            </Button>
          </div>
        );
      },
    },
  ];
}
