"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";

// DOLCE API ENM 필드가 제대로 번역되지 않아 직접 매핑
const DRAWING_USAGE_MAP: Record<string, { ko: string; en: string }> = {
  APP: { ko: "승인용", en: "Approval" },
  WOR: { ko: "작업용", en: "Working" },
  // 참조용은 eVCP에서 사용하지 않으나 추가해둠
  REF: { ko: "참조용", en: "Reference" },
  REC: { ko: "입수용", en: "GTT→SHI" },
  SUB: { ko: "제출용", en: "SHI→GTT" },
  CMT: { ko: "코멘트", en: "Comment" },
};

const REGISTER_KIND_MAP: Record<string, { ko: string; en: string }> = {
  APPR: { ko: "승인 제출용 도면(Full)", en: "For Approval(Full)" },
  APPP: { ko: "승인 제출용 도면(Partial)", en: "For Approval(Partial)" },
  WORK: { ko: "작업용 입수도면(Full)", en: "For Working(Full)" },
  WORP: { ko: "작업용 입수도면(Partial)", en: "For Working(Partial)" },
  RECW: { ko: "Working 도면입수(GTT→SHI)", en: "Working Dwg(GTT→SHI)" },
  RECP: { ko: "Pre. 도면입수(GTT→SHI)", en: "Pre. Dwg(GTT→SHI)" },
  GSUB: { ko: "SHI 입력 문서 (SHI→GTT)", en: "SHI Input Document(SHI→GTT)" },
  CMTQ: { ko: "Comment-TQ", en: "Comment-TQ" },
  CMTM: { ko: "MARK-UP", en: "MARK-UP" },
  // FMEA는 미사용 코드
  "FMEA-R1": { ko: "FMEA 1st Receipt", en: "FMEA 1st Receipt" },
  "FMEA-R2": { ko: "FMEA 2nd Receipt", en: "FMEA 2nd Receipt" },
  "FMEA-1": { ko: "FMEA 1st Submission", en: "FMEA 1st Submission" },
  "FMEA-2": { ko: "FMEA 2nd Submission", en: "FMEA 2nd Submission" },
  // 참조용 도면도 미사용 코드, 번역 받아야 적용 가능
  PREF: { ko: "본선용 참조도면", en: "본선용 참조도면" },
  RREF: { ko: "실적선 참조도면", en: "실적선 참조도면" },
  "PREP-P": { ko: "본선용 참조도면(Partial)", en: "본선용 참조도면(Partial)" },
  "RREP-P": { ko: "실적선 참조도면(Partial)", en: "실적선 참조도면(Partial)" },
};

// 카테고리는 API에서 ENM이 제공되는 것으로 가정 (필요시 추가)
const translateDrawingUsage = (code: string | null, lng: string): string => {
  if (!code) return "";
  const mapped = DRAWING_USAGE_MAP[code];
  if (!mapped) return code;
  return lng === "en" ? mapped.en : mapped.ko;
};

const translateRegisterKind = (code: string | null, lng: string): string => {
  if (!code) return "";
  const mapped = REGISTER_KIND_MAP[code];
  if (!mapped) return code;
  return lng === "en" ? mapped.en : mapped.ko;
};

// 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: 80,
      cell: ({ row }) => {
        return <div className="text-center">{row.getValue("RegisterSerialNo")}</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 }) => {
        const categoryENM = row.getValue("CategoryENM") as string;
        const categoryNM = row.original.CategoryNM;
        // 영어인 경우 ENM, 한국어인 경우 NM 사용
        return <div>{lng === "en" ? (categoryENM || categoryNM) : (categoryNM || 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: "RegisterKind",
      header: t("detailDrawing.columns.registerKind"),
      minSize: 180,
      cell: ({ row }) => {
        // API 응답의 RegisterKind는 코드값이므로 직접 매핑하여 번역
        const kindCode = row.getValue("RegisterKind") as string;
        const translated = translateRegisterKind(kindCode, lng);
        return <div>{translated}</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">
            <Button
              variant="ghost"
              size="sm"
              disabled={!isEditable || !onEdit}
              onClick={() => onEdit && onEdit(row.original)}
              title={!isEditable ? t("editDetailDialog.statusSubmittedOnly") : t("editDetailDialog.editButton")}
            >
              <Edit className="h-4 w-4" />
            </Button>
          </div>
        );
      },
    },
  ];
}
