"use client";

import * as React from 'react';
import { useDataTable } from '@/hooks/use-data-table';
import { DataTable } from '@/components/data-table/data-table';
import { DataTableAdvancedToolbar } from '@/components/data-table/data-table-advanced-toolbar';
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
} from '@/types/table';

import { getColumns } from './approval-log-table-column';
import { getApprovalLogList } from '../service';
import { type ApprovalLog } from '../service';

interface ApprovalLogTableProps {
  promises: Promise<[
    Awaited<ReturnType<typeof getApprovalLogList>>,
  ]>;
}

type ApprovalLogRowAction = {
  type: "view";
  row: { original: ApprovalLog };
} | null;

export function ApprovalLogTable({ promises }: ApprovalLogTableProps) {
  const [{ data, pageCount }] = React.use(promises);

  const setRowAction = React.useState<ApprovalLogRowAction>(null)[1];

  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  );

  // 기본 & 고급 필터 필드
  const filterFields: DataTableFilterField<ApprovalLog>[] = [];
  const advancedFilterFields: DataTableAdvancedFilterField<ApprovalLog>[] = [
    {
      id: 'subject',
      label: '결재 제목',
      type: 'text',
    },
    {
      id: 'status',
      label: '상태',
      type: 'text',
    },
    {
      id: 'userId',
      label: '사용자 ID',
      type: 'text',
    },
    {
      id: 'emailAddress',
      label: '이메일',
      type: 'text',
    },
    {
      id: 'urgYn',
      label: '긴급여부',
      type: 'text',
    },
    {
      id: 'docSecuType',
      label: '보안등급',
      type: 'text',
    },
    {
      id: 'createdAt',
      label: '생성일',
      type: 'date',
    },
    {
      id: 'updatedAt',
      label: '수정일',
      type: 'date',
    },
  ];

  const { table } = useDataTable({
    data,
    columns,
    pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: 'createdAt', desc: true }],
      columnPinning: { right: ['actions'] },
    },
    getRowId: (row) => row.apInfId,
    shallow: false,
    clearOnDefault: true,
  });

  return (
    <DataTable table={table}>
      <DataTableAdvancedToolbar
        table={table}
        filterFields={advancedFilterFields}
        shallow={false}
      />
    </DataTable>
  );
}
