"use client";

import * as React from "react";
import { useQueryState } from "nuqs";
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,
  DataTableRowAction,
  DataTableFilterField,
  Filter,
} from "@/types/table"
import { getColumns } from "./compliance-survey-templates-columns";
import { ComplianceTemplateEditSheet } from "./compliance-template-edit-sheet";
import { DeleteComplianceTemplatesDialog } from "./delete-compliance-templates-dialog";
import { ComplianceSurveyTemplatesToolbarActions } from "./compliance-survey-templates-toolbar";
import { complianceSurveyTemplates } from "@/db/schema/compliance";
import { getFiltersStateParser } from "@/lib/parsers";

interface ComplianceSurveyTemplatesTableProps {
  promises?: Promise<[{ data: typeof complianceSurveyTemplates.$inferSelect[]; pageCount: number }] >;
}

export function ComplianceSurveyTemplatesTable({ promises }: ComplianceSurveyTemplatesTableProps) {
  // 서버에서 받은 데이터 사용
  const paginationData = promises ? React.use(promises) : null;
  const [{ data, pageCount }] = paginationData 
    ? paginationData 
    : [{ data: [], pageCount: 0 }];

  const [rowAction, setRowAction] = React.useState<DataTableRowAction<typeof complianceSurveyTemplates.$inferSelect> | null>(null);

  // 기본 필터 설정 (isActive = true)
  const defaultFilter: Filter<typeof complianceSurveyTemplates.$inferSelect>[] = React.useMemo(() => [
    {
      id: "isActive",
      operator: "eq" as const,
      value: "true",
      type: "select" as const,
      rowId: "default-isActive-filter",
    }
  ], []);

  // URL에서 필터 읽기
  const [filters, setFilters] = useQueryState(
    "filters",
    getFiltersStateParser<typeof complianceSurveyTemplates.$inferSelect>().withDefault([]).withOptions({
      clearOnDefault: true,
      shallow: false,
    })
  );

  // 초기 마운트 시 필터가 없으면 기본 필터 설정
  const hasInitialized = React.useRef(false);
  React.useEffect(() => {
    if (!hasInitialized.current && filters.length === 0) {
      hasInitialized.current = true;
      setFilters(defaultFilter);
    }
  }, [filters.length, setFilters, defaultFilter]);

  // 컬럼 설정 - 외부 파일에서 가져옴
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  // 기본 필터 필드 설정
  const filterFields: DataTableFilterField<typeof complianceSurveyTemplates.$inferSelect>[] = [
    {
      id: "isActive",
      label: "상태",
      options: [
        { label: "활성", value: "true" },
        { label: "비활성", value: "false" },
      ],
    },
  ];

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<typeof complianceSurveyTemplates.$inferSelect>[] = [
    { id: "name", label: "템플릿명", type: "text" },
    {
      id: "isActive", label: "상태", type: "select", options: [
        { label: "활성", value: "true" },
        { label: "비활성", value: "false" },
      ]
    },
    { id: "version", label: "버전", type: "text" },
    { id: "createdAt", label: "생성일", type: "date" },
  ];

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

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

      {/* Edit Sheet */}
      {rowAction?.type === 'update' && rowAction.row && (
        <ComplianceTemplateEditSheet
          template={rowAction.row.original}
          open={true}
          onOpenChange={(open) => {
            if (!open) setRowAction(null);
          }}
        />
      )}

      {/* Delete Dialog */}
      {rowAction?.type === 'delete' && rowAction.row && (
        <DeleteComplianceTemplatesDialog
          templates={[rowAction.row.original]}
          showTrigger={false}
          open={true}
          onOpenChange={(open) => {
            if (!open) setRowAction(null);
          }}
        />
      )}
    </>
  );
}
