"use client";

import * as React from "react";
import { type ColumnDef } from "@tanstack/react-table";
import { format } from "date-fns";
import { ko } from "date-fns/locale";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuShortcut,
} from "@/components/ui/dropdown-menu";
import { MoreHorizontal, Eye, Edit, Trash2 } from "lucide-react";
import type { DataTableRowAction } from "@/types/table";
import { complianceSurveyTemplates } from "@/db/schema/compliance";
import { DataTableColumnHeaderSimple } from "@/components/data-table/data-table-column-simple-header";

interface GetColumnsProps {
  setRowAction: React.Dispatch<React.SetStateAction<DataTableRowAction<typeof complianceSurveyTemplates.$inferSelect> | null>>;
}

export function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<typeof complianceSurveyTemplates.$inferSelect>[] {
  // ----------------------------------------------------------------
  // 1) select 컬럼 (체크박스)
  // ----------------------------------------------------------------
  const selectColumn: ColumnDef<typeof complianceSurveyTemplates.$inferSelect> = {
    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"
      />
    ),
    size: 40,
    enableSorting: false,
    enableHiding: false,
  };

  // ----------------------------------------------------------------
  // 2) actions 컬럼 (Dropdown 메뉴)
  // ----------------------------------------------------------------
  const actionsColumn: ColumnDef<typeof complianceSurveyTemplates.$inferSelect> = {
    id: "actions",
    header: "작업",
    enableHiding: false,
    cell: ({ row }) => {
      const template = row.original;

      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" className="h-8 w-8 p-0">
              <span className="sr-only">메뉴 열기</span>
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => setRowAction({ type: 'update', row: row })}>
              <Edit className="mr-2 h-4 w-4" />
              Edit
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => setRowAction({ type: 'delete', row: row })}>
              <Trash2 className="mr-2 h-4 w-4" />
              Delete
              <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => window.location.href = `/evcp/compliance/${template.id}`}>
              <Eye className="mr-2 h-4 w-4" />
              Detail
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      );
    },
    size: 40,
  };

  // ----------------------------------------------------------------
  // 3) 일반 컬럼들 (정렬 가능)
  // ----------------------------------------------------------------
  const dataColumns: ColumnDef<typeof complianceSurveyTemplates.$inferSelect>[] = [
    {
      accessorKey: "name",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="템플릿명" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">{row.getValue("name")}</div>
      ),
      enableResizing: true,
    },
    {
      accessorKey: "description",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="설명" />
      ),
      cell: ({ row }) => (
        <div className="max-w-md truncate">{row.getValue("description")}</div>
      ),
      enableResizing: true,
    },
    {
      accessorKey: "version",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="버전" />
      ),
      cell: ({ row }) => (
        <Badge variant="secondary">{row.getValue("version")}</Badge>
      ),
      enableResizing: true,
    },
    {
      accessorKey: "isActive",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="상태" />
      ),
      cell: ({ row }) => {
        const isActive = row.getValue("isActive") as boolean;
        return (
          <Badge variant={isActive ? "default" : "secondary"}>
            {isActive ? "활성" : "비활성"}
          </Badge>
        );
      },
      enableResizing: true,
    },
    {
      accessorKey: "createdAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("createdAt") as Date;
        return date ? format(new Date(date), 'yyyy-MM-dd', { locale: ko }) : '-';
      },
      enableResizing: true,
    },
    {
      accessorKey: "updatedAt",
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="수정일" />
      ),
      cell: ({ row }) => {
        const date = row.getValue("updatedAt") as Date;
        return date ? format(new Date(date), 'yyyy-MM-dd', { locale: ko }) : '-';
      },
      enableResizing: true,
    },
  ];

  // ----------------------------------------------------------------
  // 4) 최종 컬럼 배열: select, dataColumns, actions
  // ----------------------------------------------------------------
  return [
    selectColumn,
    ...dataColumns,
    actionsColumn,
  ];
}
