'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 RegEvalCriteria // RegEvalCriteriaView 대신 RegEvalCriteria 사용
} 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 RegEvalCriteriaDetailsSheet from './reg-eval-criteria-details-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<RegEvalCriteria> | null>(null);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState<boolean>(false);
  const [promiseData] = use(promises);
  const tableData = promiseData;

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

  const filterFields: DataTableFilterField<RegEvalCriteria>[] = [
    {
      id: 'category',
      label: '평가부문',
      placeholder: '평가부문 선택...',
    },
    {
      id: 'category2',
      label: '점수구분',
      placeholder: '점수구분 선택...',
    },
    {
      id: 'item',
      label: '항목',
      placeholder: '항목 선택...',
    },
  ]
  const advancedFilterFields: DataTableAdvancedFilterField<RegEvalCriteria>[] = [
    {
      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: 'scoreType', label: '점수유형', type: 'select', 
      options: [
        { label: '고정점수', value: 'fixed' },
        { label: '변동점수', value: 'variable' }
      ] 
    },
    { 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: 'id', desc: false },
      ],
      columnPinning: { left: ['select'], right: ['actions'] },
      columnVisibility: {
        id: false,
        createdAt: false,
        updatedAt: false,
        createdBy: false,
        updatedBy: false,
        variableScoreMin: false,
        variableScoreMax: false,
        variableScoreUnit: false,
      },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  });

  const emptyCriteriaData: RegEvalCriteria = {
    id: 0,
    category: '',
    category2: '',
    item: '',
    classification: '',
    range: null,
    remarks: null,
    scoreType: 'fixed',
    variableScoreMin: null,
    variableScoreMax: null,
    variableScoreUnit: null,
    createdAt: new Date(),
    updatedAt: new Date(),
    createdBy: 0,
    updatedBy: 0,
  };

  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]);

  // 상세보기 핸들러 추가
  const handleDetailsClose = useCallback(() => {
    setRowAction(null);
  }, []);

  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}
      />
      
      {/* 상세보기 시트 - 새로 추가 */}
      <RegEvalCriteriaDetailsSheet
        open={rowAction?.type === 'view'}
        onOpenChange={handleDetailsClose}
        criteriaViewData={rowAction?.row.original ?? emptyCriteriaData}
      />
      
      {/* 수정 시트 */}
      <RegEvalCriteriaUpdateSheet
        open={rowAction?.type === 'update'}
        onOpenChange={() => setRowAction(null)}
        criteriaData={rowAction?.row.original ?? emptyCriteriaData}
        onSuccess={handleModifySuccess}
      />
      
      {/* 삭제 다이얼로그 */}
      <RegEvalCriteriaDeleteDialog
        open={rowAction?.type === 'delete'}
        onOpenChange={() => setRowAction(null)}
        criteriaViewData={rowAction?.row.original ?? emptyCriteriaData}
        onSuccess={handleDeleteSuccess}
      />
    </>
  )
}

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

/* EXPORT */
export default RegEvalCriteriaTable;