'use client';

/* IMPORT */
import { DataTable } from '@/components/data-table/data-table';
import { DataTableAdvancedToolbar } from '@/components/data-table/data-table-advanced-toolbar';
import getColumns from './reg-eval-criteria-columns';
import { getRegEvalCriteria } from '../service';
import {
  REG_EVAL_CRITERIA_CATEGORY,
  REG_EVAL_CRITERIA_CATEGORY2,
  REG_EVAL_CRITERIA_ITEM,
  type RegEvalCriteriaView
} from '@/db/schema';
import RegEvalCriteriaCreateDialog from './reg-eval-criteria-create-dialog';
import RegEvalCriteriaDeleteDialog from './reg-eval-criteria-delete-dialog';
import RegEvalCriteriaUpdateSheet from './reg-eval-criteria-update-sheet';
import RegEvalCriteriaTableToolbarActions from './reg-eval-criteria-table-toolbar-actions';
import {
  type DataTableFilterField,
  type DataTableRowAction,
  type DataTableAdvancedFilterField,
} from '@/types/table';
import { useDataTable } from '@/hooks/use-data-table';
import { use, useCallback, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';

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

/* TYPES */
interface RegEvalCriteriaTableProps {
  promises: Promise<[
    Awaited<ReturnType<typeof getRegEvalCriteria>>,
  ]>,
}

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

/* TABLE COMPONENT */
function RegEvalCriteriaTable({ promises }: RegEvalCriteriaTableProps) {
  const router = useRouter();
  const [rowAction, setRowAction] = useState<DataTableRowAction<RegEvalCriteriaView> | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState<boolean>(false);
  const [promiseData] = use(promises);
  const tableData = promiseData;

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

  const filterFields: DataTableFilterField<RegEvalCriteriaView>[] = [
    {
      id: 'category',
      label: '평가부문',
      placeholder: '평가부문 선택...',
    },
    {
      id: 'category2',
      label: '점수구분',
      placeholder: '점수구분 선택...',
    },
    {
      id: 'item',
      label: '항목',
      placeholder: '항목 선택...',
    },
  ]
  const advancedFilterFields: DataTableAdvancedFilterField<RegEvalCriteriaView>[] = [
    {
      id: 'category',
      label: '평가부문',
      type: 'select',
      options: REG_EVAL_CRITERIA_CATEGORY,
    },
    {
      id: 'category2',
      label: '점수구분',
      type: 'select',
      options: REG_EVAL_CRITERIA_CATEGORY2,
    },
    {
      id: 'item',
      label: '항목',
      type: 'select',
      options: REG_EVAL_CRITERIA_ITEM,
    },
    { id: 'classification', label: '구분', type: 'text' },
    { id: 'range', label: '범위', type: 'text' },
    { id: 'detail', label: '평가내용', type: 'text' },
    { id: 'scoreEquipShip', label: '조선', type: 'number' },
    { id: 'scoreEquipMarine', label: '해양', type: 'number' },
    { id: 'scoreBulkShip', label: '조선', type: 'number' },
    { id: 'scoreBulkMarine', label: '해양', type: 'number' },
    { id: 'remarks', label: '비고', type: 'text' },
  ];

  // Data Table Setting
  const { table } = useDataTable({
    data: tableData.data,
    columns,
    pageCount: tableData.pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [
        { id: 'criteriaId', desc: false },
        { id: 'orderIndex', desc: false },
      ],
      columnPinning: { left: ['select'], right: ['actions'] },
      columnVisibility: {
        id: false,
        criteriaId: false,
        orderIndex: false,
      },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  });

  const emptyCriteriaViewData: RegEvalCriteriaView = {
    id: null,
    category: '',
    category2: '',
    item: '',
    classification: '',
    range: null,
    remarks: null,
    criteriaId: null,
    detail: '',
    orderIndex: null,
    scoreEquipShip: null,
    scoreEquipMarine: null,
    scoreBulkShip: null,
    scoreBulkMarine: null,
  };

  const refreshData = useCallback(() => {
    router.refresh();
  }, [router]);
  const handleCreateCriteria = () => {
    setIsCreateDialogOpen(true);
  };
  const handleCreateSuccess = useCallback(() => {
    setIsCreateDialogOpen(false);
    refreshData();
  }, [refreshData]);
  const handleModifySuccess = useCallback(() => {
    setRowAction(null);
    refreshData();
  }, [refreshData]);
  const handleDeleteSuccess = useCallback(() => {
    setRowAction(null);
    refreshData();
  }, [refreshData]);

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <RegEvalCriteriaTableToolbarActions
            table={table}
            onCreateCriteria={handleCreateCriteria}
            onRefresh={refreshData}
          />
        </DataTableAdvancedToolbar>
      </DataTable>
      <RegEvalCriteriaCreateDialog
        open={isCreateDialogOpen}
        onOpenChange={setIsCreateDialogOpen}
        onSuccess={handleCreateSuccess}
      />
      <RegEvalCriteriaUpdateSheet
        open={rowAction?.type === 'update'}
        onOpenChange={() => setRowAction(null)}
        criteriaViewData={rowAction?.row.original ?? emptyCriteriaViewData}
        onSuccess={handleModifySuccess}
      />
      <RegEvalCriteriaDeleteDialog
        open={rowAction?.type === 'delete'}
        onOpenChange={() => setRowAction(null)}
        criteriaViewData={rowAction?.row.original ?? emptyCriteriaViewData}
        onSuccess={handleDeleteSuccess}
      />
    </>
  )
}

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

/* EXPORT */
export default RegEvalCriteriaTable;
