"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,
} from "@/types/table"
import { getIntegrationLogs } from "../service";
import { getColumns } from "./integration-log-table-columns";

interface IntegrationLogTableProps {
  promises?: Promise<[{ data: Record<string, unknown>[]; pageCount: number }]>;
}

export function IntegrationLogTable({ promises }: IntegrationLogTableProps) {
  const [rawData, setRawData] = React.useState<{ data: Record<string, unknown>[]; pageCount: number }>({ data: [], pageCount: 0 });

  React.useEffect(() => {
    if (promises) {
      promises.then(([result]) => {
        setRawData(result);
      });
    } else {
      // fallback: 클라이언트에서 직접 fetch (CSR)
      (async () => {
        try {
          const result = await getIntegrationLogs({
            page: 1,
            perPage: 10,
            search: "",
            sort: [{ id: "executionTime", desc: true }],
            filters: [],
            joinOperator: "and",
            flags: ["advancedTable"],
            status: "",
            errorMessage: "",
            requestUrl: "",
            requestMethod: "",
          });
          setRawData(result);
        } catch (error) {
          console.error("Error refreshing data:", error);
        }
      })();
    }
  }, [promises]);



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

  // 고급 필터 필드 설정
  const advancedFilterFields: DataTableAdvancedFilterField<Record<string, unknown>>[] = [
    { id: "name", label: "통합명", type: "text" },
    { id: "type", label: "타입", type: "select", options: [
      { label: "REST API", value: "rest_api" },
      { label: "SOAP", value: "soap" },
      { label: "DB to DB", value: "db_to_db" },
    ]},
    { id: "status", label: "상태", type: "select", options: [
      { label: "성공", value: "success" },
      { label: "실패", value: "failed" },
      { label: "타임아웃", value: "timeout" },
      { label: "대기중", value: "pending" },
    ]},
    { id: "requestMethod", label: "메서드", type: "select", options: [
      { label: "GET", value: "GET" },
      { label: "POST", value: "POST" },
      { label: "PUT", value: "PUT" },
      { label: "DELETE", value: "DELETE" },
    ]},
    { id: "httpStatusCode", label: "HTTP 상태코드", type: "number" },
    { id: "responseTime", label: "응답시간", type: "number" },
    { id: "executionTime", label: "실행시간", type: "date" },
  ];

  const { table } = useDataTable({
      data: rawData.data,
      columns,
      pageCount: rawData.pageCount,
      enablePinning: true,
      enableAdvancedFilter: true,
      initialState: {
        sorting: [{ id: "executionTime", desc: true }],
      },
      getRowId: (originalRow) => String(originalRow.id),
      shallow: false,
      clearOnDefault: true,
    })

  return (
    <>
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
        >
          <div className="flex items-center gap-2">
            <span className="text-sm text-muted-foreground">
              총 {rawData.data.length}개의 이력
            </span>
          </div>
        </DataTableAdvancedToolbar>
      </DataTable>
    </>
  );
} 