"use client"

import * as React from "react"
import { type DataTableRowAction } from "@/types/table"
import { type ColumnDef } from "@tanstack/react-table"
import { Download, Ellipsis, Paperclip, CheckCircle, XCircle, Eye } from "lucide-react"
import { toast } from "sonner"

import { getErrorMessage } from "@/lib/handle-error"
import { formatDate, formatDateTime } from "@/lib/utils"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Checkbox } from "@/components/ui/checkbox"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"

import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header"
import { scopeHelpers } from "@/config/basicContractColumnsConfig"
import { BasicContractTemplate } from "@/db/schema"
import { quickDownload } from "@/lib/file-download"
import { useRouter } from "next/navigation"

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<BasicContractTemplate> | null>>
  router: ReturnType<typeof useRouter>
}

/**
 * 파일 다운로드 함수 (공용 유틸리티 사용)
 */
const handleFileDownload = async (filePath: string, fileName: string) => {
  try {
    await quickDownload(filePath, fileName);
  } catch (error) {
    console.error("파일 다운로드 오류:", error);
    toast.error("파일 다운로드 중 오류가 발생했습니다.");
  }
};

/**
 * tanstack table 컬럼 정의 (중첩 헤더 버전)
 */
export function getColumns({ setRowAction, router }: GetColumnsProps): ColumnDef<BasicContractTemplate>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<BasicContractTemplate> = {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
        aria-label="Select all"
        className="translate-y-0.5"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
        className="translate-y-0.5"
      />
    ),
    maxSize: 30,
    enableSorting: false,
    enableHiding: false,
  }

  // ----------------------------------------------------------------
  // 2) 파일 다운로드 컬럼 (아이콘)
  // ----------------------------------------------------------------
  const downloadColumn: ColumnDef<BasicContractTemplate> = {
    id: "download",
    header: "",
    cell: ({ row }) => {
      const template = row.original;

      return (
        <Button
          variant="ghost"
          size="icon"
          onClick={() => handleFileDownload(template.filePath, template.fileName)}
          title={`${template.fileName} 다운로드`}
          className="hover:bg-muted"
        >
          <Paperclip className="h-4 w-4" />
          <span className="sr-only">다운로드</span>
        </Button>
      );
    },
    maxSize: 30,
    enableSorting: false,
  }

  // ----------------------------------------------------------------
  // 3) actions 컬럼 (Dropdown 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<BasicContractTemplate> = {
    id: "actions",
    enableHiding: false,
    cell: function Cell({ row }) {
      const [isUpdatePending, startUpdateTransition] = React.useTransition()
      const template = row.original;

      const handleViewDetails = () => {
        router.push(`/evcp/basic-contract-template/${template.id}`);
      };

      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              aria-label="Open menu"
              variant="ghost"
              className="flex size-8 p-0 data-[state=open]:bg-muted"
            >
              <Ellipsis className="size-4" aria-hidden="true" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end" className="w-40">
            <DropdownMenuItem onSelect={handleViewDetails}>
              <Eye className="mr-2 h-4 w-4" />
              View Details
            </DropdownMenuItem>
            
            <DropdownMenuSeparator />
            
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "update" })}
            >
              Edit
            </DropdownMenuItem>

            {template.status === 'ACTIVE' && (
              <DropdownMenuItem
                onSelect={() => setRowAction({ row, type: "dispose" })}
              >
                Dispose
              </DropdownMenuItem>
            )}

            {template.status === 'DISPOSED' && template.disposedAt && (
              <DropdownMenuItem
                onSelect={() => setRowAction({ row, type: "restore" })}
              >
                Restore
              </DropdownMenuItem>
            )}

            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "delete" })}
            >
              Delete
              <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    maxSize: 30,
  }

  // ----------------------------------------------------------------
  // 4) 직접 컬럼 정의 (그룹별로 중첩)
  // ----------------------------------------------------------------

  // 기본 정보 그룹
  const basicInfoColumns: ColumnDef<BasicContractTemplate>[] = [
    {
      accessorKey: "status",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="상태" />,
      cell: ({ row }) => {
        const status = row.getValue("status") as string;
        const isActive = status === "ACTIVE";
        return (
          <Badge variant={isActive ? "default" : "secondary"}>
            {isActive ? "활성" : "폐기"}
          </Badge>
        );
      },
      size: 80,
      enableResizing: true,
    },

    {
      accessorKey: "templateName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="계약문서명" />,
      cell: ({ row }) => {
        const template = row.original;
        
        const handleClick = () => {
          router.push(`/evcp/basic-contract-template/${template.id}`);
        };

        return (
          <div className="flex flex-col min-w-0">
            <button
              onClick={handleClick}
              className="truncate text-left hover:text-blue-600 hover:underline cursor-pointer transition-colors"
              title="클릭하여 상세보기"
            >
              {template.templateName}
            </button>
          </div>
        );
      },
      size: 250,
      enableResizing: true,
    },
    {
      accessorKey: "revision",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Rev." />,
      cell: ({ row }) => {
        const template = row.original;
        return (
            <span className="text-xs text-muted-foreground">v{template.revision}</span>
        );
      },
      size: 60,
      enableResizing: true,
    },
    {
      accessorKey: "legalReviewRequired",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="법무검토" />,
      cell: ({ row }) => {
        const required = row.getValue("legalReviewRequired") as boolean;
        return (
          <Badge variant={required ? "destructive" : "secondary"}>
            {required ? "필요" : "불필요"}
          </Badge>
        );
      },
      size: 100,
      enableResizing: true,
    },
  ];

  // 적용 범위 그룹
  const scopeColumns: ColumnDef<BasicContractTemplate>[] = [
    {
      accessorKey: "shipBuildingApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="조선해양" />,
      cell: ({ row }) => {
        const applicable = row.getValue("shipBuildingApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 80,
      enableResizing: true,
    },
    {
      accessorKey: "windApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="풍력" />,
      cell: ({ row }) => {
        const applicable = row.getValue("windApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 60,
      enableResizing: true,
    },
    {
      accessorKey: "pcApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="PC" />,
      cell: ({ row }) => {
        const applicable = row.getValue("pcApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 50,
      enableResizing: true,
    },
    {
      accessorKey: "nbApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="NB" />,
      cell: ({ row }) => {
        const applicable = row.getValue("nbApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 50,
      enableResizing: true,
    },
    {
      accessorKey: "rcApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="RC" />,
      cell: ({ row }) => {
        const applicable = row.getValue("rcApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 50,
      enableResizing: true,
    },
    {
      accessorKey: "gyApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="GY" />,
      cell: ({ row }) => {
        const applicable = row.getValue("gyApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 50,
      enableResizing: true,
    },
    {
      accessorKey: "sysApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="S&Sys" />,
      cell: ({ row }) => {
        const applicable = row.getValue("sysApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 60,
      enableResizing: true,
    },
    {
      accessorKey: "infraApplicable",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="Infra" />,
      cell: ({ row }) => {
        const applicable = row.getValue("infraApplicable") as boolean;
        return (
          <div className="flex justify-center">
            {applicable ? (
              <CheckCircle className="h-4 w-4 text-green-500" />
            ) : (
              <XCircle className="h-4 w-4 text-gray-300" />
            )}
          </div>
        );
      },
      size: 60,
      enableResizing: true,
    },
  ];

  // 파일 정보 그룹
  const fileInfoColumns: ColumnDef<BasicContractTemplate>[] = [
    {
      accessorKey: "fileName",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="파일명" />,
      cell: ({ row }) => {
        const fileName = row.getValue("fileName") as string;
        return (
          <div className="min-w-0 max-w-full">
            <span className="block truncate" title={fileName}>
              {fileName}
            </span>
          </div>
        );
      },
      size: 200,
      enableResizing: true,
    },
  ];

  // 감사 정보 그룹
  const auditColumns: ColumnDef<BasicContractTemplate>[] = [
    {
      accessorKey: "createdAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="생성일" />,
      cell: ({ row }) => {
        const date = row.getValue("createdAt") as Date;
        return date ? formatDateTime(date, "KR") : "-";
      },
      size: 120,
      enableResizing: true,
    },
    {
      accessorKey: "updatedAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="수정일" />,
      cell: ({ row }) => {
        const date = row.getValue("updatedAt") as Date;
        return date ? formatDateTime(date, "KR") : "-";
      },
      size: 120,
      enableResizing: true,
    },
    {
      accessorKey: "disposedAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="폐기일" />,
      cell: ({ row }) => {
        const date = row.getValue("disposedAt") as Date;
        return date ? formatDateTime(date, "KR") : "-";
      },
      size: 120,
      enableResizing: true,
    },
    {
      accessorKey: "restoredAt",
      header: ({ column }) => <DataTableColumnHeaderSimple column={column} title="복구일" />,
      cell: ({ row }) => {
        const date = row.getValue("restoredAt") as Date;
        return date ? formatDateTime(date, "KR") : "-";
      },
      size: 120,
      enableResizing: true,
    },
  ];

  // 중첩 컬럼 그룹 생성
  const nestedColumns: ColumnDef<BasicContractTemplate>[] = [
    {
      id: "기본 정보",
      header: "기본 정보",
      columns: basicInfoColumns,
    },
    {
      id: "적용 범위",
      header: "적용 범위",
      columns: scopeColumns,
    },
    {
      id: "파일 정보",
      header: "파일 정보",
      columns: fileInfoColumns,
    },
    {
      id: "감사 정보",
      header: "감사 정보",
      columns: auditColumns,
    },
  ]

  // ----------------------------------------------------------------
  // 5) 최종 컬럼 배열: select, download, nestedColumns, actions
  // ----------------------------------------------------------------
  return [
    selectColumn,
    downloadColumn,
    ...nestedColumns,
    actionsColumn,
  ]
}