'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,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { PenToolIcon, TrashIcon } from 'lucide-react';
import {
  REG_EVAL_CRITERIA_CATEGORY,
  REG_EVAL_CRITERIA_CATEGORY2,
  REG_EVAL_CRITERIA_ITEM,
  type RegEvalCriteriaView,
} from '@/db/schema';
import { type ColumnDef } from '@tanstack/react-table';
import { type DataTableRowAction } from '@/types/table';

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

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

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

/* FUNCTION FOR GETTING COLUMNS SETTING */
function getColumns({ setRowAction }: GetColumnsProps): ColumnDef<RegEvalCriteriaView>[] {
  
  // [1] SELECT COLUMN - CHECKBOX
  const selectColumn: ColumnDef<RegEvalCriteriaView> = {
    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<RegEvalCriteriaView>[] = [
    {
      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-regular">
          {row.getValue('range') || '-'}
        </div>
      ),
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Range',
        type: 'text',
      },
    },
    {
      accessorKey: 'detail',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="평가내용" />
      ),
      cell: ({ row }) => (
        <div className="font-bold">
          {row.getValue('detail')}
        </div>
      ),
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Detail',
        type: 'text',
      },
    },
  ];

  // [3] SCORE COLUMNS
  const scoreEquipColumns: ColumnDef<RegEvalCriteriaView>[] = [
    {
      accessorKey: 'scoreEquipShip',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="조선" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('scoreEquipShip');
        const displayValue = typeof value === 'string'
          ? parseFloat(parseFloat(value).toFixed(2)).toString()
          : '-';
        return (
          <div className="font-bold">
            {displayValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Equipment-Shipbuilding Score',
        group: 'Equipment Score',
        type: 'number',
      },
    },
    {
      accessorKey: 'scoreEquipMarine',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="해양" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('scoreEquipMarine');
        const displayValue = typeof value === 'string'
          ? parseFloat(parseFloat(value).toFixed(2)).toString()
          : '-';
        return (
          <div className="font-bold">
            {displayValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Equipment-Marine Engineering Score',
        group: 'Equipment Score',
        type: 'number',
      },
    },
  ];
  const scoreBulkColumns: ColumnDef<RegEvalCriteriaView>[] = [
    {
      accessorKey: 'scoreBulkShip',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="조선" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('scoreBulkShip');
        const displayValue = typeof value === 'string'
          ? parseFloat(parseFloat(value).toFixed(2)).toString()
          : '-';
        return (
          <div className="font-bold">
            {displayValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Bulk-Shipbuilding Score',
        group: 'Bulk Score',
        type: 'number',
      },
    },
    {
      accessorKey: 'scoreBulkMarine',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="해양" />
      ),
      cell: ({ row }) => {
        const value = row.getValue<string>('scoreBulkMarine');
        const displayValue = typeof value === 'string'
          ? parseFloat(parseFloat(value).toFixed(2)).toString()
          : '-';
        return (
          <div className="font-bold">
            {displayValue}
          </div>
        );
      },
      enableSorting: true,
      enableHiding: false,
      meta: {
        excelHeader: 'Bulk-Marine Engineering Score',
        group: 'Bulk Score',
        type: 'number',
      },
    },
  ];

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

  // [5] HIDDEN ID COLUMN
  const hiddenColumns: ColumnDef<RegEvalCriteriaView>[] = [
    {
      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: 'criteriaId',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="기준 ID" />
      ),
      cell: ({ row }) => (
        <div className="font-regular">
          {row.getValue('criteriaId')}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Criteria ID',
        group: 'Meta Data',
        type: 'criteriaId',
      },
    },
    {
      accessorKey: 'orderIndex',
      header: ({ column }) => (
        <DataTableColumnHeaderSimple column={column} title="정렬 순서" />
      ),
      cell: ({ row }) => (
        <div className="font-regular">
          {row.getValue('orderIndex')}
        </div>
      ),
      enableSorting: true,
      enableHiding: true,
      meta: {
        excelHeader: 'Order Index',
        group: 'Meta Data',
        type: 'number',
      },
    },
  ];

  // [6] ACTIONS COLUMN - DROPDOWN MENU
  const actionsColumn: ColumnDef<RegEvalCriteriaView> = {
    id: 'actions',
    header: '작업',
    enableHiding: false,
    cell: function Cell({ row }) {
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon">
              <PenToolIcon className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem
              onClick={() => setRowAction({ row, type: 'update' })}
            >
              <PenToolIcon className="mr-2 h-4 w-4" />
              Modify Criteria
            </DropdownMenuItem>
            <DropdownMenuItem
              onClick={() => setRowAction({ row, type: 'delete' })}
              className="text-destructive"
            >
              <TrashIcon className="mr-2 h-4 w-4" />
              Delete Criteria
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 80,
  };

  return [
    selectColumn,
    ...criteriaColumns,
    {
      id: 'score',
      header: '배점',
      columns: [
        {
          id: 'scoreEquip',
          header: '기자재',
          columns: scoreEquipColumns,
        },
        {
          id: 'scoreBulk',
          header: '벌크',
          columns: scoreBulkColumns,
        },
      ],
    },
    ...hiddenColumns,
    remarksColumn,
    actionsColumn,
  ];
};

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

/* EXPORT */
export default getColumns;