"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,
  DataTableRowAction,
} from '@/types/table';

import { getColumns } from './approval-template-table-columns';
import { getApprovalTemplateList } from '../service';
import { type ApprovalTemplate } from '../service';
import { ApprovalTemplateTableToolbarActions } from './approval-template-table-toolbar-actions';
import { CreateApprovalTemplateSheet } from './create-approval-template-sheet';
import { UpdateApprovalTemplateSheet } from './update-approval-template-sheet';
import { DuplicateApprovalTemplateSheet } from './duplicate-approval-template-sheet';
import { DeleteApprovalTemplateDialog } from './delete-approval-template-dialog';

interface ApprovalTemplateTableProps {
  promises: Promise<[
    Awaited<ReturnType<typeof getApprovalTemplateList>>,
  ]>;
}

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

  const [rowAction, setRowAction] = 
    React.useState<DataTableRowAction<ApprovalTemplate> | null>(null);

  const [showCreateSheet, setShowCreateSheet] = React.useState(false);

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

  // 기본 & 고급 필터 필드 (추후 확장 가능)
  const filterFields: DataTableFilterField<ApprovalTemplate>[] = [];
  const advancedFilterFields: DataTableAdvancedFilterField<ApprovalTemplate>[] = [
    {
      id: 'name',
      label: '템플릿 이름',
      type: 'text',
    },
    {
      id: 'subject',
      label: '제목',
      type: 'text',
    },
    {
      id: 'category',
      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: 'updatedAt', desc: true }],
      columnPinning: { right: ['actions'] },
    },
    getRowId: (row) => String(row.id),
    shallow: false,
    clearOnDefault: true,
  });

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <ApprovalTemplateTableToolbarActions
            table={table}
            onCreateTemplate={() => setShowCreateSheet(true)}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 새 템플릿 생성 Sheet */}
      <CreateApprovalTemplateSheet
        open={showCreateSheet}
        onOpenChange={setShowCreateSheet}
      />

      {/* 템플릿 수정 Sheet */}
      <UpdateApprovalTemplateSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        template={rowAction?.type === "update" ? rowAction.row.original : null}
      />

      {/* 템플릿 복제 Sheet */}
      <DuplicateApprovalTemplateSheet
        open={rowAction?.type === "duplicate"}
        onOpenChange={() => setRowAction(null)}
        template={rowAction?.type === "duplicate" ? rowAction.row.original : null}
      />

      {/* 템플릿 삭제 Dialog */}
      <DeleteApprovalTemplateDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        templates={rowAction?.type === "delete" ? [rowAction.row.original] : []}
        showTrigger={false}
        onSuccess={() => {
          setRowAction(null)
          // 테이블 새로고침은 server action에서 자동으로 처리됨
        }}
      />
    </>
  );
} 