"use client"

import * as React from "react"
import type {
  DataTableAdvancedFilterField,
  DataTableFilterField,
  DataTableRowAction,
} from "@/types/table"

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 { getEsgEvaluations } from "../service"
import { getColumns } from "./esg-evaluations-table-columns"
import { EsgEvaluationsTableToolbarActions } from "./esg-evaluations-table-toolbar-actions"
import { EsgEvaluationDetailsSheet } from "./esg-evaluation-details-sheet"
import { EsgEvaluationFormSheet } from "./esg-evaluation-form-sheet"
import { EsgEvaluationBatchDeleteDialog } from "./esg-evaluation-delete-dialog"
import { EsgEvaluationsView } from "@/db/schema"
import { useRouter } from "next/navigation"

interface EsgEvaluationsTableProps {
  promises: Promise<
    [
      Awaited<ReturnType<typeof getEsgEvaluations>>,
    ] 
  >
}

export function EsgEvaluationsTable({ promises }: EsgEvaluationsTableProps) {
  // 1. 데이터 로딩 상태 관리
  const [isLoading, setIsLoading] = React.useState(true)
  const [tableData, setTableData] = React.useState<{
    data: EsgEvaluationsView[]
    pageCount: number
  }>({ data: [], pageCount: 0 })
  const router = useRouter()


  console.log(tableData)
  // 2. 행 액션 상태 관리
  const [rowAction, setRowAction] =
    React.useState<DataTableRowAction<EsgEvaluationsView> | null>(null)

  // 3. 새 평가표 생성 상태 관리
  const [isCreateFormOpen, setIsCreateFormOpen] = React.useState(false)

  // 4. Promise 해결을 useEffect로 처리
  React.useEffect(() => {
    promises
      .then(([result]) => {
        setTableData(result)
        setIsLoading(false)
      })
      // .catch((error) => {
      //   console.error('Failed to load ESG evaluations:', error)
      //   setIsLoading(false)
      // })
  }, [promises])

  // 5. 컬럼 정의
  const columns = React.useMemo(
    () => getColumns({ setRowAction }),
    [setRowAction]
  )

  // 6. 필터 필드 정의
  const filterFields: DataTableFilterField<EsgEvaluationsView>[] = [
    {
      id: "category",
      label: "분류",
      placeholder: "분류 선택...",
    },
    {
      id: "isActive",
      label: "상태",
      placeholder: "상태 선택...",
    },
  ]

  const advancedFilterFields: DataTableAdvancedFilterField<EsgEvaluationsView>[] = [
    {
      id: "serialNumber",
      label: "시리얼번호",
      type: "text",
    },
    {
      id: "category",
      label: "분류",
      type: "text",
    },
    {
      id: "inspectionItem",
      label: "점검항목",
      type: "text",
    },
    {
      id: "totalEvaluationItems",
      label: "평가항목 수",
      type: "number",
    },
    {
      id: "totalAnswerOptions",
      label: "답변옵션 수",
      type: "number",
    },
    {
      id: "maxPossibleScore",
      label: "최대점수",
      type: "number",
    },
    {
      id: "isActive",
      label: "상태",
      type: "select",
      options: [
        { label: "활성", value: "true" },
        { label: "비활성", value: "false" },
      ],
    },
    {
      id: "createdAt",
      label: "생성일",
      type: "date",
    },
    {
      id: "updatedAt",
      label: "수정일",
      type: "date",
    },
  ]

  // 7. 데이터 테이블 설정
  const { table } = useDataTable({
    data: tableData.data,
    columns,
    pageCount: tableData.pageCount,
    filterFields,
    enablePinning: true,
    enableAdvancedFilter: true,
    initialState: {
      sorting: [{ id: "createdAt", desc: true }],
      columnPinning: { left: ["select"], right: ["actions"] },
    },
    getRowId: (originalRow) => String(originalRow.id),
    shallow: false,
    clearOnDefault: true,
  })

  // 8. 데이터 새로고침 함수
  const handleRefresh = React.useCallback(() => {
    setIsLoading(true)
    router.refresh()
  }, [])

  // 9. 새 평가표 생성 성공 핸들러
  const handleCreateSuccess = React.useCallback(() => {
    setIsCreateFormOpen(false)
    handleRefresh()
  }, [handleRefresh])

  // 10. 평가표 수정 성공 핸들러
  const handleEditSuccess = React.useCallback(() => {
    setRowAction(null)
    handleRefresh()
  }, [handleRefresh])

  // 11. 평가표 삭제 성공 핸들러
  const handleDeleteSuccess = React.useCallback(() => {
    setRowAction(null)
    table.resetRowSelection()

    handleRefresh()
  }, [handleRefresh, table])

  // 12. 로딩 상태 표시
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-32">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900"></div>
        <span className="ml-2">ESG 평가표를 불러오는 중...</span>
      </div>
    )
  }

  return (
    <>
      {/* 메인 테이블 */}
      <DataTable table={table}>
        <DataTableAdvancedToolbar
          table={table}
          filterFields={advancedFilterFields}
          shallow={false}
        >
          <EsgEvaluationsTableToolbarActions 
            table={table} 
            onCreateNew={() => setIsCreateFormOpen(true)}
            onRefresh={handleRefresh}
          />
        </DataTableAdvancedToolbar>
      </DataTable>

      {/* 상세보기 시트 */}
      <EsgEvaluationDetailsSheet
        open={rowAction?.type === "view"}
        onOpenChange={() => setRowAction(null)}
        evaluationId={rowAction?.row.original.id ?? null}
      />

      {/* 수정 폼 시트 */}
      <EsgEvaluationFormSheet
        open={rowAction?.type === "update"}
        onOpenChange={() => setRowAction(null)}
        evaluation={rowAction?.row.original ?? null}
        onSuccess={handleEditSuccess}
      />

      {/* 새 평가표 생성 폼 시트 */}
      <EsgEvaluationFormSheet
        open={isCreateFormOpen}
        onOpenChange={setIsCreateFormOpen}
        evaluation={null}
        onSuccess={handleCreateSuccess}
      />

      {/* 삭제 확인 다이얼로그 */}
      <EsgEvaluationBatchDeleteDialog
        open={rowAction?.type === "delete"}
        onOpenChange={() => setRowAction(null)}
        evaluations={rowAction?.row.original ? [rowAction.row.original] : []}
        onSuccess={handleDeleteSuccess}
      />
    </>
  )
}
