'use client';

/* IMPORT */
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { DataTableColumnHeaderSimple } from '@/components/data-table/data-table-column-simple-header';
import { Dispatch, SetStateAction } from 'react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuShortcut,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Ellipsis, Eye, Edit, Trash2 } from 'lucide-react';
import {
  REG_EVAL_CRITERIA_CATEGORY,
  REG_EVAL_CRITERIA_CATEGORY2,
  REG_EVAL_CRITERIA_ITEM,
  type RegEvalCriteria, // RegEvalCriteriaView 대신 RegEvalCriteria 사용
} from '@/db/schema';
import { type ColumnDef } from '@tanstack/react-table';
import { type DataTableRowAction } from '@/types/table';

// ----------------------------------------------------------------------------------------------------

/* TYPES */
interface GetColumnsProps {
  setRowAction: Dispatch<SetStateAction<DataTableRowAction<RegEvalCriteria> | null>>,
};

// ----------------------------------------------------------------------------------------------------

/* FUNCTION FOR GETTING COLUMNS SETTING */
function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<RegEvalCriteria>[] {
  
  // [1] SELECT COLUMN - CHECKBOX
  const selectColumn: ColumnDef<RegEvalCriteria> = {
    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"
      />
    ),
    enableSorting: false,
    enableHiding: false,
    size: 40,
  };

  // [2] CRITERIA COLUMNS
  const criteriaColumns: ColumnDef<RegEvalCriteria>[] = [
    {
      accessorKey: 'category',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="평가부문" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('category');
        const label = REG_EVAL_CRITERIA_CATEGORY.find(item => item.value === value)?.label ?? value;
        return (
          <Badge variant="default">
            {label}
          </Badge>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Category',
        type: 'select',
      },
    },
    {
      accessorKey: 'category2',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="점수구분" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('category2');
        const label = REG_EVAL_CRITERIA_CATEGORY2.find(item => item.value === value)?.label ?? value;
        return (
          <Badge variant="secondary">
            {label}
          </Badge>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Score Category',
        type: 'select',
      },
    },
    {
      accessorKey: 'item',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="항목" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('item');
        const label = REG_EVAL_CRITERIA_ITEM.find(item => item.value === value)?.label ?? value;
        return (
          <Badge variant="outline">
            {label}
          </Badge>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Item',
        type: 'select',
      },
    },
    {
      accessorKey: 'classification',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="구분" />
      ),
      cell: ({ row }) => (
        <div className="font-regular">
          {row.getValue('classification')}
        </div>
      ),
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Classification',
        type: 'text',
      },
    },
    {
      accessorKey: 'range',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="평가명" />
      ),
      cell: ({ row }) => (
        <div className="font-medium">
          {row.getValue('range') || '-'}
        </div>
      ),
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Evaluation Name',
        type: 'text',
      },
    },
    {
      accessorKey: 'scoreType',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="점수유형" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('scoreType');
        return (
          <Badge variant={value === 'fixed' ? 'default' : 'secondary'}>
            {value === 'fixed' ? '고정점수' : '변동점수'}
          </Badge>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Score Type',
        type: 'select',
      },
    },
  ];

  // [3] VARIABLE SCORE COLUMNS (변동점수 관련 컬럼들)
  const variableScoreColumns: ColumnDef<RegEvalCriteria>[] = [
    {
      accessorKey: 'variableScoreMin',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="최소점수" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('variableScoreMin');
        const scoreType = row.getValue<string>('scoreType');
        if (scoreType !== 'variable') return <div className="text-gray-400">-</div>;
        
        const displayValue = typeof value === 'string'
          ? parseFloat(parseFloat(value).toFixed(2)).toString()
          : '-';
        return (
          <div className="font-regular text-center">
            {displayValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Min Score',
        type: 'number',
      },
    },
    {
      accessorKey: 'variableScoreMax',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="최대점수" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('variableScoreMax');
        const scoreType = row.getValue<string>('scoreType');
        if (scoreType !== 'variable') return <div className="text-gray-400">-</div>;
        
        const displayValue = typeof value === 'string'
          ? parseFloat(parseFloat(value).toFixed(2)).toString()
          : '-';
        return (
          <div className="font-regular text-center">
            {displayValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Max Score',
        type: 'number',
      },
    },
    {
      accessorKey: 'variableScoreUnit',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="점수단위" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('variableScoreUnit');
        const scoreType = row.getValue<string>('scoreType');
        if (scoreType !== 'variable') return <div className="text-gray-400">-</div>;
        
        return (
          <div className="font-regular text-center">
            {value || '-'}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Score Unit',
        type: 'text',
      },
    },
  ];

  // [4] REMARKS COLUMN
  const remarksColumn: ColumnDef<RegEvalCriteria> = {
    accessorKey: 'remarks',
    header: ({ column }) => (
      <DataTableColumnHeaderSimple column={column} title="비고" />
    ),
    cell: ({ row }) => (
      <div className="font-regular max-w-[150px] truncate" title={row.getValue('remarks')}>
        {row.getValue('remarks') || '-'}
      </div>
    ),
    enableSorting: true,
    enableHiding: false,
    meta: {
      excelHeader: 'Remarks',
      type: 'text',
    },
  };

  // [5] HIDDEN ID COLUMNS
  const hiddenColumns: ColumnDef<RegEvalCriteria>[] = [
    {
      accessorKey: 'id',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="ID" />
      ),
      cell: ({ row }) => (
        <div className="font-regular">
          {row.getValue('id')}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'ID',
        group: 'Meta Data',
        type: 'number',
      },
    },
    {
      accessorKey: 'createdAt',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="생성일시" />
      ),
      cell: ({ row }) => {
        const date = row.getValue<Date>('createdAt');
        return (
          <div className="font-regular">
            {date ? new Date(date).toLocaleDateString('ko-KR') : '-'}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Created At',
        group: 'Meta Data',
        type: 'date',
      },
    },
    {
      accessorKey: 'updatedAt',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="수정일시" />
      ),
      cell: ({ row }) => {
        const date = row.getValue<Date>('updatedAt');
        return (
          <div className="font-regular">
            {date ? new Date(date).toLocaleDateString('ko-KR') : '-'}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Updated At',
        group: 'Meta Data',
        type: 'date',
      },
    },
  ];

  // [6] ACTIONS COLUMN - DROPDOWN MENU WITH VIEW ACTION
  const actionsColumn: ColumnDef<RegEvalCriteria> = {
    id: 'actions',
    enableHiding: false,
    cell: function Cell({ row }) {
      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={() => setRowAction({ row, type: "view" })}
            >
              <Eye className="mr-2 size-4" />
              상세보기
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "update" })}
            >
              <Edit className="mr-2 size-4" />
              수정하기
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              onSelect={() => setRowAction({ row, type: "delete" })}
            >
              <Trash2 className="mr-2 size-4" />
              삭제하기
              <DropdownMenuShortcut>⌘⌫</DropdownMenuShortcut>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 80,
  };

  return [
    selectColumn,
    ...criteriaColumns,
    ...variableScoreColumns,
    remarksColumn,
    ...hiddenColumns,
    actionsColumn,
  ];
};

// ----------------------------------------------------------------------------------------------------

/* EXPORT */
export default getColumns;